Hi there.
I'm pretty new to the Arduino. I'm trying to put together a traffic light simulation.
I used states to go through the different phases. The simulation works fine inside the loop. Now I'm trying to integrate a button to interrupt the defined sequence. The button is wired with a pulldown resistor.
I have 3 traffic lights which simulate traffic North/South, East/West and pedestrians. The loop let's them also go in that order. (pins 13, 10 & 7 are red)
The idea: If the light is green for north/south I want to be able to hit the button for pedestrians and the program shall do following: switch the state to the curren one it's in (green N/S or state 2 in the code) and then apply the delay related to it. Then it should go to state 3 (switch N/S to yellow) apply the delay. Then I suppose it should switch to state 8 (all red before pedestrians green) and jump back into the loop.
How can I make that happen? I've tried the following but what happens is that it always jumps to the pedestrian even if I don't push the button. So somehow it's getting the signal HIGH anyway from that button...?
// C++ code
//
const int ledPins[9] = {13, 12, 11, 10, 9, 8, 7, 6, 5};
const int bNSPin = 4;
const int bEWPin = 1;
const int bPPin = 0;
int bNSState = 0;
int bEWState = 0;
int bPState = 0;
int test[2][11] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1}, // testate 0
{0, 0, 0, 0, 0, 0, 0, 0, 0}, // testate 1
};
int mytestate = 0;
int phase[11][9] = {
{1, 0, 0, 1, 0, 0, 1, 0, 0}, // state 0
{1, 1, 0, 1, 0, 0, 1, 0, 0}, // state 1
{0, 0, 1, 1, 0, 0, 1, 0, 0}, // state 2
{0, 1, 0, 1, 0, 0, 1, 0, 0}, // state 3
{1, 0, 0, 1, 0, 0, 1, 0, 0}, // state 4
{1, 0, 0, 1, 1, 0, 1, 0, 0}, // state 5
{1, 0, 0, 0, 0, 1, 1, 0, 0}, // state 6
{1, 0, 0, 0, 1, 0, 1, 0, 0}, // state 7
{1, 0, 0, 1, 0, 0, 1, 0, 0}, // state 8
{1, 0, 0, 1, 0, 0, 0, 0, 1}, // state 9
{1, 0, 0, 1, 0, 0, 0, 1, 0}, // state 10
};
int pause[11] = {3000, 1000, 10000, 4000, 3000, 1000, 10000, 4000, 3000, 10000, 5000};
int mystate = 0;
void setup() {
for (int i = 0; i < 9; i++) {
pinMode(ledPins[i], OUTPUT);
}
// Test-LED
for (int i = 0; i < 9; i++) {
digitalWrite(ledPins[i], HIGH);
}
delay(3000);
mytestate++;
for (int i = 0; i < 9; i++) {
digitalWrite(ledPins[i], LOW);
}
delay(3000);
pinMode(bNSPin, INPUT);
pinMode(bEWPin, INPUT);
pinMode(bPPin, INPUT);
}
void showphase() {
for (int i = 0; i < 9; i++) {
digitalWrite(ledPins[i], phase[mystate][i]);
}
delay(pause[mystate]);
}
void loop() {
bPState = digitalRead(bPPin);
showphase();
mystate++;
if (mystate >= 11) mystate = 0;
if ((bPState == HIGH)&&(mystate == 2)) {
mystate = 2;
for (int i = 0; i < 9; i++) {
digitalWrite(ledPins[i], phase[mystate][i]);
}
delay(pause[mystate]);
mystate = 3;
for (int i = 0; i < 9; i++) {
digitalWrite(ledPins[i], phase[mystate][i]);
}
delay(pause[mystate]);
mystate = 8;
for (int i = 0; i < 9; i++) {
digitalWrite(ledPins[i], phase[mystate][i]);
}
}
}