-
-
Save lopesivan/bee47a4130a705041949df922ee4d619 to your computer and use it in GitHub Desktop.
AVR Microcontroller Advanced Hello World (LED Blink) http://youtu.be/KatkY_YJgsY
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define F_CPU 16000000 //16MHz | |
#include <avr/io.h> | |
#include <util/delay.h> | |
int ledPins[] = {PC3, PC4, PC5}; | |
int ledPinsNum = sizeof(ledPins)/sizeof(int); | |
bool pressed = false; | |
bool oldPressed = false; | |
bool leftDirection = false; | |
bool button_is_pressed() | |
{ | |
//debouncing | |
if(bit_is_clear(PINC, PC2)) | |
{ | |
_delay_ms(10); | |
if(bit_is_clear(PINC, PC2)) | |
{ | |
return true; | |
} | |
} | |
return false; | |
} | |
bool process_button() | |
{ | |
bool isChanged = false; | |
pressed = button_is_pressed(); | |
isChanged = pressed && oldPressed == false; | |
if(isChanged) | |
{ | |
leftDirection = !leftDirection; | |
} | |
oldPressed = pressed; | |
return isChanged; | |
} | |
void switch_off_leds() | |
{ | |
//drive all led pins low | |
for(int i=0; i < ledPinsNum; i++) | |
{ | |
PORTC &= ~(1<<ledPins[i]); | |
} | |
} | |
int main(void) | |
{ | |
DDRC |= (1<<DDC3)|(1<<DDC4)|(1<<DDC5); // set PC3, PC4 and PC5 pins to output | |
DDRC &= ~(1<<DDC2); // set PC2 pin to input | |
PORTC |= (1<<PC2); //internal pull-up resistor for PC2 | |
int i=0; | |
while(1) | |
{ | |
bool buttonProcessed = false; | |
switch_off_leds(); | |
//change the direction if necessary | |
int currLedPin = leftDirection ? ledPinsNum - i - 1: i; | |
PORTC |= (1<<ledPins[currLedPin]); //drive current led pin high | |
//500ms delay and button state reading | |
for(int j=0; j < 10; j++) | |
{ | |
//if the direction was changed, keep delaying without button state reading | |
if(!buttonProcessed) | |
{ | |
buttonProcessed = process_button(); | |
} | |
_delay_ms(50); | |
} | |
if(!(buttonProcessed && i==0)) | |
{ | |
i++; | |
} | |
if(i >= ledPinsNum) | |
{ | |
i=0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment