Anda di halaman 1dari 15

ECTE333 Spring 2010 ─ Schedule

Week Lecture (2h) Tutorial (1h) Lab (2h) (5%)


1 L7: C programming for the ATMEL AVR
2 Tutorial 7 Lab 7
3 L8: Serial communications
4 Tutorial 8 Lab 8
5 L9: Timers
6 Tutorial 9 Lab 9
ECTE333: Digital Hardware 2 7 L10: Pulse width modulator

Lecture 7 - C Programming for the Atmel AVR 8 Tutorial 10 Lab 10


9 L11: Analogue-to-digital converter
10 Tutorial 11 Lab 11
11 Class Test 2 (1h, worth 5%)
School of Electrical, Computer and Telecommunications Engineering
12 Lab 12
University of Wollongong
13 L13: Revision lecture Lab report (5%)
Australia
Final exam (25%) & Practical exam (10%)

Lam Phung © University of Wollongong, 2010. 2

Lecture 7 references Lecture 7’s sequence

J. Pardue, C Programming for Microcontrollers, 2005, SmileyMicros,


[Chapters 1-6]. 7.1 Overview of ATmega16

S. F. Barrett and D. J. Pack, Atmel AVR Microcontroller Primer:


Programming and Interfacing, 2008, Morgan & Claypool Publishers, 7.2 C Development Environment for the AVR
[Chapter 1].

7.3 Review of C Programming


Atmel Corp., 8-bit AVR microcontroller with 16K Bytes In-System
Programmable Flash ATmega16/ATmega16L, 2007.
7.4 Digital IO in ATmega16

Lam Phung © University of Wollongong, 2010. 3 Lam Phung © University of Wollongong, 2010. 4
AVR story 7.1 Overview of ATmega16

Why using ATmega16?

To support different design requirements and reduce cost, the Atmel


AVR family has many microcontrollers: ATmega8515, ATmega16, etc.

Microcontrollers in the 8-bit AVR family share a similar instruction set


and architecture.

The ATmega16 has components that are useful for typical


microcontroller applications, such as
‰ analog-to-digital converter,
‰ pulse-width-modulator.

AVR podcast by AVR TV.

Lam Phung © University of Wollongong, 2010. 5 Lam Phung © University of Wollongong, 2010. 6

Comparison between ATmega8515 and ATmega16 ATmega16 ─ Block diagram


ATmega8515 ATmega16 Timers
Number of instructions 130 131
Port C Port A
Flash program memory 8K 16K
Interrupt
Internal SRAM 512 bytes 1K bytes
Serial
EEPROM 512 bytes 512 bytes
External memory up to 64K bytes none
General-purpose 8-bit 32 32
registers
IO ports 5 4 Port D
Serial interfaces SPI, USART, SPI, USART, Two-wire Port B
Timers one 8-bit, one 16-bit two 8-bit, one 16-bit
PWM channels 3 4
ADC Analogue comparator Analogue comparator,
8-channel 10-bit ADC
Interrupt vectors 17 21 CPU
ADC
Lam Phung © University of Wollongong, 2010. 7 Lam Phung © University of Wollongong, 2010. 8
ATmega16 ─ Pin layout Using the ATmega16 for embedded applications

C programming for Lecture Lab Tutorial


Digital IO 7 7 7
Serial communications 8 8 8
Interrupts 9 9 9
Timers
PWM 10 10 10
Analogue to digital converter 11 11 11
Embedded applications 12

In Lecture 7, we’ll study digital IO ports of the ATmega16.


Other peripherals will be studied in depth, from Lectures 8 to 11.

Lam Phung © University of Wollongong, 2010. 9 Lam Phung © University of Wollongong, 2010. 10

7.2 C Development Environment for the AVR C tools

Why using C? We need two tools for C development: Atmel AVR Studio and WinAVR.

C is a high-level programming language: C code is easier to Atmel AVR Studio


understand compared to other languages.
‰ An integrated development environment for Atmel AVR
microcontroller.
C supports low-level programming: We can access every hardware
‰ It includes editor, assembler, emulator, HEX file downloader.
components of the microcontroller with C.
‰ Available from Atmel website,
http://www.atmel.com/dyn/products/tools_card.asp?tool_id=2725
C has standard libraries for complex tasks: data type conversions,
standard input/output, long-integer arithmetic. WinAVR
‰ A C compiler for AVR microcontroller.
The Atmel AVR instruction set has been designed to support C ‰ Can be used alone or as a plug-in for Atmel AVR Studio.
compilers: C code can be converted efficiently to assembly code. ‰ Available at: http://winavr.sourceforge.net/

