Home > Mobile >  arduino on / off NON momentary switch implementation assistance
arduino on / off NON momentary switch implementation assistance

Time:11-07

I am new to programming and Arduino. Board - ESP8266 Nodemcu pinout as below,

enter image description here

What I am trying to achieve is send a command based LOW/HIGH value from pin 0. A two leg switch's one leg is connected to D3 (GPIO0 and in program 0) and other to ground.

The code I am trying is below,

#include<BitsAndDroidsFlightConnector.h>

BitsAndDroidsFlightConnector connector = BitsAndDroidsFlightConnector();

const byte exampleButtonA = 0;

void setup() {
  Serial.begin(115200);
  pinMode(exampleButtonA, INPUT_PULLUP);
}

void loop() {
   byte exampleButtonAvalue = digitalRead(exampleButtonA);   
   switch(exampleButtonAvalue)
    {
      case LOW:
        Serial.println("ON IT IS");
        break;
      case HIGH:
        Serial.println("OFF IT IS");
        break;
      default:
        Serial.println("error!");
        break;
    } 
}

Issue I am facing is, when I flash this program, Based on physical switch on or off It continually prints either "ON IT IS" or "OFF IT IS" The break is really not happening. I only want it to execute once.

I also tried this with if else and face same problem of repeated printing.

#include<BitsAndDroidsFlightConnector.h>

BitsAndDroidsFlightConnector connector = BitsAndDroidsFlightConnector();

const byte exampleButtonA = 0;

void setup() {
  Serial.begin(115200);
  pinMode(exampleButtonA, INPUT_PULLUP);
}

void loop() {
   if(digitalRead(exampleButtonA) == LOW){
    Serial.println("ON");
    delay(200);
   }
  else {
   Serial.println("OFF");   
   delay(200);
  } 
}

Any assistance?

CodePudding user response:

If you want to see message only once you need to write youre code in setup() section. All code in loop() section is repeated in loop.

Replace you code with this:

#include<BitsAndDroidsFlightConnector.h>

BitsAndDroidsFlightConnector connector = BitsAndDroidsFlightConnector();

const byte exampleButtonA = 0;
int exampleButtonAvalue = 0;
int saved_exampleButtonAvalue = 0;

void setup() {
  Serial.begin(115200);
  pinMode(exampleButtonA, INPUT_PULLUP);

}

void loop() {
    exampleButtonAvalue = digitalRead(exampleButtonA); 

    if (exampleButtonAvalue != saved_exampleButtonAvalue){
        if(exampleButtonAvalue == LOW){
            Serial.println("ON");
        } else {
            Serial.println("OFF");   
        }
        saved_exampleButtonAvalue = exampleButtonAvalue;
    }

    delay(200);
}

  • Related