I'm getting my feet wet in embedded development, and like all those before me, my first task was to make an LED blink. I went a bit further than that and made a "runner" that lights up each led from 0 to 7 in sequence. The sequence begins as soon as the board is powered on. You can see it in action here.
I'm using an ATxMegaA1 chip with the avr-gcc compiler and tool chain. The document I consulted most was the Using IO pins and external interrupts doc.
I decided that creating an "Led" concept was a nice abstraction to wrap around the port they're attached to on the board. I also introduced a macro to change the delay when I'm debugging, because the simulator is orders of magnitudes slower than the real chip.
It's my first ever c, so please be brutal.
led.h
#include <avr/io.h>
#define LEDPORT PORTE_OUT
#define LEDPORT_DIR PORTE_DIR
void init(void);
void toggleLights(int ledPosition);
led.c
#include "led.h"
void init(void)
{
LEDPORT_DIR = 0b11111111; //Configure LED port for output
LEDPORT = 0b11111111; //LEDs are active low, this makes sure they're off on start up
}
//Turns light at provided port pin on and all others off.
void toggleLights(int ledPosition)
{
LEDPORT = ~(1 << ledPosition);
}
Blink.c
#include <stdint.h>
#include "led.h"
#ifdef DEBUG
#define DELAYITERATIONS 0
#else
#define DELAYITERATIONS 10000
#endif
void delay(volatile uint32_t d)
{
while (d-- != 0) // loops while non-0 and decrements
;
}
int main(void)
{
init();
while(1)
{
for (int i = 0; i < 8; i++)
{
toggleLights(i);
delay(DELAYITERATIONS);
}
}
}