Reputation: 746
I want my code to first blink when the system is powered on, then when Button B1 on Pin D3 is pressed once, to freeze on the LED states at the moment it was pressed. Then on B1 press again, to continue blinking and so on...
My code works until I press B1 the 2nd time. The AVR freezes on the state, but when I press B1 a third time, nothing happens. Is there something wrong with my scope?
#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);
}
Upvotes: 0
Views: 687
Reputation: 958
You are always resetting the Released_Confidence_Level after incrementing in the else branch.
Upvotes: 1