Hi all,
First, thank you all, for this forum and all the tips I've found so far without even having to setup an account ! but on this on, I'm really stuck so I'm calling for help ![]()
I have a traffic light (a real one!) connected to an arduino. I'm working on different functions to turn off and on the 3 lights :
- STATE1 = 3 lights always ON
- STATE2 = each light is ON for 3 sec
- STATE3 = each light is ON when the low, mid or high frequency is above average (I have a microphone connected to it and I do the FFT of its output analog signal)
These 3 functions work perfectly but I would like to switch between each other with a button. I went through a lot of tutorials, but not so many are studying the case of more than 2 cases. And I can't find the right algorithm to do the following.
Initial state : all lights ON (STATE1)
STATE1 run
Press button -> switch to STATE2
STATE2 run
Press button -> switch to STATE3
STATE3 run
Press button -> switch to STATE1
STATE 1 run
etc...
Here is the beginning of code I took from here and I modified to fit my problem. But I didn't go too far because I really don't see how to set this up. So the code doesn't work.
My main issues are the following :
- I don't see how to make different cases similar to what is written in the project I took the code from
- With STATE2 running during 9 sec, how can I switch to STATE3 ? Can the Arduino remember that I pressed the button and switch state at the end of STATE2 ?
- How can my initial state (in my code) can also be STATE1 ?
Some help would be more than appreciated !
Cheers
const int state=0;
const int buttonPin = 2;  // the pin that the pushbutton is attached to
int previousState = LOW;Â // the previous reading from the input pin
unsigned long lastDebounceTime = 0;Â // the last time the output pin was toggled
unsigned long debounceDelay = 50;
void setup()
{
  pinMode(12, OUTPUT); // the three lights
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP); //connect to 20Kohm internal resistance and 5V
}
void loop (){
  // Initial state
  digitalWrite(12, HIGH);
  digitalWrite(11, HIGH);
  digitalWrite(10, HIGH);
  int reading = digitalRead(buttonPin);
  if (reading == HIGH && previousState == LOW && millis() - lastDebounceTime > debounceDelay)
  {
    digitalWrite(12, HIGH);
    delay(3000);
    digitalWrite(12, LOW);
    digitalWrite(11, HIGH);
    delay(3000);
    digitalWrite(11, LOW);
    digitalWrite(10, HIGH);
    delay(3000);
    digitalWrite(10, LOW);
  state++;
  }