Go Down

Topic: Sequence leds and button to activate a counter. (Read 1 time) previous topic - next topic

dotgridline

Hi ther, I have 5 leds connected to a protoboard and also, one button. I tested this code several times, each time with a function alone. Alone, they all work. But when I try to mix them, it doesn't work. What I need is: I need the 5 leds to light on and off in sequence, and then I need the user to push the button when only the red one, the third, is on. If he do it, I just need to add a ++ to the counter.

Can someone help me, please?

All the connections are right and all the positions in the arduino too.

Code: [Select]

const int buttonOrange = 2;
const int ledOne  = 13;
const int ledTwo  = 12;
const int ledRed  = 11;
const int ledFour = 10;
const int ledFive = 9;         

// Array of Pins
int ledPins[] = {            // an array of variables refering pin numbers to which LEDs are attached
  ledOne,
  ledTwo,
  ledRed,
  ledFour,
  ledFive
};   
         
int delayTime = 400;
int clickCounter = 0;
int buttonState = 0;
int ledState = 0;
int lastButtonState = 0;

void setup() {
  for (int currentPin = 0; currentPin <= 5; currentPin++)  {
    pinMode(ledPins[currentPin], OUTPUT);
  }
  pinMode(buttonOrange, INPUT);

  Serial.begin(9600);
}

void loop(){
  buttonState = digitalRead(buttonOrange);
  ledState = digitalRead(ledRed);

  for(int i = 0; i <= 5; i++){
    int offLED = i - 1; 
      if(i == 0) {         
        offLED = 5;       
      }

      if (buttonState != lastButtonState) {
        if(buttonState == HIGH && ledRed == HIGH){
          clickCounter++;
          Serial.println(clickCounter);
        }
      }
   
    lastButtonState = buttonState;                   
    digitalWrite(ledPins[i], HIGH);   
    digitalWrite(ledPins[offLED], LOW);
    delay(delayTime);
  } 
}



AiRgeek

It would be easier for others to read and understand your code, if you comment your code more to explain the control flow and purpose of variables.

Go Up