My aim: To make a button that turns on and off a "Blink LED" Program. PortD only has output LED. PORTBO has input button. Microcontroller: Atmega328p
Problem: Currently when I press button case1 of switch runs so the "Blink LED" Program starts. But I cannot turn off LED with button push.
Note: I am a beginner, I think I may have to use an interrupt somehow, but not sure
#include <avr/io.h> // header file file for input output pins
#include <util/delay.h> // header file for delay.
#define DEBOUNCE_TIME 25 // time to wait while "de-bouncing" button
void init_ports_mcu()
{ /* set pin 5 of PORTB for output*/
DDRD = 0xFF;
PORTD = 0x00;
PORTB |= (1 << DDB0);
}
unsigned char button_state()
{
if( !(PINB & 0x01) )
{
_delay_ms( DEBOUNCE_TIME );
if( (PINB & 0x01) ) return 1;
}
return 0;
}
int main( void )
{
init_ports_mcu();
unsigned char n_led = 1;
while( 1 )
{
if( button_state() )
{
switch( n_led )
{
case 1:
while( 2 )
{
PORTD |= 0xFF;
_delay_ms( 1000 ); //delay 1 second
PORTD &= ~0xFF;
_delay_ms( 1000 );
if( button_state() ) // If the button is pressed break while loop
{
break;
}
}
break;
case 2:
PORTD |= 0x00;
_delay_ms( 5000 ); //delay 1 second
n_led--; // swtiches back to case1 LED number
break;
}
//n_led ++;
}
}
return 0;
}
mainstarts withunsigned char n_led = 1;and the only timen_ledchanges afterwards isn_led--;. I don't see howswitch(n_led)could ever reachcase 2:. - dxivbutton_state()function is an edge detector. In order to get that function to return 1, you need to press the button within the 25msec delay time. When the code is executing thewhile(1)loop, most of the time is spent in the_delay(DEBOUNCE_TIME)call, so button presses are recognized. But in thewhile(2)loop, most of the time is spent in the_delay(1000)calls, so you need to time the button press down to the millisecond. Good luck with that! The odds are 40 to 1 against you. - user3386109_delay_ms(1000). ChangeDEBOUNCE_TIMEto 1000. Now when you press the button, the LED will start blinking. If you press the button when the LED is on, it will keep blinking. But if you press the button when the LED is off, it will stop blinking. - user3386109