In this section, we will try to blink the on-board LED that is connected to Digital pin 13 or Port B 5th pin from the ATMEGA328P.
The code for the blinky project is given below: (using AVR GCC library)
#include <avr/io.h> // Exposes GPIO functions and registers
#include <util/delay.h> // Exposes the delay function
int main(){
DDRB |= (1<<PB5); // Making PORTB 5th bit as an output bit
while(1){ // Infinite loop
PORTB |= (1<<PB5); // Setting the 5th bit of Port B
_delay_ms(1000); // 1000 ms delay
PORTB &= ~(1<<PB5); // Clearing the 5th Bit of Port B
_delay_ms(1000); // 1000 ms delay
}
return 0;
}
Here the F_CPU flag is defined to tell the compiler about the operating Frequency. By default its 10MHz and avrgcc will show warnings in case if you don’t define F_CPU.
<avr/io.h> header file is used to obtain the GPIO configuration and control functions.
<util/delay.h> is used to get the _delay_ms function that can be used to specify the nop delay in milliseconds.
Here, the Digital Pin 13 LED is connected to Port B 5th Pin. Hence, we declare the 5th pin as an output pin by defining DDRB |= (1<<PB5).
Then its the usual blink sketch. We set the 5th bit in PORTB and clear it followed by a delay of 1000ms (or 1sec) for set and clearing.
Building the hex file and flashing
make clean can be used to remove the previous files stored in the build directory.
make all to generate the hex files for flashing the chip.
Connect your Arduino Uno to PC and identify (and verify) that the port is /dev/ttyACM0 from the Arduino application.
Now, you can flash the chip by running make flash_mcu. avr-dude will write the flash in atmega328p, read it back to verify if the write was right.
Then your program will start executing (or you may have to reset the micro-controller).
Blinky but with user defined memory file
// Imports the register
// memory mapping variables
#include "./../inc/atmega328p/memorymap.h"
// #include <avr/io.h> // Exposes GPIO functions and registers
#include <util/delay.h> // Exposes the delay function
int main(){
DDRB |= (1<<5); // Making PORTB 5th bit as an output bit
while(1){ // Infinite loop
PORTB |= (1<<5); // Setting the 5th bit of Port B
_delay_ms(1000); // 1000 ms delay
PORTB &= ~(1<<5); // Clearing the 5th Bit of Port B
_delay_ms(1000); // 1000 ms delay
}
return 0;
}