Lam Phung © University of Wollongong, 2010. 11 Lam Phung © University of Wollongong, 2010. 12
Installing C tools Development cycle for C

For ECTE333, we use the following versions: Step 1: Create AVR Studio project

* Atmel AVR Studio version 4.18 build 692 ‰ project name

* WinAVR release 2010.01.10 ‰ project type C


‰ select simulator and device
1) Uninstall earlier versions of WinAVR and Atmel AVR Studio.
Step 2: Enter a C program.
2) Download setup files for Atmel AVR Studio and WinAVR
‰ http://www.elec.uow.edu.au/avr/getdoc.php?doc=tools/AvrStudio4Setup.exe Step 3: Compile the C program to produce a HEX file.
‰ http://www.elec.uow.edu.au/avr/getdoc.php?doc=tools/AVRStudio4.18SP1.exe
‰ http://www.elec.uow.edu.au/avr/getdoc.php?doc=tools/WinAVR-20100110-install.exe
Step 4: Download and test the HEX file on Atmel AVR microcontroller.
3) Run setup file for Atmel AVR Studio. Accept default options.
We’ll illustrate these steps using an example.
4) Run setup file for WinAVR. Accept default options. Refer to the lab notes for debugging techniques.

Lam Phung © University of Wollongong, 2010. 13 Lam Phung © University of Wollongong, 2010. 14

Development cycle for C ─ Example Step 1: Create AVR Studio project


Start the AVR Studio
program.

Select menu Project | New


Project.
‰ project type: AVR GCC
‰ project name: led
‰ project location: C:\AVR
‰ option ‘Create initial file’
‰ option ‘Create folder’

Click Next.
A program that lets user turn on LED by pressing a switch.
Video demo link: [avr]/ecte333/lab07_task123.mp4

Lam Phung © University of Wollongong, 2010. 15 Lam Phung © University of Wollongong, 2010. 16
Create AVR Studio project Step 2: Enter a C program

Select debug platform and


device. project files program
led.c
‰ debug platform: AVR
Simulator
‰ device: ATmega16

Click Finish. status


messages

The AVR Studio window.

Lam Phung © University of Wollongong, 2010. 17 Lam Phung © University of Wollongong, 2010. 18

Enter a C program Step 3: Compile the C program


c
/* 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/pins
int main(void){
unsigned char i; // temporary variable

DDRA = 0x00; // set PORTA for input


DDRB = 0xFF; // set PORTB for output
PORTB = 0x00; // turn ON all LEDs initially

while(1){
// Read input from PORTA.
// This port will be connected to the 8 switches
i = PINA;

// Send output to PORTB.


// This port will be connected to the 8 LEDs
PORTB = i;
}
return 1; Select menu Build | Build to generate HEX file led.c.
}
Lam Phung © University of Wollongong, 2010. 19 Lam Phung © University of Wollongong, 2010. 20
Step 4: Download/test HEX file on microcontroller Download/run HEX file on microcontroller

PORTA to
switches power switch
12-V power
Select menu Tools |
ATmega16
supply Program AVR | Connect.
chip

Select platform and port.


serial cable ‰ ‘STK500 or AVRISP’
to PC
‰ ‘Auto’

Click ‘Connect’.
programming
mode

PORTB to LEDs

Hardware setup for example program.


Connections to PORTA & PORTB are only for this example.

Lam Phung © University of Wollongong, 2010. 21 Lam Phung © University of Wollongong, 2010. 22

Download/run HEX file on microcontroller 7.3 Review of C Programming

Select Input HEX file, Most students in this class learnt C programming in their first year.
generated in Step 3.

Here, we review briefly major aspects of the C programming language.


Click ‘Program’.
7.3.1 Structure of a C program
7.3.2 Data types and operators
After this, the program is
downloaded to and run on 7.3.3 Flow control in C
the STK500 board. 7.4.4 C functions

The program remains even In all lectures of ECTE333, C code examples will be used extensively.
after power-off. To erase,
click ‘Erase Device’.

Lam Phung © University of Wollongong, 2010. 23 Lam Phung © University of Wollongong, 2010. 24
7.3.1 Structure of a C program C comments
A C program typically has two main sections.
Comments are text that the compiler ignores.
‰ #include section: to insert header files.
‰ main() section: code that runs when the program starts.
For a single-line comment, use double back slashes
In the example below, <avr/io.h> is a header file that contains all
DDRA = 0x00; // set PORTA for input
register definitions for the AVR microcontroller.
#include <avr/io.h> // avr header file for all registers/pins
int main(void){ For a multi-line comment, use the pair /* and */
unsigned char i; // temporary variable /* File: led.c
DDRA = 0x00; // set PORTA for input Description: Simple C program for the ATMEL AVR(ATmega16 chip)
DDRB = 0xFF; // set PORTB for output It lets user turn on LEDs by pressing the switches on the STK500
PORTB = 0x00; // turn ON all LEDs initially board
while(1){ */
// Read input from PORTA, which is connected to the 8 switches
i = PINA;
// Send output to PORTB, which is connected to the 8 LEDs
PORTB = i;
Always use comments to make program easy to understand.
}
return 1;
}

