Coding a toggle solution for switch and LEDs

Hi,

I'm using this switch which has connections NO, NC,COM, GND, V+. When the switch is on it illuminates blue and when depressed is green and released it again is blue.

My objective is when the switch is pressed my code will remember the state of the button and change the colour of an LED. So initial state the LED would be red and when the switch is pressed it would illuminate green until the switch is pressed again. I'm trying to develop a toggling type solution in my code but its not having the desired effect. It normally shows red and on occasion shows green.

Any ideas?

Here's my code:

    // Define Pins
    #define BLUE 25
    #define GREEN 23
    #define RED 27
 
    // Other Global Constants 
    int oldButtonState = 0;
    int buttonState = 0;
    bool toggle = false;

void setup() {
  // Initiating
    Serial.begin(9600);                     // Start the serial monitor

    pinMode(RED, OUTPUT);
    pinMode(GREEN, OUTPUT);
    
    digitalWrite(RED, HIGH);
    digitalWrite(GREEN, LOW);
   
    //Exit switch
    pinMode(45, INPUT_PULLUP); //pin 45 - COM
    pinMode(47, OUTPUT);  //pin 47 - NC, NO - GND
}


void loop() {

    //oldButtonState = LOW; 
    buttonState = digitalRead(45);

  //  if the button just became pressed...
  if(buttonState == HIGH && oldButtonState==LOW){
    toggle = !toggle;  // same thing, toggle our variable. 
     //delay(200);
  }

  oldButtonState = buttonState;  // save the button state for next time


  if (toggle) {
        digitalWrite(47, HIGH);
        
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, HIGH);
        //openLock();
        Serial.println("HIGH");
       // delay(2000);
  } else {
      digitalWrite(47, LOW);
      
      digitalWrite(RED, HIGH);
      digitalWrite(GREEN, LOW);
      
      //closeLock();
      Serial.println("LOW");
     // delay(2000);
  }
}

My state change detection for active low inputs may be of interest.

A demo program for toggling the state of a variable.

// by C Goulding aka groundFungus

const byte  buttonPin = 2;    // the pin to which the pushbutton is attached
const byte ledPin = 13;       // the pin to which the LED is attached

bool buttonState = 0;         // current state of the button
bool lastButtonState = 0;     // previous state of the button

bool mode = false;

void setup()
{
   // initialize the button pin as a input with internal pullup enabled
   pinMode(buttonPin, INPUT_PULLUP);
   // initialize the LED as an output:
   pinMode(ledPin, OUTPUT);
   // initialize serial communication:
   Serial.begin(115200);
   Serial.println("Select mode with push button");
}

void loop()
{
   static unsigned long timer = 0;
   unsigned long interval = 50;  // check switch 20 times per second
   if (millis() - timer >= interval)
   {
      timer = millis();
      // read the pushbutton input pin:
      buttonState = digitalRead(buttonPin);
      // compare the new buttonState to its previous state
      if (buttonState != lastButtonState)
      {
         if (buttonState == LOW)
         {
            // if the current state is LOW then the button
            // went from off to on:
            digitalWrite(ledPin, !digitalRead(ledPin)); // toggle the output
            mode = !mode;
            if (mode == true)
            {
               Serial.println("Manual mode\n");
            }
            else
            {
               Serial.println("Scan mode\n");
            }
         }
      }
      // save the current state as the last state,
      //for next time through the loop
      lastButtonState = buttonState;
   }
}
1 Like

switch wiring

1 Like

Nice one, thank you. My code was fairly close, I've removed your timer condition though. I've now got a bit further and when I press the button a stepper motor runs and the LED colour changes. Getting there :slight_smile: Thank you very much for your help!

May I ask why?

I've put it back now, although it hasn't resolved a problem I have. I have two ways of switching the LED and stepper motor on, one via the switch and the other via an RFID reader. The issue is that operating the switch doesn't always register, I have no delays in my code and I can't see anything that would prevent it from registering operation of the switch. Took the timer thinking that was the issue.

We may be able to help if you post a circuit diagram and latest code.

The switch info from Amazon is... amusing. Read it, came away knowing less than I thought I knew before I went there. Utter rubbish.
Is it momentary, continuous, NC, NO, what's the power hookup, none of that is clarified properly in the sales page.

Can you post a link to the page, please?
Never mind.

no need. post #1, words 3 and 4.

Thanks. I did miss that. I claim old eyes and cell phone screen.

1 Like

No big deal, the page won't help much. Good luck, I don't think I've seen a worse description on Amazon, though it pales in comparison with the rubbish on Ali Express.

Your topic has been moved to a more suitable location on the forum. I do not quite see how this relates to "Interfacing w/ Software on the Computer" :wink:

Yeah, I was thinking it was the switch, I've ordered something else, I'll give that a go. If it works my circuit, in my amateur assessment, is looking good :wink:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.