traffic.ino (1731B)
1 const int PL_BUTTON = 2; 2 const int PL_LED_RED = 6; 3 const int PL_LED_GREEN = 7; 4 const int TL_LED_RED = 3; 5 const int TL_LED_ORANGE = 4; 6 const int TL_LED_GREEN = 5; 7 8 const int NSTATES = 4; 9 10 volatile int curstate = 0; 11 12 ISR(TIMER1_COMPA_vect) 13 { 14 int btn_state; 15 16 btn_state = digitalRead(PL_BUTTON); 17 if (btn_state == HIGH) { 18 delay(100); /* lazy debounce */ 19 curstate = 1; 20 } 21 } 22 23 void 24 timer_init() 25 { 26 noInterrupts(); 27 TCCR1A = 0; 28 TCCR1B = 0; 29 TCNT1 = 0; 30 OCR1A = 6249; 31 TCCR1B |= (1 << WGM12) | (1 << CS12); 32 TIMSK1 |= (1 << OCIE1A); 33 interrupts(); 34 } 35 36 void 37 state0() 38 { 39 digitalWrite(PL_LED_RED, HIGH); 40 digitalWrite(PL_LED_GREEN, LOW); 41 digitalWrite(TL_LED_RED, LOW); 42 digitalWrite(TL_LED_ORANGE, LOW); 43 digitalWrite(TL_LED_GREEN, HIGH); 44 delay(4000); 45 } 46 47 void 48 state1() 49 { 50 digitalWrite(PL_LED_RED, HIGH); 51 digitalWrite(PL_LED_GREEN, LOW); 52 digitalWrite(TL_LED_RED, LOW); 53 digitalWrite(TL_LED_ORANGE, HIGH); 54 digitalWrite(TL_LED_GREEN, LOW); 55 delay(2000); 56 } 57 58 void 59 state2() 60 { 61 digitalWrite(PL_LED_RED, LOW); 62 digitalWrite(PL_LED_GREEN, HIGH); 63 digitalWrite(TL_LED_RED, HIGH); 64 digitalWrite(TL_LED_ORANGE, LOW); 65 digitalWrite(TL_LED_GREEN, LOW); 66 delay(4000); 67 } 68 69 void 70 state3() 71 { 72 digitalWrite(PL_LED_RED, HIGH); 73 digitalWrite(PL_LED_GREEN, LOW); 74 digitalWrite(TL_LED_RED, HIGH); 75 digitalWrite(TL_LED_ORANGE, LOW); 76 digitalWrite(TL_LED_GREEN, LOW); 77 delay(3000); 78 } 79 80 void 81 setup() 82 { 83 pinMode(PL_BUTTON, INPUT); 84 pinMode(PL_LED_RED, OUTPUT); 85 pinMode(PL_LED_GREEN, OUTPUT); 86 pinMode(TL_LED_RED, OUTPUT); 87 pinMode(TL_LED_ORANGE, OUTPUT); 88 pinMode(TL_LED_GREEN, OUTPUT); 89 90 timer_init(); 91 Serial.begin(9600); 92 } 93 94 void (*states[NSTATES])() = { 95 state0, 96 state1, 97 state2, 98 state3, 99 }; 100 101 void 102 loop() 103 { 104 curstate %= NSTATES; 105 (*states[curstate++])(); 106 }