This week we have to learn to read the datasheet of a controller and learn to program an AVR.
Usually this type of exercises do them all on a PC running Ubuntu, but since her mother board decided to abandon me I've been forced to work on a laptop with windows.
What is an AVR
The AVR microcontrollers are composed of a CPU, flash memory, RAM and EEPROM.
The AVR execute the programs in the FLASH memory, use the RAM to store temporary data and EEPROM to store data even after the power is disconnected.
Program an AVR
To program an AVR we need to compile our code we in binary generating a HEX file and transfer it to our chip.
To transfer our compiled program to the AVR we have to connect it to the PC using the special pin, unfortunately these pins are different on each chip. for this we must find the correct ones using the datasheet.
Identified the pins we have to connect our programmer, in our case the FabISP, to the board.
In order to program an AVR on windows as First download and install avrdude.
Once you installed to use it we have to open the command promp and type:
avrdude
With this command, the terminal will show us all the options available with the command.
if you want to see a list of programs available to upload to the AVR we can enter the "avrdude -c" option followed by a meaningless string so promp go wrong.
avrdude -c asdf
For as defining the port where it is connected our programmer use the "-P" option followed by the port name.
To send data to the AVR must instead type this command in Terminal:
"Avrdude -p "controller_name" -p "port" -U "memory_type":W:"path_to_file_hex"
The C script
Given our board what we want to achieve is the toogle the LED every time we press the button, to do so we used this script:
#include < avr/io.h >
#include < util/delay.h >
#define input(directions, pin) (directions &= (~pin))
#define output(directions,pin) (directions |= pin)
#define set(port,pin) (port |= pin)
#define clear(port,pin) (port &= (~pin))
#define pin_test(pins,pin) (pins & pin)
#define bit_test(byte,bit) (byte & (1 << bit))
#define led_delay() _delay_ms(200)
#define led_port PORTA
#define led_direction DDRA
#define led_pin (1 << PA7)
#define button_port PORTB
#define button_direction DDRB
#define button_pin (1 << PB2)
#define button_pins PINB
int main(void) {
CLKPR = (1 << CLKPCE);
CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);
clear(led_port, led_pin);
output(led_direction, led_pin);
set(button_port, button_pin);
input(button_direction, button_pin);
while (1) {
if (pin_test(button_pins,button_pin)==0){
set(led_port, led_pin);
led_delay();
clear(led_port, led_pin);
led_delay();
}
}
}
To fill it out and get the HEX file to be sent to the controller I've used Atmel Studio