Lam Phung © University of Wollongong, 2010. 25 Lam Phung © University of Wollongong, 2010. 26

C statements and blocks 7.3.2 Data types and operators


C statements
The main data types in C are
‰ C statements control the program flow. ‰ char: 8-bit integer
‰ They consist of keywords, expressions and other statements. ‰ int: 16-bit integer
‰ A statement ends with semicolon. ‰ long int: 32-bit integer
DDRB = 0xFF; // set PORTB for output

The above data types can be modified by keyword ‘unsigned’


C blocks char a; // a value range -128, 0, …, 127

‰ A C block is a group of statements enclosed by braces {}. unsigned char b; // b value range 0, 1, 2, …, 255
unsigned long int c; // c value range 0,…, 232 - 1
‰ Usually, a C block is run depending on some logical conditions.
while (1){
// Read input from PORTA - connected to the 8 switches Some examples of variable assignment
i = PINA; a = 0xA0; // a stores hexadecimal value of A0
// Send output to PORTB - connected to the 8 LEDs b = ‘1’; // b stores ASCII code of character ‘1’
PORTB = i; c = 2000ul; // c stores a unsigned long integer 2000
}
Lam Phung © University of Wollongong, 2010. 27 Lam Phung © University of Wollongong, 2010. 28
C operators Arithmetic operators

C has a rich set of operators Operator Name Example Description


* Multiplication x * y Multiply x times y

‰ Arithmetic operators / Division x / y Divide x by y

‰ Relational operators % Modulo x % y Remainder of x divided by y

‰ Logical operators + Addition x + y Add x and y

- Subtraction x – y Subtract y from x


‰ Bit-wise operators
++ Increment x++ Increment x by 1 after using it
‰ Data access operators
++x Increment x by 1 before using it

‰ Miscellaneous operators -- Decrement x-- Decrement x by 1 after using it


--x Decrement x by 1 before using it

- Negation -x Negate x

Lam Phung © University of Wollongong, 2010. 29 Lam Phung © University of Wollongong, 2010. 30

Relational operators Logical operators

Operator Name Example Description These operate on logical variables/constants.


> Greater than x > 5 1 if x is greater than 5, 0 otherwise
Operator Name Example Description
>= Greater than or x >=5 1 is x is greater than or equal to 5, 0 otherwise
equal to ! Logical NOT !x 1 if x is 0, otherwise 0

< Less than x < y 1 if x is smaller than y, 0 otherwise && Logical AND x && y 1 is both x and y are 1, otherwise 0

<= Less than or x <= y 1 is x is smaller than or equal to y, 0 otherwise || Logical OR x || y 0 if both x and y are 0, otherwise 1
equal to
== Equal to x == y 1 is x is equal to y, 0 otherwise

!= Not equal to x != 4 1 is x is not equal to 4, 0 otherwise

Lam Phung © University of Wollongong, 2010. 31 Lam Phung © University of Wollongong, 2010. 32
Bit-wise operators Data-access operators

These operate on arrays, structures or pointers.


These operate on individual bits of a variable/constant.
We’ll learn more about these operators later.
Operator Name Example Description
~ Bit-wise ~x Toggle every bit from 0 to 1, or 1 to 0 Operator Name Example Description
complement [] Array element x[2] Third element of array x
& Bitwise AND x & y Bitwise AND of x and y
. Member selection x.age Field ‘age’ of structure variable x
| Bitwise OR x | y Bitwise OR of x and y
-> Member selection p->age Field ‘age’ of structure pointer p
^ Bitwise XOR x ^ y Bitwise XOR of x and y
* Indirection *p Content of memory location pointed by p
<< Shift left x << 3 Shift bits in x three positions to the left
& Address of &x Address of the memory location where
>> Shift right x >> 1 Shift bits in x one position to the right variable x is stored

