EE470 Microcontrollers and Embedded Systems
EE470 Microcontrollers and Embedded Systems
Microcontrollers and
Embedded Systems
Week 6: Checkpoint and Examples
1
Outline
• Midterm
• Common mistakes
• Feedback from you
• Summary
• Examples
2
ATmega328 Pin-out
3
Common Errors
• Shift operator:
- What register? What bit?
• Serial comm.: the pins are defined as input or output!
• Comments in the Lab manual
4
Feedback
• Lectures:
- Face-to-face, online, recorded
- Pace
• Lab:
- Pre-lab
- Lab
• Other suggestions?
5
Summary
6
Input-Output Ports
• Programming steps:
1. DDRx: configure as input or output
7
Timers – Normal Mode
• Programming steps
1. TCNT0 = initial value.
2. TCCR0A = 0
3. TCCR0B = clk source and prescalar
4. overflow flag (TOV0): 0 or 1 (if 1, do something)
5. TCCR0B = 0 (Stop the timer)
6. Clear the TOV0 flag for the next round.
7. Go back to Step 1 to load TCNT0 again.
8
Timers – CTC
• Programming steps
1. Configure pins (PD5/6) as output, if needed
2. Turn off TC0 (TCCR0B=0)
3. OCR0A (and OCR0B if needed)
4. TCCR0A: COM0x[1:0] and WGM0[1:0]
5. TCCR0B: WGM0[2] and CS0[2:0].
6. Monitor Flags (OC0x)
9
Timers – PWM
• Programming steps
1. Configure pins (PD5/6) as output
2. Turn off TC0 (TCCR0B=0)
3. OCR0x
4. TCCR0A: COM0x[1:0] and WGM0[1:0]
5. TCCR0B: WGM0[2] and CS0[2:0].
10
Examples
• Motors:
- Speed measurement
• Cruise control
• Conveyer belt
- Angle or position
- Starting
• Multi-click or long key-down
- Elevator
• Cascaded/Chained timers
• Debounce
11
Example 9-41
Write a C program to toggle only the PORTB.4 bit continuously every 2 ms.
Use Timer1, Normal mode, and no prescaler to create the delay. Assume
XTAL = 8 MHz.
12
13
Example 9-44
Assume that a 1-Hz external clock is being fed into pin T1 (PD5). Write a C
program for TC1 in rising edge mode to count the pulses and display the
TCNT1H and TCNT1L registers on PORTD and PORTC, respectively
14
Example 15-31 (15-8)
#include “ee470avr.h"
int main ( ) {
• Assuming XTAL = 1 MHz, bitset(DDRD,PD6);
draw the wave generated while (1) {
bitset(TCCR0A,COM0A1);
by the following program bitset(TCCR0A,COM0A0);
bitset(TCCR0A,WGM01);
TCCR0B = 0x01;
OCR0A = 69;
while (bittst(TIFR0,OCF0A) == 0);
bitset(TIFR0,OCF0A);
bitset(TCCR0A,COM0A1);
bitset(TCCR0A,WGM01);
OCR0A = 99;
while (bittst(TIFR0,OCF0A) == 0);
bitset(TIFR0,OCF0A);
}
return 0;
} 15
Example 15-39 (15-23)
Assuming that clock pulses are fed into pin PORTB.0, write a program to
measure the period of the pulses. Place the binary result on PORTC and
PORTD.
16