我希望我的代码在系统开机时首先闪烁,然后当按下 D3 上的按钮 B1 一次时,在按下它的那一刻冻结 LED 状态。然后在 B1 上再次按下,继续闪烁等等......
我的代码一直有效,直到我第二次按 B1。AVR 冻结在状态,但是当我第三次按 B1 时,什么也没有发生。我的范围有问题吗?
#include <avr/io.h>
#include <avr/interrupt.h>
#define LED1 PIND1
#define B2 PIND2
#define B1 PIND3
#define LED2 PIND4
void turn_on();
void turnoff();
void toggle_led1();
void toggle_led2();
void blink();
void led1_on_led2_off();
int counter = 0;
int main(void)
{
// Set variables
DDRD |= 1 << LED1; //Set Direction for Output on PINB0 (Led 1)
DDRD |= 1 << LED2; //Set Direction for Output on PINB0 (Led 2)
DDRD &= ~(1 << B1); //Data Direction Register input PINB3 (Button B1)
PORTD |= 1 << B1; //Set PINB3 to a high reading
DDRD &= ~(1 << B2); //Data Direction Register input PINB4 (Button B2)
PORTD |= 1 << B2; //Set PINB4 to a high reading
int Pressed = 0;
int Pressed_Confidence_Level = 0;
int Released_Confidence_Level = 0;
GICR |=(1<<INT0);//Enables int0 as an external interrupt
MCUCR |= (1<<ISC01 | 1<<ISC00); // Generate interrupt on rising edge
sei(); // Enable the global interrupts
TCCR1B |= 1<<CS10 | 1<<CS11; // start the timer at F_CPU/pre-scaler
OCR1A = 7812; // = 0.5 second
turnoff();
while(1)
{
if (bit_is_clear(PIND, 3))
{
Pressed_Confidence_Level ++; //Increase Pressed Confidence
Released_Confidence_Level = 0; //Reset released button confidence since there is a button press
if (Pressed_Confidence_Level >500) //Indicator of good button press
{
if (Pressed == 0)
{
Pressed = 1;
counter++;
}
//Zero it so a new pressed condition can be evaluated
Pressed_Confidence_Level = 0;
}
}
else
{
Released_Confidence_Level ++; //This works just like the pressed
Released_Confidence_Level = 0; //Reset pressed button confidence since the button is released
if (Released_Confidence_Level >500)
{
Pressed = 0;
Released_Confidence_Level = 0;
}
}
if(counter%2==0)
{
blink();
}
}
return 0;
}
/*
TCCR0 is a control register used in pre-scaling.
*/
void turn_on()
{
PORTD |= 1 << LED1;// Turns on LED1 on port d
PORTD |= 1 << LED2;// Turns on LED2 on port d
}
void turnoff()
{
PORTD &= ~(1 << LED1);
PORTD &= ~(1 << LED2);
}
void toggle_led1()
{
PORTD ^= (1 << LED1);
}
void toggle_led2()
{
PORTD ^= (1 << LED2);
}
void blink()
{
if(TCNT1>7812)
{
toggle_led1();
toggle_led2();
TCNT1 = 0;
}
}
void led1_on_led2_off()
{
PORTD |= 1 << LED1;
PORTD &= ~(1 << LED2);
}