Lam Phung © University of Wollongong, 2010. 33 Lam Phung © University of Wollongong, 2010. 34

Miscellaneous operators 7.3.3 Flow control in C

By default, C statements are executed sequentially.

Operator Name Example Description To change the program flow, there are six types of statements
() Function _delay_ms(250) Call a function to create delay of
250ms ‰ if-else statement
Conditional
(type) Type cast char x = 3; x is 8-bit integer ‰ switch statement
(int) x x is converted to 16-bit integer
? Conditional char x; This is equivalent to
‰ while statement
evaluation y=(x>5)?10:20; if (x > 5)
y = 10; ‰ for statement Iterative
else ‰ do statement
y = 20;

‰ goto statement Should be avoided!


commonly used by C coders.

Lam Phung © University of Wollongong, 2010. 35 Lam Phung © University of Wollongong, 2010. 36
If-else statement Switch statement
General syntax General syntax
if (expression)
switch (expression)
statement_1; case constant_1:
else statement_1;
statement_2; break;
case constant_2:
Example code statement_2;
char a, b, sum; break;
a = 4; b = -5; …
sum = a + b; case constant_n: Use ‘break’ to separate
if (sum < 0) statement_n; different cases.
printf(“sum is negative”); break;
else if (sum > 0) default:
printf(“sum is positive”); statement_other;
else }
printf(“sum is zero”);

Lam Phung © University of Wollongong, 2010. 37 Lam Phung © University of Wollongong, 2010. 38

Switch statement ─ Example Switch statement ─ Example

Lab 7: Find the bit pattern to display a digit on the 7-segment LED. 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:
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 PORTB = led_pattern; // send to PORTB and 7-segment LED

Lam Phung © University of Wollongong, 2010. 39 Lam Phung © University of Wollongong, 2010. 40
While statement For statement
General syntax
General syntax
for (expression1; expression2; expression3){
while (expression){ statements;
statements; }
}
‰ expression1 is run before the loop starts.
‰ expression2 is evaluated before each iteration.
Example code: Compute the sum of 1 + 2+ …+ 100
‰ expression3 is run after each iteration.

int sum, i; Example code: Compute the sum of 1 + 2+ …+ 10


i = 1; sum = 0; int sum;
while (i <= 100){ sum = 0;
sum = sum + i;
i = i + 1; for (int i = 1; i <= 10; i++){
} sum = sum + i;
}
Lam Phung © University of Wollongong, 2010. 41 Lam Phung © University of Wollongong, 2010. 42

Do statement Break statement in loop

General syntax The ‘break’ statement inside a loop forces early termination of the
do { loop.
statements;
} while (expression);
What is the value of ‘sum’ after the following code is executed?

Example code: compute the sum of 1 + 2 + … + 10 int sum, i;


i = 1; sum = 0;
int sum, i; while (i <= 10){
i = 1; sum = 0; sum = sum + i;
do{ i = i + 1;
sum = sum + i; if (i > 5)
i = i + 1; break;
} while (i <= 10); }

Lam Phung © University of Wollongong, 2010. 43 Lam Phung © University of Wollongong, 2010. 44
Continue statement in loop C arrays
An array is a list of values that have the same data type.
The ‘continue’ statement skips the subsequent statements in the
code block and forces the execution of the next iteration. In C, array index starts from 0.

An array can be one-dimensional, two-dimensional or more.

What is the value of ‘sum’ after the following code is executed?


This code example creates a 2-D array (multiplication table):
int a[8][10];
int sum, i; for (int i = 0; i < 8; i++)
i = 1; sum = 0; for (int j = 0; i < 10; j++)
while (i <= 10){ a[i][j]= i * j;
i = i + 1;
if (i < 5)
An array can be initialized when it is declared.
continue;
int b[3] = {4, 1, 10};
sum = sum + i; unsigned char keypad_key[3][4] = {{'1', '4', '7', '*'},
} {'2', '5', '8', '0'},
{'3', '6', '9', '#'}};

Lam Phung © University of Wollongong, 2010. 45 Lam Phung © University of Wollongong, 2010. 46

7.3.4 C functions Functions ─ Example 1

C functions are sub-routines that can be called from the main Write a function to compute the factorial n! for a given n.
program or other functions.

// factorial is the name of the custom function


// it accepts an input n of type int, and return an output of type int
Functions enable modular designs, code reuse, and hiding of int factorial(int n){
complex implementation details. int prod = 1;
for (int i = 1; i <=n; i++)
prod = prod * i;
return prod; // return the result
A C function can have a list of parameters and produce a return }
value. int main(void){
int n = 5; // some example value of n
int v; // variable to storage result
v = factorial(n); // call the function, store return value in v
Let us study C functions through examples. return 1;
}

