0

我正在建立一个交通信号灯系统。所以当没有按下按钮时,led 1 和 4 会亮 4 秒,然后 led 2 和 3 会亮 4 秒。如果按下按钮,行人的led(led 5)会等待,只有在led 2亮的​​时候才会亮(也就是说当我们按下按钮时,如果led 1和4亮,那么led 5会一直等到led 1 和 4 熄灭)。此时只有led 5和2会亮,其他会灭。2 秒后,led 5 熄灭,led 3 亮 2 秒。LED 2 将一直亮着(4 秒)。然后我们恢复正常。但问题是当我运行程序时,所有 4 个 LED 都亮着。

#include <avr/io.h>
#include <avr/interrupt.h>

volatile int second = 1;

volatile boolean buttonPressed = false;

enum light_state {EW, SN, PES, START_UP};
enum light_state state;

int main(void) {

  DDRB = 0xFF; //Set LEDs as output

  DDRD &= ~(1 << 2); //Set button as input
  PORTD |= (1 << PORTD2);

  EIMSK |= (1 << INT0); //enable PORTB2 as external interrupt
  EICRA |= (1 << ISC01); //detect falling edge
  EIFR |= (1 << INTF0); //clear flag

  TCCR1B |= (1 << WGM12) | (1 << CS12) | (1 << CS10); //turn on CTC mode and set up Timer 1 with the prescaler of 1024
  OCR1A = 15624; //enable output Compare A Match Interrupt
  TIMSK1 = 1 << OCIE1A; //set CTC compare value to 2 Hz at 16 MHz AVR clock , with a prescaler of 1024

  sei();
  while (1) {
    if (!buttonPressed) {
      switch (state) {
        case EW:
          PORTB &= ~((1 << PORTB1) | (1 << PORTB4));
          PORTB |= (1 << PORTB2) | (1 << PORTB3);
          state = SN;
          break;
        case SN:
          PORTB |= (1 << PORTB1) | (1 << PORTB4);
          PORTB &= ~((1 << PORTB2) | (1 << PORTB3));
          state = EW;
          break;
        case START_UP :
          PORTB &= ~((1 << PORTB1) | (1 << PORTB2) | (1 << PORTB3) | (1 << PORTB4));
          state = SN;
          break;
        default:
          state = START_UP;
          break;
        }
      second = 1;
    } else {
      switch (state) {
        case PES:
          PORTB |= (1 << PORTB2) | (1 << PORTB5);
          PORTB &= ~((1 << PORTB1) | (1 << PORTB3) | (1 << PORTB4));
          state = SN;
          break;
        case SN:
          PORTB |= (1 << PORTB2) | (1 << PORTB3);
          PORTB &= ~((1 << PORTB1) | (1 << PORTB4));
          state = EW;
          break;
        case START_UP :
          PORTB &= ~((1 << PORTB1) | (1 << PORTB2) | (1 << PORTB3) | (1 << PORTB4) | (1 << PORTB5));
          state = PES;
          break;
        default:
          state = START_UP;
          break;
      }
      buttonPressed = false;
      second = 1;
    }
  }
}

ISR(INT0_vect) {
  buttonPressed = true;
}

ISR(TIMER1_COMPA_vect) {
  if (buttonPressed) {
    if (second == 2) {
        second = 1;
    }
  }
  second++;
}
4

0 回答 0