Elt 209 CH 7
Elt 209 CH 7
Chapter 7
Sepehr Naimi
www.NicerLand.com
www.MicroDigitalEd.com
Topics
Data Types
Time Delays
IO Programming in C
Logic Operation in C
Data serialization in C
Languages
High Level Languages
Easy to develop and
update
C Language
Acceptable performance
High Level Languages
Easy to develop and (like VB)
update C Language
Portable
Machine Language
Low Level Languages
High performance
Not portable
A simple C program
Write a program that calculate the sum of {1,3,
…,13,15}
int main ()
{
unsigned int sum;
while (1);
return 0;
}
Accessing I/O registers
Example 1: Write an AVR C program to send
value 0xAA to PORTA.
#include <avr/io.h>
int main ()
{
DDRA = 0xFF;
PORTA = 0xAA;
while (1);
return 0;
}
Accessing I/O registers
Example 2: Write an AVR C program to calculate
PINA + PINB and send the result to PORTC.
#include <avr/io.h>
int main ()
{
DDRA = 0x00;
DDRB = 0x00;
DDRC = 0xFF;
while (1)
PORTC = PINA + PINB;
return 0;
}
What is happening in machine language?
int Fibonnaci (int n); int Fibonnaci (int n)
{
int main () int a1 = 1;
{ int a2 = 1;
unsigned int sum = 0; int i;
int temp;
for(int j = 0; j < 11; j++)
{ if(n == 0)
sum += Fibonnaci return 0;
(j); else
} if(n <= 2)
return 1;
while(1); else{
return 0; for(i = 2; i < n; i+
+)
}
{
temp = a2;
a2 = a1 + a2;
a1 = temp;
}
return a2;
}
}
Data Types
Use unsigned whenever you can
unsigned char instead of unsigned int if you can
Data types (cont.)
char c; c long lng; lng
int a1; a1
unsigned int a;
a
What
Whatisisthe
thedifference
differencebetween
betweenint
intand
andunsigned
unsignedint?
int?
int vs. unsigned int
int a1 = 5;
AVR is an 8-bit. How could we multiply
int a2 = 3; 16-bit numbers?
int a3 = 9;
b = (a1 * a2) + a3;
Multiplications of Big Numbers
23 ab
*49 *cd
27 b*d
18
27 ad+bc
8 ac
Choosing optimized data type
unsigned int sum; unsigned char sum;
for (int i = 1; i <= 15; i+=2) for (char i = 1; i <= 15; i+=2)
sum += i; sum += i;
Accessing I/O registers
#include <avr/io.h>
int main ()
{
DDRA = 0xFF;
while(1)
{
for (unsigned char i = 0; i <= 9; i++)
PORTA = i;
}
return 0;
}
Time Delays in C
You can use for to make time delay
void delay(void)
{
volatile unsigned int i;
for(i = 0; i < 42150; i++)
{ }
}
In Atmel Studio:
It is compiler dependant
I/O programming in C
Byte size I/O programming in C
DDRB = 0xFF;
while (1) {
PORTB = 0xFF;
_delay_ms(500);
PORTB = 0x55;
_delay_ms(500);
}
#include <avr/pgmspace.h>
int main(void)
{
unsigned char a;
a = pgm_read_byte(&lookup[i]);
while (1);
}
Accessing EEPROM
#include <avr/io.h>
#include <avr/eeprom.h>
int main(void)
{
DDRC = 0xFF;
while (1);
}