Lam Phung © University of Wollongong, 2010. 47 Lam Phung © University of Wollongong, 2010. 48
Functions ─ Example 2 Guidelines on C coding and documentation
Optimize the C code for efficiency and length.
Write a function to compute the factorial n! for a given n.
Delete unnecessary lines of code.
The C code must be properly formatted.
// factorial is the name of the custom function
// it accepts an input n of type int, For printing, use a fixed-width font such as Courier New for code.
// it stores output at memory location by int pointer p
void factorial(int n, int* p){ Use indentation to show the logical structure of the program.
int prod = 1;
for (int i = 1; i <=n; i++) Use a blank line to separate code sections.
prod = prod * i;
*p = prod;// store output at memory location pointed by p Use meaningful variable names and function names.
}
If a C statement is too long for one printed line, split it logically into
int main(void){
int n = 5; // some example value of n multiple lines.
int v; // variable to storage result
factorial(n, &v); // call the function, store return value in v Use C comments concisely to explain code.
}
Observe the way that C code is presented in the lecture notes or
lab notes.

Lam Phung © University of Wollongong, 2010. 49 Lam Phung © University of Wollongong, 2010. 50

7.4 Digital IO in ATmega16 Digital IO in ATmega16 ─ Pins

ATmega16 has fours 8-bit digital IO ports:


‰ PORT A,
‰ PORT B,
‰ PORT C, and
‰ PORT D.

Each port has 8 data pins.

Every port is bi-directional. Each of the 8 pins can be individually


configured as
‰ input (receiving data into microcontroller), or
‰ output (sending data from microcontroller).

Lam Phung © University of Wollongong, 2010. 51 Lam Phung © University of Wollongong, 2010. 52
Digital IO in ATmega16 ─ Configuring for input/output Digital IO in ATmega16 ─ Reading from/Writing to Port
For each port, there are three relevant 8-bit registers. Register Data Register (PORTx) is used to write output data to port.
‰ Data Direction Register (DDRx) ‰ Example: To write a binary 0 to output pin 6, binary 1 to other
‰ Input Pins Address (PINx) pins of Port A, we write C code
PORTA = 0b10111111; // write output
‰ Data Register (PORTx)
Here, x denotes A, B, C or D.
Register Input Pins Address (PINx) is used to read input data from port.
Data Direction Register (DDRx) is used to configure a specific port ‰ Example: To read the input pins of Port A, we write C code
pin as output (1) or input (0). unsigned char temp; // temporary variable
temp = PINA; // read input
‰ Example: To set Port A pins 0 to 3 for input, pins 4 to 7 for
output, we write C code Where do the C names PINA, PORTA, DDRA come from?
DDRA = 0b11110000; // configure pins // extract for header file <avr/iom16>
bit 7 6 5 4 3 2 1 0 #define PINA _SFR_IO8(0x19)
DDRA 1 1 1 1 0 0 0 0 #define DDRA _SFR_IO8(0x1A)

for input #define PORTA _SFR_IO8(0x1B)…


for output
Lam Phung © University of Wollongong, 2010. 53 Lam Phung © University of Wollongong, 2010. 54

AVR header file Digital IO in ATmega16 ─ Example


/* File: led.c
To access all AVR microcontroller registers, your program must 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 the header file <io.h>, which is found in the WinAVR folder. */
#include <avr/io.h> #include <avr/io.h> // AVR header file for all registers/pins
int main(void){
unsigned char i; // temporary variable
Depending on which device selected in your project, file ‘io.h’ will DDRA = 0x00; // set PORTA for input
automatically redirect to a specific header file. DDRB = 0xFF; // set PORTB for output
PORTB = 0x00; // turn ON all LEDs initially

Example while(1){
// Read input from PORTA.
‰ For ATmega16, the specific header file is ‘avr/iom16.h’. // This port will be connected to the 8 switches
i = PINA;
‰ This header file is printed in Appendix A of the lab notes.
‰ The header file lists the C names for all registers in ATmega16, // Send output to PORTB.
// This port will be connected to the 8 LEDs
and their memory locations. PORTB = i;
} Demo in
‰ We always use the C names in our code. return 1; slide 15.
}
Lam Phung © University of Wollongong, 2010. 55 Lam Phung © University of Wollongong, 2010. 56
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.

Lam Phung © University of Wollongong, 2010. 57

Anda mungkin juga menyukai