C
language?
C
is available for every CPUpuC
will work on every AVRwrite code in C
then compile the code to machine language
then transfer the code to the chip
using FTDI protocol, so we need a hardware between the AVR board and the PCavr-gcc
» for linux users sudo apt-get install avrdude binutils-avr avr-libc gcc-avr
avrdude -p atmega168 -c avrisp -b 19200 -p /dev/ttyACM0 -nv
make flash
or make program
make
to make the hex fileavrdude -p atmega168 -c usbtiny -U blinkLED.hex
0R avrdude -p atmega168 -c avrisp -b 19200 -P /dev/ttyACM0 -U blinkLED.hex
depending on the programmer
-p
chip type-c
programmer type-U
hexfile file to upload // where your include information from other files
#include <avr/io.h>
#include <util/delay.h>
// here we can also use define function.
// or define globale variables
int main(void) // the C code must have one main, here //where the AVR starts executing your code
{
DDRB = 0b00000010; // DDR, Data direction register sets pin one in PORTB (PB1) into output mode
// can be DDRB |= (1<<PB1);
while(1) // called main loop
{
PORTB = 0b00000010;
_delay_ms(1000);
PORTB = 0b00000000;
_delay_ms(1000);
}
return (0);
}
#include<avr/io.h>
#include<util/delay.h>
#define led PB0
#define led_port PORTB
#define led-ddr DDRB
#define bv(x) (1<<x)
#define setbit(p,b) p|=bv(b)
#define clearbit(p,b) p&=bv(b)
#define togglebit(p,b) p^=bv(b)
...
in the main function
setbit(led-ddr,led)
...
togglebit(led-port,led)
OR
bitwise : if i want to turn on PB1
and PB2
ledS i should consider the following :
0b00000010 = (1<<PB1)
0b01000000 = (1<<PB7)
0b01000010 = (1<<PB1) | (1<<PB7)
1010
|1100
=1110
XOR
bitwise : if i want to change the status of one led i should use this operator as follows :
0b00001111
^0b00000010
0b00001101
1010
^1100
=0110
AND
bitwise : if i want to clear a specific bit like :
0b00001111
&0b11111101
0b00001101
Bitwise AND compares two bits and returns 1 only if both of the bits are 1. If either of the bits are 0, AND returns 0:
1010
&1100
=1000
NOT
bitwise : also to clear bit :
0b11111101=~(1<<PB1)
~1100
=0011
PORTB = PORTB & ~(1<<PB1)
OR
PORTB & = ~(1<<PB1)
PORTB | = (1<<PB1)
PORTB & = ~(1<<PB1)
PORTB ^ = (1<<PB1)
PORTB = (1<<PB1) = (1<<1)
#define _BV(bit) (1 << (bit))
PORTB =(1<<i)
, PORTB = ~(1<<i)
, PORTB |= (1<<i)
, PORTB &= ~(1<<i)
PORTB |= (1 << 2);
PORTB ^= (1 << 2);
PORTB ^= ((1 << 2) | (1 << 4));
PORTB &= ~(1 <<2);
(1 << 2) -> 0b00000100
~(1 << 2) -> 0b11111011
PORTB & = ~(1«3);uint8_t
: unsigned int 8 bitsuint16_t
: unsigned int 16 bitsuint8_t
: from 0 to 255 if the maximum value 255
is reached it will count from the begining 0
againserial protocol
: The rules for encoding data into voltage pulses and decoding the voltage pulses back into dataUART
serial : universal asynchronous receive and transmit is the most common serial mode
DDRD &= ~(1 << PD2);
PORTD |= (1 << PD2);
(1 << 2) : 00000100
PIND : xxxxxxxx
(1 << 2) : 00000100
& : 00000x00
if (PIND & (1<<2))
{
doStuff();
}