Led Toggle Problem

Hi, I'm having a bit of difficulty trying to get some code to work. Any help would be appreciated.

I am trying to make some code with 4 digital inputs, where all digital input need to be low first and then at least one has to be turned on to light an LED. This is what i have got so far:

int ButtonState1 = 0;
int ButtonState2 = 0;
int ButtonState3 = 0;
int ButtonState4 = 0;

const int LedPin = 3;
const int InPin = 2;
void setup(){
pinmode(LedPin, OUTPUT);
pinmode(InPin, INPUT);
void loop(){  
ButtonState1 = digitalRead(4);
ButtonState2 = digitalRead(5);
ButtonState3 = digitalRead(6);
ButtonState4 = digitalRead(7);
in = digitalRead(InPin
if(in = TRUE){
    digitalWrite(LedPin, HIGH);
    Trigger1 = 1;
    Trigger2 = 1;
  }
  while(Trigger1 == 1){
    if(ButtonState1 == 0 && ButtonState2 == 0 && ButtonState3 == 0 && ButtonState4 == 0){
    Trigger1 = 0;
    }
    while(Trigger2 == 1){
      if(ButtonState1 == 1 || ButtonState2 == 1 || ButtonState3 == 1 || ButtonState4 == 1){
        Trigger2 = 0;
        digitalWrite(LedPin, LOW);
      }
    }
  }

Hello
What are your troubles? What do you expect ?

I am making a 4 digit combination lock and i want the Led output to toggle on when the combination is correct and then toggle of when any button on the keypad (only 4 numbers in this case) is pressed.

nice

But I can't seem to get the code to work, I've been trying for an hour, making small adjustments but it doesn't seem to make a difference.

consider
but you didn't specify the pins for all the buttons and the code is missing some braces

#undef MyHW
#ifdef MyHW
byte pinsLed [] = { 10, 11, 12 };
byte pinsBut [] = { A1, A2, A3 };
#else
byte pinsLed [] = { 3 };
byte pinsBut [] = { 2, A1, A2, A3, A4 };
#endif

#define N_BUT   sizeof(pinsBut)

enum { Off = HIGH, On = LOW };

byte butState [N_BUT];

int  Trigger1 = 0;
int  Trigger2 = 0;

// -----------------------------------------------------------------------------
void
readButtons (void)
{
    for (unsigned n = 0; n < sizeof(pinsBut); n++)
        butState [n] = digitalRead (pinsBut [n]);
}

// -----------------------------------------------------------------------------
void
loop ()
{
    readButtons ();

    if (LOW == butState [0])  {
        digitalWrite (pinsLed [0], On);

        Trigger1 = 1;
        Trigger2 = 1;
    }

    while (Trigger1 == 1)  {
        readButtons ();

        int state = 0;
        for (unsigned n = 1; n < sizeof(pinsBut); n++)  {
            state |= butState [n];
        }

        if (0 == state)  {
            Trigger1 = 0;
        }
    }

    while (Trigger2 == 1){
        readButtons ();

        int state = 0;
        for (unsigned n = 1; n < sizeof(pinsBut); n++) {
            state |= butState [n];
        }

        if (1 == state)  {
            Trigger2 = 0;
            digitalWrite (pinsLed [0], Off);
        }
    }
}

// -----------------------------------------------------------------------------
void
setup ()
{
    Serial.begin (9600);

    for (unsigned n = 0; n < sizeof(pinsBut); n++)  {
        pinMode (pinsBut [n], INPUT_PULLUP);
        butState [n] = digitalRead (pinsBut [n]);
    }

    for (unsigned n = 0; n < sizeof(pinsLed); n++)  {
        digitalWrite (pinsLed [n], Off);
        pinMode      (pinsLed [n], OUTPUT);
    }
}

What do you mean when you say I didn't specify the pins for the buttons? I have four buttons each representing a number (1, 2, 3, 4) , four digits (1 digit is either 1, 2, 3 or 4) and one led which signifies if the code is correct. this is my full code:

const int LedPin = 6;
const int Button1 = 2;
const int Button2 = 3;
const int Button3 = 4;
const int Button4 = 5;
int Correct = 0;
int ButtonCount = 0;
int ButtonState1 = 0;
int ButtonState2 = 0;
int ButtonState3 = 0;
int ButtonState4 = 0;
int LastButtonState1 = 0;
int LastButtonState2 = 0;
int LastButtonState3 = 0;
int LastButtonState4 = 0;
void setup() {
  pinMode(LedPin, OUTPUT);
  pinMode(Button1, INPUT);
  pinMode(Button2, INPUT);
  pinMode(Button3, INPUT);
  pinMode(Button4, INPUT);
  Serial.begin(9600);
}
void loop() {
  Serial.println(ButtonCount);
  ButtonState1 = digitalRead(Button1);
  ButtonState2 = digitalRead(Button2);
  ButtonState3 = digitalRead(Button3);
  ButtonState4 = digitalRead(Button4);
  if(ButtonState1 != LastButtonState1){
    if(ButtonState1 == 1) {
      if(ButtonCount == 2){
        Correct = 3;
        ButtonCount = 3;
      }
      else{
        Correct = 0;
        ButtonCount = 0;
      }
    }
  }
  LastButtonState1 = ButtonState1;
  if(ButtonState2 != LastButtonState2){
    if(ButtonState2 == 1) {
      if(ButtonCount == 0){
        Correct = 1;
        ButtonCount = 1;
      }
      else{
        Correct = 0;
        ButtonCount = 0;
      }
    }
  }
  LastButtonState2 = ButtonState2;
  if(ButtonState3 != LastButtonState3){
    if(ButtonState3 == 1) {
      if(ButtonCount == 1 || ButtonCount == 3){
        Correct = Correct + 1;
        ButtonCount = ButtonCount + 1;
      }
      else{
        Correct = 0;
        ButtonCount = 0;
      }
    }
  }
  LastButtonState3 = ButtonState3;
  if(ButtonState4 != LastButtonState4){
    if (ButtonState4 == 1) {
      Correct = 0;
      ButtonCount = 0;
    }
  }
  if(Correct == 4){
    digitalWrite(LedPin, HIGH);
    delay(1000);
    digitalWrite(LedPin, LOW);
    }
  }
  delay(500);
}

But instead of the led blinking when the code is correct I would like it to toggle on until any of the four buttons is pressed, and then it will start taking in passcodes again.

Hi @awesomechapro
Try this sketch:

RV mineirin

const int LedPin = 13;
const int Button1 = 2;
const int Button2 = 3;
const int Button3 = 4;
const int Button4 = 5;
int Correct = 0;
int Trigger1 = 0;
int Trigger2 = 0;
int ButtonCount = 0;
int ButtonState1 = 0;
int ButtonState2 = 0;
int ButtonState3 = 0;
int ButtonState4 = 0;
int LastButtonState1 = 0;
int LastButtonState2 = 0;
int LastButtonState3 = 0;
int LastButtonState4 = 0;
//-----------------------------------------------------
void setup() {
  pinMode(LedPin, OUTPUT);
  pinMode(Button1, INPUT);
  pinMode(Button2, INPUT);
  pinMode(Button3, INPUT);
  pinMode(Button4, INPUT);
  Serial.begin(9600);
}
//-------------------------------------------------------
void readMyButton()
{
  ButtonState1 = digitalRead(Button1);                // Read all buttons
  ButtonState2 = digitalRead(Button2);
  ButtonState3 = digitalRead(Button3);
  ButtonState4 = digitalRead(Button4);
}
//-------------------------------------------------------
void loop() {
  Serial.println(ButtonCount);
  readMyButton();
  if (Correct == 4)
  {
    digitalWrite(LedPin, HIGH);
    Trigger1 = 1;
    Trigger2 = 1;
  }

  if (ButtonState1 != LastButtonState1)               // If button 1 is difereente of last1
  {
    if (ButtonState1 == 1)                            // If button 1  is HIGH
    {
      if (ButtonCount == 2)                           // Sequence 2
      {
        Correct = 3;                                  //
        ButtonCount = 3;                              // Sequence 3
      }
      else                                            // Not is 1st time
      {
        Correct = 0;                                  // Corret OK
        ButtonCount = 0;                              //  ??
      }
    }
  }
  LastButtonState1 = ButtonState1;

  if (ButtonState2 != LastButtonState2)               // If button 2 is difereente of last2
  {
    if (ButtonState2 == 1)                            // If button 2  is HIGH
    {
      if (ButtonCount == 0)                           // Sequence 0
      {
        Correct = 1;                                  // Sequence 3 ??
        ButtonCount = 1;
      }
      else
      {
        Correct = 0;                                    // Corret OK
        ButtonCount = 0;
      }
    }
  }
  LastButtonState2 = ButtonState2;

  if (ButtonState3 != LastButtonState3)                 // If button 3 is difereente of last3
  {
    if (ButtonState3 == 1)                              // If button 2  is HIGH
    {
      if (ButtonCount == 1 || ButtonCount == 3)
      {
        Correct = Correct + 1;
        ButtonCount = ButtonCount + 1;
      }
      else
      {
        Correct = 0;                                    // Corret OK
        ButtonCount = 0;
      }
    }
  }
  LastButtonState3 = ButtonState3;

  if (ButtonState4 != LastButtonState4)                 // If button 4 is difereente of last4
  {
    if (ButtonState4 == 1)                              // If button 2  is HIGH
    {
      Correct = 0;                                      // Corret OK
      ButtonCount = 0;
    }
  }

  while (Trigger1 == 1)
  {
    if (ButtonState1 == 0 && ButtonState2 == 0 && ButtonState3 == 0 && ButtonState4 == 0)
    {
      Trigger1 = 0;
    }
    while (Trigger2 == 1)
    {
      readMyButton();
      if (ButtonState1 == 1 || ButtonState2 == 1 || ButtonState3 == 1 || ButtonState4 == 1)
      {
        Trigger2 = 0;
        digitalWrite(LedPin, LOW);
        Correct = 0; 
        ButtonCount = 0;
      }
    }
  }
  delay(500);
}

not in the code you posted originally !!!!!!!!!!!!!

This sounds EXACTLY like the project another recent newcomer wanted solved. This is what I came up with.

const byte SwitchCount = 3;  // Note: If this goes above 16, increase the pattern size

const byte SwitchPins[SwitchCount] = {2, 3, 4};
const byte LEDPins[SwitchCount] = {11, 12, 13};
const byte BINGOPin = 8;

int SwitchValues[SwitchCount];

// Note: Not all switches have to be on at the end of the pattern
const byte ValidOrder[] = {3, 1, 2};  // Note: Subtract 1 to get bit index.
const byte OrderCount = sizeof ValidOrder / sizeof ValidOrder[0];  // Number of switches in pattern

const byte PatternCount = OrderCount + 1;  // Add one for the empty pattern
unsigned int ValidPatterns[PatternCount];

unsigned int LastPattern = 0;

void setup()
{
  Serial.begin(9600);
  for (int i = 0; i < SwitchCount; i++)
  {
    pinMode(SwitchPins[i], INPUT);
    pinMode(LEDPins[i], OUTPUT);
  }

  // Generate the list of valid patterns
  unsigned int pattern = 0;
  ValidPatterns[0] = pattern;  // The empty pattern
  for (int i = 0; i < OrderCount; i++)
  {
    pattern |= 1 << (ValidOrder[i] - 1);
    ValidPatterns[i + 1] = pattern;
  }
}

void loop()
{
  unsigned int pattern = 0;

  for (int i = 0; i < SwitchCount; i++)
  {
    SwitchValues[i] = digitalRead(SwitchPins[i]);
    digitalWrite(LEDPins[i], SwitchValues[i]);
    pattern |=  SwitchValues[i] << i;
  }

  // Examine the pattern if it has changed
  if (pattern != LastPattern)
  {
    LastPattern = pattern;
    Serial.print("New pattern: ");
    Serial.println(pattern, BIN);

    boolean isValid = false;
    byte validIndex = 0;
    for (int i = 0; i < PatternCount; i++)
    {
      if (pattern == ValidPatterns[i])
      {
        isValid = true;
        validIndex = i;
      }
    }

    if (isValid)
    {
      Serial.print("Valid Pattern.  Match at step ");
      Serial.println(validIndex);
      if (validIndex == PatternCount - 1)
      {
        Serial.println("FULL MATCH.  OPEN THE LOCK.");
      }
    }
    else // not valid
    {
      Serial.println("INVQALID PATTERN.  SOUND THE ALARM!");
    }
  }
}

I tried the code, but was a bit confused why there's three led pins, how i change the passcode and what pins i should connect the buttons to.

Their requirement was one LED per switch. Feel free to remove that feature. They are also using toggle switches for their combination so that sketch may not be of much use.

const byte ValidOrder[] = {3, 1, 2};

const byte SwitchPins[SwitchCount] = {2, 3, 4};

Yeah I was gonna try and stick with momentary buttons for the project. The code I wrote works fine and the led blinks when the code is correct. I just want the output to latch on until any button is pressed. I did try @ruilviana's code but the arduino just seemed to not turn the led on at all and it got stuck in one of the loops. I am mainly looking for a couple lines of code I can put instead of the lines that makes the led blink if the code is correct at the end of my code to make it do as I want.

Hi,
How have you got your buttons wired?
Between 5V and digital input pin, with 10K resistor from digital input to gnd.
OR
Between gnd and digital input pin, with 10K resistor from digital input to 5V.

What model Arduino are you using?

Thanks.. Tom.. :smiley: :+1: :coffee: :australia:
PS, Give each button a binary value, 1, 2, 4 , 8. Then you only need to store a single number as the password, as all you do is add the true inputs together. Only ONE combination will be valid.

Hi @awesomechapro
Sorry, my mistake.
You use the LED on pin 6, but when testing the sketch I changed it to 13 and posted the scketch as LED on pin 13.

RV mineirin

i had realised that and swapped it but it still didn't do anything for some reason

@TomGeorge The buttons are connected to +5V with the digital pins pulled low through a 10K resistor, and i am using an arduino nano but hoping to eventually use an attiny85. :australia:

should I attempt writing code with edge detection in it? would that be the way to do it?

When dealing with mechanical buttons you almost always need State Change Detection and Debounce. Here is a sketch that does both on multiple buttons:

const byte ButtonCount = 3;
const byte ButtonPins[ButtonCount] = {2, 3, 4};

const unsigned long DebounceTime = 30;
boolean ButtonWasPressed[ButtonCount];  // Defaults to 'false'
unsigned long ButtonStateChangeTime = 0; // Debounce timer common to all buttons

void setup()
{
  Serial.begin(115200);

  for (byte i = 0; i < ButtonCount; i++)
  {
    pinMode (ButtonPins[i], INPUT_PULLUP);  // Button between Pin and Ground
  }
}

void loop()
{
  checkButtons();
}

void checkButtons()
{
  unsigned long currentTime = millis();

  // Update the buttons
  for (byte i = 0; i < ButtonCount; i++)
  {
    boolean buttonIsPressed = digitalRead(ButtonPins[i]) == LOW;  // Active LOW

    // Check for button state change and do debounce
    if (buttonIsPressed != ButtonWasPressed[i] &&
        currentTime - ButtonStateChangeTime > DebounceTime)
    {
      // Button state has changed
      ButtonStateChangeTime = currentTime;
      ButtonWasPressed[i] = buttonIsPressed;
      if (ButtonWasPressed[i])
      {
        // Button i was just pressed
      }
      else
      {
        // Button i was just released
      }
    }
  }
}
1 Like

I think i may have found a way to do it, its not the best way but it works. Thanks for all the help though. :smiley: