Upload
metin-akkus
View
259
Download
1
Embed Size (px)
Citation preview
School of Electrical, Computer and Telecommunications EngineeringUniversity of Wollongong
Australia
ECTE333: Digital Hardware 2Lecture 7 - C Programming for the Atmel AVR
© University of Wollongong, 2010. 2Lam Phung
ECTE333 Spring 2010 ─ Schedule
Final exam (25%) & Practical exam (10%)
Lab report (5%)L13: Revision lecture13
Lab 1212
Class Test 2 (1h, worth 5%)11
Lab 11Tutorial 1110
L11: Analogue-to-digital converter9
Lab 10Tutorial 108
L10: Pulse width modulator7
Lab 9Tutorial 96
L9: Timers5
Lab 8Tutorial 84
L8: Serial communications3
Lab 7Tutorial 72
L7: C programming for the ATMEL AVR1
Lab (2h) (5%)Tutorial (1h)Lecture (2h)Week
© University of Wollongong, 2010. 3Lam Phung
Lecture 7 references
J. Pardue, C Programming for Microcontrollers, 2005, SmileyMicros,[Chapters 1-6].
Atmel Corp., 8-bit AVR microcontroller with 16K Bytes In-SystemProgrammable Flash ATmega16/ATmega16L, 2007.
S. F. Barrett and D. J. Pack, Atmel AVR Microcontroller Primer:Programming and Interfacing, 2008, Morgan & Claypool Publishers,[Chapter 1].
© University of Wollongong, 2010. 4Lam Phung
Lecture 7’s sequence
Overview of ATmega167.1
C Development Environment for the AVR7.2
Review of C Programming7.3
Digital IO in ATmega167.4
© University of Wollongong, 2010. 5Lam Phung
AVR story
AVR podcast by AVR TV.
© University of Wollongong, 2010. 6Lam Phung
7.1 Overview of ATmega16
To support different design requirements and reduce cost, the AtmelAVR family has many microcontrollers: ATmega8515, ATmega16, etc.
Microcontrollers in the 8-bit AVR family share a similar instruction setand architecture.
The ATmega16 has components that are useful for typicalmicrocontroller applications, such as
analog-to-digital converter,pulse-width-modulator.
Why using ATmega16?
© University of Wollongong, 2010. 7Lam Phung
Comparison between ATmega8515 and ATmega16
45IO ports
noneup to 64K bytesExternal memory
512 bytes512 bytesEEPROM
1K bytes512 bytesInternal SRAM
2117Interrupt vectors
SPI, USART, Two-wireSPI, USART,Serial interfaces
Analogue comparator,8-channel 10-bit ADC
Analogue comparatorADC
16K8KFlash program memory
43PWM channels
two 8-bit, one 16-bitone 8-bit, one 16-bitTimers
3232General-purpose 8-bitregisters
131130Number of instructions
ATmega16ATmega8515
© University of Wollongong, 2010. 8Lam Phung
ATmega16 ─ Block diagram
ADC
Timers
Serial
Port A
Port B
Port C
Port D
CPU
Interrupt
© University of Wollongong, 2010. 9Lam Phung
ATmega16 ─ Pin layout
© University of Wollongong, 2010. 10Lam Phung
Using the ATmega16 for embedded applications
12Embedded applications
11
10
9
8
7
Lab
11
10
9
8
7
Lecture
11Analogue to digital converter
10PWM
9InterruptsTimers
8Serial communications
7Digital IO
TutorialC programming for
In Lecture 7, we’ll study digital IO ports of the ATmega16.Other peripherals will be studied in depth, from Lectures 8 to 11.
© University of Wollongong, 2010. 11Lam Phung
7.2 C Development Environment for the AVR
C is a high-level programming language: C code is easier tounderstand compared to other languages.
C supports low-level programming: We can access every hardwarecomponents of the microcontroller with C.
C has standard libraries for complex tasks: data type conversions,standard input/output, long-integer arithmetic.
The Atmel AVR instruction set has been designed to support Ccompilers: C code can be converted efficiently to assembly code.
Why using C?
© University of Wollongong, 2010. 12Lam Phung
C tools
We need two tools for C development: Atmel AVR Studio and WinAVR.
Atmel AVR StudioAn integrated development environment for Atmel AVRmicrocontroller.It includes editor, assembler, emulator, HEX file downloader.Available from Atmel website,
http://www.atmel.com/dyn/products/tools_card.asp?tool_id=2725
WinAVRA C compiler for AVR microcontroller.Can be used alone or as a plug-in for Atmel AVR Studio.Available at: http://winavr.sourceforge.net/
© University of Wollongong, 2010. 13Lam Phung
Installing C tools
1) Uninstall earlier versions of WinAVR and Atmel AVR Studio.
2) Download setup files for Atmel AVR Studio and WinAVRhttp://www.elec.uow.edu.au/avr/getdoc.php?doc=tools/AvrStudio4Setup.exehttp://www.elec.uow.edu.au/avr/getdoc.php?doc=tools/AVRStudio4.18SP1.exehttp://www.elec.uow.edu.au/avr/getdoc.php?doc=tools/WinAVR-20100110-install.exe
3) Run setup file for Atmel AVR Studio. Accept default options.
4) Run setup file for WinAVR. Accept default options.
For ECTE333, we use the following versions:* Atmel AVR Studio version 4.18 build 692* WinAVR release 2010.01.10
© University of Wollongong, 2010. 14Lam Phung
Development cycle for C
Step 1: Create AVR Studio projectproject nameproject type Cselect simulator and device
Step 2: Enter a C program.
Step 3: Compile the C program to produce a HEX file.
Step 4: Download and test the HEX file on Atmel AVR microcontroller.
We’ll illustrate these steps using an example.Refer to the lab notes for debugging techniques.
© University of Wollongong, 2010. 15Lam Phung
Development cycle for C ─ Example
A program that lets user turn on LED by pressing a switch.Video demo link: [avr]/ecte333/lab07_task123.mp4
© University of Wollongong, 2010. 16Lam Phung
Step 1: Create AVR Studio project
Start the AVR Studioprogram.
Select menu Project | NewProject.
project type: AVR GCCproject name: ledproject location: C:\AVRoption ‘Create initial file’option ‘Create folder’
Click Next.
© University of Wollongong, 2010. 17Lam Phung
Create AVR Studio project
Select debug platform anddevice.
debug platform: AVRSimulatordevice: ATmega16
Click Finish.
© University of Wollongong, 2010. 18Lam Phung
Step 2: Enter a C program
programled.c
project files
statusmessages
The AVR Studio window.
© University of Wollongong, 2010. 19Lam Phung
Enter a C program/* File: led.c
Description: Simple C program for the ATMEL AVR uC (ATmega16 chip)It lets user turn on LEDs by pressing the switches on STK500 board
*/#include <avr/io.h> // AVR header file for all registers/pinsint main(void){
unsigned char i; // temporary variable
DDRA = 0x00; // set PORTA for inputDDRB = 0xFF; // set PORTB for outputPORTB = 0x00; // turn ON all LEDs initially
while(1){// Read input from PORTA.// This port will be connected to the 8 switchesi = PINA;
// Send output to PORTB.// This port will be connected to the 8 LEDsPORTB = i;
}return 1;
}
c
© University of Wollongong, 2010. 20Lam Phung
Step 3: Compile the C program
Select menu Build | Build to generate HEX file led.c.
© University of Wollongong, 2010. 21Lam Phung
Step 4: Download/test HEX file on microcontroller
Hardware setup for example program.Connections to PORTA & PORTB are only for this example.
PORTA toswitches
programmingmode
power switch 12-V powersupply
serial cableto PC
PORTB to LEDs
ATmega16chip
© University of Wollongong, 2010. 22Lam Phung
Download/run HEX file on microcontroller
Select menu Tools |Program AVR | Connect.
Select platform and port.‘STK500 or AVRISP’‘Auto’
Click ‘Connect’.
© University of Wollongong, 2010. 23Lam Phung
Download/run HEX file on microcontroller
Select Input HEX file,generated in Step 3.
Click ‘Program’.
After this, the program isdownloaded to and run onthe STK500 board.
The program remains evenafter power-off. To erase,click ‘Erase Device’.
© University of Wollongong, 2010. 24Lam Phung
7.3 Review of C Programming
Here, we review briefly major aspects of the C programming language.
7.3.1 Structure of a C program7.3.2 Data types and operators7.3.3 Flow control in C7.4.4 C functions
In all lectures of ECTE333, C code examples will be used extensively.
Most students in this class learnt C programming in their first year.
© University of Wollongong, 2010. 25Lam Phung
7.3.1 Structure of a C program
#include <avr/io.h> // avr header file for all registers/pinsint main(void){
unsigned char i; // temporary variableDDRA = 0x00; // set PORTA for inputDDRB = 0xFF; // set PORTB for outputPORTB = 0x00; // turn ON all LEDs initiallywhile(1){
// Read input from PORTA, which is connected to the 8 switchesi = PINA; // Send output to PORTB, which is connected to the 8 LEDsPORTB = i;
}return 1;
}
A C program typically has two main sections.#include section: to insert header files.main() section: code that runs when the program starts.
In the example below, <avr/io.h> is a header file that contains allregister definitions for the AVR microcontroller.
© University of Wollongong, 2010. 26Lam Phung
C comments
Comments are text that the compiler ignores.
For a single-line comment, use double back slashesDDRA = 0x00; // set PORTA for input
For a multi-line comment, use the pair /* and *//* File: led.c
Description: Simple C program for the ATMEL AVR(ATmega16 chip)It lets user turn on LEDs by pressing the switches on the STK500board
*/
Always use comments to make program easy to understand.
© University of Wollongong, 2010. 27Lam Phung
C statements and blocksC statements
C statements control the program flow.They consist of keywords, expressions and other statements.A statement ends with semicolon.DDRB = 0xFF; // set PORTB for output
C blocksA C block is a group of statements enclosed by braces {}.Usually, a C block is run depending on some logical conditions.
while (1){
// Read input from PORTA - connected to the 8 switches
i = PINA;
// Send output to PORTB - connected to the 8 LEDs
PORTB = i;
}
© University of Wollongong, 2010. 28Lam Phung
7.3.2 Data types and operators
The main data types in C arechar: 8-bit integer
int: 16-bit integer
long int: 32-bit integer
The above data types can be modified by keyword ‘unsigned’char a; // a value range -128, 0, …, 127
unsigned char b; // b value range 0, 1, 2, …, 255
unsigned long int c; // c value range 0,…, 232 - 1
Some examples of variable assignmenta = 0xA0; // a stores hexadecimal value of A0
b = ‘1’; // b stores ASCII code of character ‘1’
c = 2000ul; // c stores a unsigned long integer 2000
© University of Wollongong, 2010. 29Lam Phung
C operators
C has a rich set of operators
Arithmetic operators
Relational operators
Logical operators
Bit-wise operators
Data access operators
Miscellaneous operators
© University of Wollongong, 2010. 30Lam Phung
Arithmetic operators
Negate x-xNegation-
Decrement x by 1 after using itDecrement x by 1 before using it
x--
--x
Decrement--
Increment x by 1 after using itIncrement x by 1 before using it
x++
++x
Increment++
Subtract y from xx – ySubtraction-
Add x and yx + yAddition+
Remainder of x divided by yx % yModulo%
Divide x by yx / yDivision/
Multiply x times yx * yMultiplication*
DescriptionExampleNameOperator
© University of Wollongong, 2010. 31Lam Phung
Relational operators
1 is x is not equal to 4, 0 otherwisex != 4Not equal to!=
1 is x is equal to y, 0 otherwisex == yEqual to==
1 is x is smaller than or equal to y, 0 otherwisex <= yLess than orequal to
<=
1 if x is smaller than y, 0 otherwisex < yLess than<
1 is x is greater than or equal to 5, 0 otherwisex >=5Greater than orequal to
>=
1 if x is greater than 5, 0 otherwisex > 5Greater than>
DescriptionExampleNameOperator
© University of Wollongong, 2010. 32Lam Phung
Logical operators
0 if both x and y are 0, otherwise 1x || yLogical OR||
1 is both x and y are 1, otherwise 0x && yLogical AND&&
1 if x is 0, otherwise 0!xLogical NOT!
DescriptionExampleNameOperator
These operate on logical variables/constants.
© University of Wollongong, 2010. 33Lam Phung
Bit-wise operators
Shift bits in x one position to the rightx >> 1Shift right>>
Shift bits in x three positions to the leftx << 3Shift left<<
Bitwise XOR of x and yx ^ yBitwise XOR^
Bitwise OR of x and yx | yBitwise OR|
Bitwise AND of x and yx & yBitwise AND&
Toggle every bit from 0 to 1, or 1 to 0~xBit-wisecomplement
~
DescriptionExampleNameOperator
These operate on individual bits of a variable/constant.
© University of Wollongong, 2010. 34Lam Phung
Data-access operators
Address of the memory location wherevariable x is stored
&xAddress of&
Content of memory location pointed by p*pIndirection*
Field ‘age’ of structure pointer pp->ageMember selection->
Field ‘age’ of structure variable xx.ageMember selection.
Third element of array xx[2]Array element[]
DescriptionExampleNameOperator
These operate on arrays, structures or pointers.We’ll learn more about these operators later.
© University of Wollongong, 2010. 35Lam Phung
Miscellaneous operators
This is equivalent toif (x > 5)
y = 10;
else
y = 20;
char x;
y=(x>5)?10:20;
Conditionalevaluation
?
x is 8-bit integerx is converted to 16-bit integer
char x = 3;
(int) x
Type cast(type)
Call a function to create delay of250ms
_delay_ms(250)Function()
DescriptionExampleNameOperator
commonly used by C coders.
© University of Wollongong, 2010. 36Lam Phung
7.3.3 Flow control in C
By default, C statements are executed sequentially.
To change the program flow, there are six types of statements
if-else statementswitch statement
while statementfor statementdo statement
goto statement
Conditional
Iterative
Should be avoided!
© University of Wollongong, 2010. 37Lam Phung
If-else statementGeneral syntax
if (expression)
statement_1;
else
statement_2;
Example code
char a, b, sum;a = 4; b = -5;sum = a + b;if (sum < 0)
printf(“sum is negative”);else if (sum > 0)
printf(“sum is positive”);else
printf(“sum is zero”);
© University of Wollongong, 2010. 38Lam Phung
Switch statement
General syntax
switch (expression)case constant_1:
statement_1;break;
case constant_2:statement_2;break;
…case constant_n:
statement_n;break;
default:statement_other;
}
Use ‘break’ to separatedifferent cases.
© University of Wollongong, 2010. 39Lam Phung
Switch statement ─ Example
Lab 7: Find the bit pattern to display a digit on the 7-segment LED.
Bit pattern for digit ‘1’: 0 0 0 0 0 1 1 0 Bit pattern for digit ‘2’: 0 0 0 1 1 0 1 1
© University of Wollongong, 2010. 40Lam Phung
Switch statement ─ Example
unsigned char digit;unsigned char led_pattern;switch (digit)case ‘0’:
led_pattern = 0b00111111;break;
case ‘1’:led_pattern = 0b00000110;break;
case ‘2’:led_pattern = 0b01011011;break;
//you can complete more cases here...default:}PORTB = led_pattern; // send to PORTB and 7-segment LED
© University of Wollongong, 2010. 41Lam Phung
While statement
General syntax
while (expression){
statements;
}
Example code: Compute the sum of 1 + 2+ …+ 100
int sum, i;i = 1; sum = 0;while (i <= 100){
sum = sum + i;i = i + 1;
}
© University of Wollongong, 2010. 42Lam Phung
For statementGeneral syntaxfor (expression1; expression2; expression3){
statements;
}
expression1 is run before the loop starts.expression2 is evaluated before each iteration.expression3 is run after each iteration.
Example code: Compute the sum of 1 + 2+ …+ 10int sum;sum = 0;
for (int i = 1; i <= 10; i++){sum = sum + i;
}
© University of Wollongong, 2010. 43Lam Phung
Do statement
General syntaxdo {
statements;
} while (expression);
Example code: compute the sum of 1 + 2 + … + 10
int sum, i;i = 1; sum = 0;do{
sum = sum + i;i = i + 1;
} while (i <= 10);
© University of Wollongong, 2010. 44Lam Phung
Break statement in loop
The ‘break’ statement inside a loop forces early termination of theloop.
What is the value of ‘sum’ after the following code is executed?
int sum, i;i = 1; sum = 0;while (i <= 10){
sum = sum + i;i = i + 1;if (i > 5)
break;}
© University of Wollongong, 2010. 45Lam Phung
Continue statement in loop
The ‘continue’ statement skips the subsequent statements in thecode block and forces the execution of the next iteration.
What is the value of ‘sum’ after the following code is executed?
int sum, i;i = 1; sum = 0;while (i <= 10){
i = i + 1;if (i < 5)
continue;sum = sum + i;
}
© University of Wollongong, 2010. 46Lam Phung
C arraysAn array is a list of values that have the same data type.
In C, array index starts from 0.
An array can be one-dimensional, two-dimensional or more.
This code example creates a 2-D array (multiplication table):int a[8][10];for (int i = 0; i < 8; i++)
for (int j = 0; i < 10; j++)a[i][j]= i * j;
An array can be initialized when it is declared.int b[3] = {4, 1, 10};unsigned char keypad_key[3][4] = {{'1', '4', '7', '*'},
{'2', '5', '8', '0'},{'3', '6', '9', '#'}};
© University of Wollongong, 2010. 47Lam Phung
7.3.4 C functions
C functions are sub-routines that can be called from the mainprogram or other functions.
A C function can have a list of parameters and produce a returnvalue.
Functions enable modular designs, code reuse, and hiding ofcomplex implementation details.
Let us study C functions through examples.
© University of Wollongong, 2010. 48Lam Phung
Functions ─ Example 1
// factorial is the name of the custom function// it accepts an input n of type int, and return an output of type intint factorial(int n){
int prod = 1;for (int i = 1; i <=n; i++)
prod = prod * i; return prod; // return the result
}
int main(void){int n = 5; // some example value of nint v; // variable to storage resultv = factorial(n); // call the function, store return value in vreturn 1;
}
Write a function to compute the factorial n! for a given n.
© University of Wollongong, 2010. 49Lam Phung
Functions ─ Example 2
// factorial is the name of the custom function// it accepts an input n of type int,// it stores output at memory location by int pointer pvoid factorial(int n, int* p){
int prod = 1;for (int i = 1; i <=n; i++)
prod = prod * i; *p = prod;// store output at memory location pointed by p
}
int main(void){int n = 5; // some example value of nint v; // variable to storage resultfactorial(n, &v); // call the function, store return value in v
}
Write a function to compute the factorial n! for a given n.
© University of Wollongong, 2010. 50Lam Phung
Guidelines on C coding and documentation
Optimize the C code for efficiency and length.
Delete unnecessary lines of code.
The C code must be properly formatted.
For printing, use a fixed-width font such as Courier New for code.
Use indentation to show the logical structure of the program.
Use a blank line to separate code sections.
Use meaningful variable names and function names.
If a C statement is too long for one printed line, split it logically intomultiple lines.
Use C comments concisely to explain code.
Observe the way that C code is presented in the lecture notes orlab notes.
© University of Wollongong, 2010. 51Lam Phung
7.4 Digital IO in ATmega16
ATmega16 has fours 8-bit digital IO ports:PORT A,PORT B,PORT C, andPORT D.
Each port has 8 data pins.
Every port is bi-directional. Each of the 8 pins can be individuallyconfigured as
input (receiving data into microcontroller), oroutput (sending data from microcontroller).
© University of Wollongong, 2010. 52Lam Phung
Digital IO in ATmega16 ─ Pins
© University of Wollongong, 2010. 53Lam Phung
Digital IO in ATmega16 ─ Configuring for input/outputFor each port, there are three relevant 8-bit registers.
Data Direction Register (DDRx)Input Pins Address (PINx)Data Register (PORTx)
Here, x denotes A, B, C or D.
Data Direction Register (DDRx) is used to configure a specific portpin as output (1) or input (0).
Example: To set Port A pins 0 to 3 for input, pins 4 to 7 foroutput, we write C code
DDRA = 0b11110000; // configure pins
1 1 1 1 0 0 0 001234567
DDRA
for inputfor output
bit
© University of Wollongong, 2010. 54Lam Phung
Digital IO in ATmega16 ─ Reading from/Writing to PortRegister Data Register (PORTx) is used to write output data to port.
Example: To write a binary 0 to output pin 6, binary 1 to otherpins of Port A, we write C code
PORTA = 0b10111111; // write output
Register Input Pins Address (PINx) is used to read input data from port.Example: To read the input pins of Port A, we write C code
unsigned char temp; // temporary variable
temp = PINA; // read input
Where do the C names PINA, PORTA, DDRA come from?// extract for header file <avr/iom16>
#define PINA _SFR_IO8(0x19)
#define DDRA _SFR_IO8(0x1A)
#define PORTA _SFR_IO8(0x1B)…
© University of Wollongong, 2010. 55Lam Phung
AVR header file
To access all AVR microcontroller registers, your program mustinclude the header file <io.h>, which is found in the WinAVR folder.#include <avr/io.h>
Depending on which device selected in your project, file ‘io.h’ willautomatically redirect to a specific header file.
ExampleFor ATmega16, the specific header file is ‘avr/iom16.h’.This header file is printed in Appendix A of the lab notes.The header file lists the C names for all registers in ATmega16,and their memory locations.We always use the C names in our code.
© University of Wollongong, 2010. 56Lam Phung
Digital IO in ATmega16 ─ Example/* File: led.c
Description: Simple C program for the ATMEL AVR uC (ATmega16 chip)It lets user turn on LEDs by pressing the switches on STK500 board
*/#include <avr/io.h> // AVR header file for all registers/pinsint main(void){
unsigned char i; // temporary variable
DDRA = 0x00; // set PORTA for inputDDRB = 0xFF; // set PORTB for outputPORTB = 0x00; // turn ON all LEDs initially
while(1){// Read input from PORTA.// This port will be connected to the 8 switchesi = PINA;
// Send output to PORTB.// This port will be connected to the 8 LEDsPORTB = i;
}return 1;
}
Demo inslide 15.
© University of Wollongong, 2010. 57Lam Phung
Summary
What we learnt in this lecture:An overview of ATmega16.The tools and the steps for programming the Atmel AVR.Basics about C programming.Programming the digital IO ports of ATmega16.
What are next activities?Tutorial 7: ‘Introduction to C programming for the AVR’ .Lab 7: ‘Introduction to C programming for the AVR’
Complete online Pre-lab Quiz for Lab 7.Write programs for tasks 4-5 of Lab 7.Use video demo of Lab 7: [avr]/ecte333/lab07_task4.mp4.