MPS W7-L1 AVR Programming in C I
MPS W7-L1 AVR Programming in C I
AVR Programming in C
Week7-Lecture 1
int main ()
{
DDRD = 0xFF;
PORTD = 0xAA;
while (1);
return 0;
}
Accessing I/O registers
Example 2: Write an AVR C program to
calculate PINB + PINC and send the
result<avr/io.h>
#include to PORTD.
int main ()
{
DDRB = 0x00;
DDRC = 0x00;
DDRD = 0xFF;
while (1)
PORTD = PINB + PINC;
return 0;
}
AVR C Data Types
Data Types
• Use unsigned whenever you can
• unsigned char instead of unsigned int if you can
Data types (cont.)
c
lng
• long
char lng;
c;
a1 a
• unsigned
int a1; int a;
int main ()
{
DDRD = 0xFF;
while(1)
{
for (unsigned char i = 0; i <= 9; i++)
PORTD = i;
}
return 0;
}
Time Delays in C
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++)
{ }
}
duration !
The compiler has direct effect on delay duration!
Time Delays in C
• You can use predefined functions of compilers to make
time delays
In Atmel Studio:
• It is compiler dependent
Logic Operations in C
Bit-wise logical operators
1110 1110
1111 1111 ~ 1110
& 0000 | 0000 1011
0001 0001 --------------
-------------- -------------- 0001
0000 1110 0100
0001 1111
Bit-wise Example – (1)
• Write an AVR C program to toggle only bit 4 of
Port B continuously without disturbing the rest
of the pins of PORT B.
Bit-wise Example – (2)
• Write AVR C program to monitor bit 7 of Port B.
If it is 1, make bit 4 of Port B as input; otherwise,
change pin 4 of Port B to output.
Shift operations in C
data >> number of bits to be shifted right
data << number of bits to be shifted left
xxxx xxxx
xxxx OR xxxx
| 0001 | 1 << 4
0000 -------------
-------------
xxx1 xxxx
PORTB |= (1<<4); //set bit 4 (5th bit) of PORTB
xxx1 xxxx
Clearing a bit in a Byte to 0
• We can use | operator to set a bit of a byte to 1
xxxx xxxx
xxxx OR xxxx
& 1110 & ~(1 <<
1111 4)
------------- -------------
PORTB &= ~(1<<4); //clear bit 4 (5th bit) of PORTB
xxx0 xxxx xxx0 xxxx
Checking a bit in a Byte
• We can use & operator to see if a bit in a byte is 1 or 0
xxxx xxxx
xxxx OR xxxx
& 0001 & (1 << 4)
0000 -------------
-------------
if( ((PINC & (1<<5)) != 0) 00x0
//check bit 0000
5 (6th bit)
000x 0000
Bit-wise Example: Using
Compound Assignment Operator
• Write an AVR C program to toggle only bit 4 of
Port B continuously without disturbing the rest
of the pins of PORT B.
Other Examples
• See carefully 7-15 – 7-20
Bit-wise Shift Operation:
Example
27
Assembly Code
28
Conclusion
• Programming in C
▫ I/O Programming
29
Reading Material
• TextBook
▫ Chapter-7
Make sure you actually understand and run all the
examples in Atmel Studio
30
Questions?