简体   繁体   中英

Press twice or more to turn off, once to turn on

I'm trying to make this sensor in ESP32, and I can't figure out what am I missing or if I did something wrong, I think I could use a relay module to make it easier, but the task implies that I only use basic code like if, while, etc. The thing is that I need to press twice in a short amount of time (1 or 2 seconds) while it is on to turn it off, and if it is off, just press once and it will turn on. I can't figure out how to make the sensor to stop, since it keeps giving signals. It should work like: when someone goes closer than 30cm to the sensor, the red LED blink, if not the green LED is always on. I need to put in a button that turns off and on this device.

I tried to create a parameter that tells if it is on or off, but I can't make it work, I can not figure out why tho.

`#include <Arduino.h>
    #define trigger 27
#define echo 14
#define ledrojo 4
#define ledverde 5
#define BOTON 13
float distancia = 0;
unsigned long ta = 0;
unsigned long tiempo_capturado_inicio = 0;
unsigned long tiempo_pulsado = 0;
int pulsos = 0;
int estadosistema = 0;
byte aux_boton = 0;
byte aux_inicio = 0;

void setup()
{
  Serial.begin(9600);
  // El numero serial para la comunicacion serial
  pinMode(BOTON, INPUT_PULLUP);
  estadosistema = 0;
}

void loop()
{
  if (!digitalRead(BOTON)) // Cuando se presione el boton
  {
    while (!digitalRead(BOTON))
    {
    }                      // Mientras mantengo el boton presionado, no pasara nada
    aux_inicio = 1;        // Con esto enciendo el temporizador
    aux_boton = 1;         // Con esto comienza el contador
    if (estadosistema = 1) // Si el sistema esta encendido sucedera:
    {
      if (aux_inicio = 1)
      {
        if (millis() - tiempo_pulsado >= 4000) // Tiempo maximo para dar el segundo pulso es 1 segundo
        {
          aux_inicio = 0; // Apagar el temporizador
          aux_boton = 0;  // Apagar el contador
        }
        if (!digitalRead(BOTON))
        {
          aux_boton = 1; // Mantener el contador encendido
        }
        if (aux_boton = 1 && !digitalRead(BOTON)) // Conteo de pulsos
        {
          pulsos += 1;
          aux_boton = 0;
        }
      }
      if (aux_inicio = 0) // Cuando el temporizador termina, se contea los pulsos
      {
        if (pulsos >= 1) // Si se pulso una segunda vez o mas, el sistema se apagara
        {
          estadosistema = 0;
          pulsos = 0;
          aux_boton = 0;
          aux_inicio = 0;
          Serial.print("Se ha apagado el sistema de alarma");
        }
        else
        { // Si solo se presiono una vez, el sistema seguira encendido
          Serial.print("El sistema de alarma sigue encedido");
        }
      }
    }
    if (estadosistema = 0) // Si el sistema esta apagado sucedera:
    {
      estadosistema = 1; // Se enciende el sistema
      delay(1000);
      aux_boton = 0;
      aux_inicio = 0;
      Serial.print("El sistema de alarma se ha encendido");
    }
  }
  if (estadosistema = 0) // Mientras el sistema esta apagado
  {
    distancia = 1000000000000000;
    digitalWrite(trigger,LOW);
    digitalWrite(echo,LOW);
  }
  if (estadosistema = 1)
  {
    pinMode(echo, INPUT);
    // Esto es para recibir la informacion del echo del sensor ultrasonico
    pinMode(trigger, OUTPUT);
    // Esto es lo que provocara una señal en el sistema serial
    pinMode(ledrojo, OUTPUT);
    // Este es el led rojo que se usara cuando haya peligro
    pinMode(ledverde, OUTPUT);
    // Este es el led verde que se usara cuando no haya peligro
    digitalWrite(trigger, HIGH); // Prendemos el trigger
    delayMicroseconds(10);
    digitalWrite(trigger, LOW); // Apagamos el trigger

    ta = pulseIn(echo, HIGH); // Tiempo que demora en llegar la señal al Echo
    ta = ta / 2;
    distancia = ta / 29; // Distancia hasta el obstaculo
    if (distancia <= 30)
    {
      digitalWrite(ledrojo, HIGH);          // Prendemos el LED rojo
      digitalWrite(ledverde, LOW);          // Apagamos el LED verde
      Serial.print("¡PELIGRO, RETROCEDA!"); // Mensaje de que una persona esta en la zona de peligro
      delay(5);
      Serial.print("");
      digitalWrite(ledrojo, LOW); // Hacemos que parpadee a 100Hz
      delay(5);
    }
    else
    {
      digitalWrite(ledverde, HIGH);
      digitalWrite(ledrojo, LOW);
    }
  }
}
`

use easyButtton library (look at https://github.com/evert-arias/EasyButton )

try this sketch (may need some fix - not tested)

#include <EasyButton.h>

//syntax EasyButton button(BUTTON_PIN, debounce, pullup, invert);
EasyButton button(BOTON, 10, true, false);
boolean sensor_on;
#define trigger 27
#define echo 14
#define ledrojo 4
#define ledverde 5
#define BOTON 13

void setup()
{
  Serial.begin(9600);
  // El numero serial para la comunicacion serial
  pinMode(BOTON, INPUT_PULLUP);

  button.begin();
  button.onPressed(buttonPressed);              //single press
  button.onSequence(2, 500, sequenceEllapsed);  //2 press in 500mS - change value if needed
  
  if (button.supportsInterrupt())
  {
    button.enableInterrupt(buttonISR);
    wifi.sendNow("Button will be used through interrupts");
  }
  
}
  
void loop() {

//button.read(); //remove comment if button don't work by interrupt

if(sensor_on) {  //1 press
  if(get_distance() < 30) { 
   blink_red_led();             //red led blink
   digitalWrite(ledverde, LOW); //green led off
   } else {
   digitalWrite(ledverde, HIGH);//green led on
   digitalWrite(ledrojo,LOW);   //red led off
   } 
  } else {  //no measure and set all leds off
   digitalWrite(ledverde, LOW);
   digitalWrite(ledrojo,LOW);
  }
}

ICACHE_RAM_ATTR void buttonISR() {
  button.read();
}
    
void buttonPressed() {
sensor_on=true;
}

void sequenceEllapsed() {
sensor_on=false;
}

unsigned long get_distance() {
 digitalWrite(trigger, HIGH); // Prendemos el trigger
 delayMicroseconds(10);
 digitalWrite(trigger, LOW); // Apagamos el trigger
 
 unsigned long ta = pulseIn(echo, HIGH); // Tiempo que demora en llegar la señal al Echo
 ta = ta / 2;
 return(ta / 29); // Distancia hasta el obstaculo
}  

void blink_red_led() {
 digitalWrite(ledverde, LOW);
 digitalWrite(ledrojo, !digitalRead(ledrojo);
 delay(200);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM