Professional Documents
Culture Documents
Arduinocourse 30-01-23
Arduinocourse 30-01-23
1 2 3 4 5 6 7 8 9 10
Chapter 1
INTRODUCTION TO EMBEDDED SYSTEM
System Example
11
Chip Density
Number of
Chip density transistor
SSI 10
MSI (1960s) 100
LSI(1970s) 1000
VLSI(1980s) 10000
ULSI(now) 1000000
IC Manufacturing
15
Harvard Architecture in AVR
EEPROM TIMERS
Progra GPRs SRAM
m Flash
ROM CPU
Data bus
Address bus
Data bus
Address bus Control bus
Control bus
Interrup Ports Other
t Units Peripherals
On Chip
Debugger
17
Atmel Atmega32
Central Processing Unit
Arithmetic Logic Unit (ALU)
performs the actual arithmetic,
logical, and bit-functions
Memory – SRAM, EEPROM, Flash
Clock circuit – internal/external
I/O – Input/Output; video, serial,
parallel, USB, SCSI, etc.
2.1 Memory
3 Separate on-chip memories
8 bits of register (MSB : most significant bit [D7]; LSB: Least significant bit[D0))
D7 D6 D5 D4 D3 D2 D1 D0
2.3 Special-purpose Registers
Special-purpose Registers can also be operated upon directly by
the ALU (with certain specific instructions)
Stack pointer (SP, 16-bit)
Stores return address of
subroutine/interrupt calls
Storing temporary data
and local variables
23
2.4 The machine-instruction is executed by the
Central Processing Unit
• When the device is powered-on, the Program Counter is
set to 0.
• The instruction at the location in Flash Memory at the
address indicated by the Program Counter is fetched
and placed in the Instruction Register
• The opcode and operands within the instruction are
extracted by the Instruction Decoder
• The control lines from the I.D. activate the particular
circuitry within the ALU that is capable of processing that
particular opcode. The ALU executes the instruction.
• The Program Counter is automatically incremented and
the cycle repeats.
24
Instruction execution timing
25
2.5 Overview assembly language instructions
• Describing operations in a
seminatural language
• Increase the portability
High- Levels Language of the code
• One line may involve many
low-level operations
• Ex: C,C++
• Tied to the specifics of the
underlying machine
Three Levels of Languages Assembly Languages • Commands and names to
make the code readable and
writeable by humans
• Hand-coded assembly code
may be more efficient
Machine Languages
26
2.5 Overview assembly language instructions
29
Yet another Development System: AVRStudio
30
31
Chapter 3
C PROGRAMMING in Arduino (AVR
microcontroller)
Arduino
Environment
Operating voltage → 5V
Input Voltage →7-12V
Digital I/O pins → 14 pins → 0:13
Analog input pins → 6 pins → A0:A5
Flash Memory → 32KB
Clock speed → 16MHz
Arduino Pins
Digital Analog
▶ Can be only Two Value 0volt or 5Volt ▶ Can be any Value from 0Volt to 5Volt
▶ Arduino Has 14 Digital Input / Output Pins ▶ Arduino Has 6 Analog Input Pins
Power
▶ How bright is it ?
▶ How loud is it?
▶ How humid is it?
▶ How distance is it ?
▶ Is the button being pressed?
▶ Is there motion ?
Sensors
Symbol Operation
}
• Break → use to stop operation
int sensorPin = A0; // chọn chân analog A0 cho cảm biến
int sensorValue; // khai báo biến để lưu giá trị từ cảm biến
void setup() {
// Khởi tạo serial port với tốc độ truyền dữ liệu là 9600 bps
Serial.begin(9600);
}
void loop() {
// Đọc giá trị từ cảm biến
sensorValue = analogRead(sensorPin);
delay(1000); // đợi 1 giây trước khi đọc giá trị từ cảm biến lần tiếp
}
Loop Statements
▶ For Loop
▶ While Loop
▶ Do-while loop
▶ Nested Loop
▶ Infinite Loop
For statement for ( expr1; expr2; expr3; )
{ statement }
▶ expr1→ initialization
▶ expr2→ termination
▶ expr3→ step
#include <Servo.h>
void setup() {
myservo.attach(9); // Chọn chân số 9 để điều khiển servo
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // Lặp lại từ 0 đến 180 độ với bước nhảy là 1 độ
myservo.write(pos); // Gửi tín hiệu điều khiển đến servo
delay(15); // Đợi 15ms trước khi xoay tiếp
}
for (pos = 180; pos >= 0; pos -= 1) { // Lặp lại từ 180 đến 0 độ với bước nhảy là 1 độ
myservo.write(pos); // Gửi tín hiệu điều khiển đến servo
delay(15); // Đợi 15ms trước khi xoay tiếp
}
}
While Loop
int buttonPin = 2; while (expression)
int ledPin = 13; {
bool buttonState = false;
Statements
void setup() {
pinMode(buttonPin, INPUT); }
pinMode(ledPin, OUTPUT);
}
void loop() {
// Đợi người dùng nhấn nút
while (digitalRead(buttonPin) == LOW) {
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
delay(100);
}
}
Do-while
Loop
Nested
Loop
• Using BRNE (Branch if not equal) instruction for looping: Zero flag in the status register is applied
LDI R16,8;
BACK: SBI DDRB, 0 ; Set PB0 as Output
SBI PORTB,0
DEC R16
BRNE BACK
• Loop inside loop
LDI R20,10;
LOOP_1: LDI R21,70
LOOP_2: DEC R21
BRNE LOOP_2
DEC R20
BRNE LOOP_1
RET Instruction and the role of stack
When the RET instruction at the end of the subroutine is executed
.ORG 0
BACK:
LDI R16, 0x55;
OUT PORTB, R16;
CALL DELAY
LDI R16,0xAA;
OUT PORTB,R16;
CALL DELAY;
RJMP BACK;
.ORG 0x300;
DELAY:
LDI R20,0xFF;
AGAIN:
NOP;
NOP;
DEC R20;
BRNE AGAIN;
RET;
Chapter 4
Input /Output Ports
Ports of AVR ATmega32
Port B Port A
Port C
Port D
ATMega32 Pin out & Descriptions
Ports of AVR ATmega32
• Each port has three I/O registers associated with it
• Each bit in I/O registers affects on of the pins
• DDRx: Data Direction Register : is used solely for purpose of making a given port
an input or output
DDRx Register Role in Outputting Data
• Each of the Ports A-D in ATmega32 can be used for Input or
Output.
• DDRx I/O register is used solely for the purpose of making a
given port input or output port.
• For example, to make a port an output, we write 1s to the
DDRx register.
• In other words, to output data to all of the pins of Port B, we
must first put 0b11111111 (0xFF) into DDRB register to make
all the pins output.
How data is sent to the output port?
• Once you set the direction of a port as
output, the data that you want to send to
the output, you have to write that data into
PORTx I/O register.
• If DDRC=0xFF and then PORTC=0x3B, the
data at the output will also be 0x3B.
• That is -
0 0 1 1 1 0 1 1
PC7 PC6 PC5 PC4 PC3 PC2 PC1 PC0
DDRx Register Role in Inputting Data
• To make a port an input port, we must first
put 0s into the DDRx register for that port.
• Then we can read the data which is residing
at the pins of Port x.
• Notice that upon reset, all ports have the
value 0x00 in their DDRx registers.
• That is all ports upon reset remains as input
ports.
How data is read from the Input Port?
• Once you set the direction of a port as input,
the data that you want to read from the input,
you have to place that data to port pins.
• If DDRB=0x00 and the data presented at the
port pins of Port B port is 0x75, the data will go
to PINB register of I/O memory. You have to
read that reg.
• The content of PINx will be -
PINB
0 1 1 1 0 1 0 1
Register PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0
Role of Pull up resistors at the port pins
• Let us say you have configured a port
pin as input pin.
• If there is nothing connected with the
pin and your program reads the state of
the pin, will it be high of low? It will be
difficult to tell.
A switch connected at the
• This phenomena is referred to as input pin without pull up
floating state. resistor
R GND
PC7
PC6
PC5
PC4
PC3
PC2
PC1
PC0
All LEDs glow and off at an interval of
1 sec. And the process is repeated.
0xFF 1 1 1 1 1 1 1 1
0x00 0 0 0 0 0 0 0 0
PORTC=0xFF
while (1)
{
PORTC=~PORTC;
delay_ms(1000);
}
}
Alternate LEDs will glow and toggle at
every 1 sec
0xAA 1 0 1 0 1 0 1 0
0x55 0 1 0 1 0 1 0 1
PORTC=0xAA
while (1)
{
PORTC=~PORTC;
delay_ms(1000);
}
}
LED at MSB Position is ON, all others are off. After 1 sec, the
next one is ON. Then the next one and so on. When it
reaches at the LSB one, it starts from MSB again
PORTC 1 0 0 0 0 0 0 0
PORTC>>1 0 1 0 0 0 0 0 0
PORTC=0x80
while (1)
{
PORTC=PORTC>>1;
delay_ms(1000);
if (PORTC==0X01)
PORTC=0X80;
}
LED at MSB Position is ON, all others are off. After 1 sec, the
next one is ON. Then the next one and so on. When it
reaches at the LSB one, it REVERSES.
PORTC 0 0 0 0 0 0 0 1
PORTC<<1 0 0 0 0 0 0 1 0
PORTC=0x80 else
movement=0; {
while (1) PORTC=PORTC<<1;
{ if (PORTC==0x80)
if (movement==0) { movement=0;
PORTC=PORTC>>1; }
if (PORTC==0X01) delay_ms(1000);
movement=1;} }
An Example of Inputting data
• Use Pin 0-7 of PORT D of an ATmega32 chip
for inputting a data.
• Some of the pins are connected to VCC and
some are made grounded.
• Read the data.
• Send the value to PORT C. [The port C is
connected with LEDs]
• Write a C code for the above mentioned
tasks.
Another Example
If Pin 0 of Port D is found to be zero send 0xAA to
Port C, otherwise send 0x55 to Port C
while (1)
{
// Place your code here
if (PIND.0==0)
PORTC=0xAA;
if (PIND.0==1)
PORTC=0x55;
}
}
7-segment display: Introduction
• Seven segment displays are very common for
electronic product to display numerical output.
• Many common devices like calculators, lift,
watches, electronic weighing scales, ovens etc use
them.
• A seven-segment display is so named because it is
divided into seven different segments that can be
switched on or off.
• It can display digits from 0 to 9 and quite a few
characters like A, b, C, ., H, E, e, F, n, o, t, u, y, etc.
• Knowledge about how to interface a seven
segment display to a micro controller is very
essential in designing embedded systems. 96
The Pin Out and Picture of a 7-segment Display
2 4
d
a
b f b b
g g g c
e c e
d d
97
Two types of 7-segment display
• Seven segment displays are of two types,
common cathode and common anode.
• In common cathode type , the cathode (N side)
of all LEDs are tied together to a single
terminal which is usually labeled as ‘com‘ and
the anode (P side) of all LEDs are left alone as
individual pins labeled as a, b, c, d, e, f, g & h
(or dot) .
• In common anode type, the anode of all LEDs
are tied together as a single terminal and
cathodes are left alone as individual pins. 98
Interfacing 7 segment display
+5V
PA.0
b
c
d
e
f Common
g 330 330
PA.7 Cathode
LED ‘dp’ LED ‘a’
GND
Prof. S. M. Lutful Kabir, BUET 99
a
f g b
e c
d dp
0 1 2 3 4 5 6 7 8 9
dp g f e d c b a Hex dig
0 0 1 1 1 1 1 1 3F 0
0 0 0 0 0 1 1 0 06 1
7-Segment
0 1 0 1 1 0 1 1 5B 2
0 1 0 0 1 1 1 1 4F 3
Display
0 1 1 0 0 1 1 0 66 4
0 1 1 0 1 1 0 1 6D 5
0 1 1 1 1 1 0 1 7D 6
0 0 0 0 0 1 1 1 07 7
0 1 1 1 1 1 1 1 7F 8
0 1 1 0 1 1 1 1 6F 9
Multiple 7-Segment Display
• Suppose you need a four digit display connected
to the AVR ATmega32.
• Each 7 segment display have 8 pins and so a total
amount of 32 pins are to the connected to the
microcontroller and there will be no pin left with
the microcontroller for other input output
applications.
• More over four displays will be ON always and
this consumes a considerable amount of power.
• All these problems associated with the straight
forward method can be solved by multiplexing .
101
Multiplexing 7-Segment Display
• In multiplexing all displays are connected in parallel to
one port and only one display is allowed to turn ON at
a time, for a short period.
• This cycle is repeated for at a fast rate and due to the
persistence of vision of human eye, all digits seems to
glow.
• The main advantages of this method are
• Fewer number of port pins are required .
• Consumes less power.
• More number of display units can be interfaced.
• The circuit diagram for multiplexing 4 seven segment
displays to the AVR ATmega32 is shown in the next
slide. 102
Connection Diagram of Multiple 7-segment
Display with AVR ATmega32
Digit 2 Digit 1
PC.0 a a
PC.1 b b
PC.2 c c
d d
PC.3
PC.4 e e
f
PC.5 f g
PC.6 g
dp dp
PC.7
330
PA.1 Q2
PA.0
GND 330
ATmega 32 Q1
GND
LEDs are Common Cathode type 103
How it works
• Let us see how ‘16’ will be displayed in 2 digit
display.
• Initially the first display is only activated by
making PA.0 low and then digit drive pattern for
“1″ is loaded to the Port C.
• This condition is maintained for around 1ms and
then PA.0 is made high.
• Then the second display is activated by making
PA.1 low and then the digit drive pattern for “6″ is
loaded to the port C. This will make the second
display to show “6″. This condition is maintained
for another 1ms.
• This cycle is repeated and due to the persistence of
104
vision you will feel it as “16″.
C Code for 4 digit 7-segment Display
unsigned int anode[10]={0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10};
unsigned int cathode[10]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};
unsigned int select[4]={0x01,0x02,0x04,0x08};
int i=0; j=0;
void show_number(int temp) {
int a=0;
char b=0;
for(b=0;b<4;b++) {
a=temp%10;
temp=temp/10;
PORTA=~select[b];
PORTC=cathode[a]; }
}
105
void main(void) {
while (1) {
for(i=0;i<10000;i++) {
for (j=0;j<500;j++) {
show_number(i);
}
}
}
}
106
USING ARDUINO FUNCTION
Pin mode function of arduino
•pinMode() function
•digitalRead() function
•digitalWrite() function
•analogRead() function
•analogWrite() function
Example: pinMode()
• These function allow access to the pins
• Set a pin to act as an INPUT or OUTOUT or INPUT_PULLUP
pinMode( pin , mode )
Pin
• Is the number of the pin “0:13 for digital
• analog” “A0:A5 for analog pins
Mode
• Is the I/O mode the pin is set to “INPUT” “OUTPUT”
Digital output function
Example: digitalWrite()
• Assign the state of an output pin
• Assign either LOW or HIGH
digitalWrite(pin , Value)
Value
• HIGH
• LOW
GIFR Register
INTF1 INTF0 INTF2 - - - - -
Experiment with Int0
• A push button switch is connected in INT0 (PD.2) pin of the ATmega32
microcontroller.
• The INT0 bit in the GICR register has to be set (i.e. INT0 will be
enables.
• At first, we set falling edge as Interrupt sense control.
• We have to write an ISR which will be executed only when a falling
edge (from 1 to 0) is generated at INT0 pin.
Chương
trình phục
Code (Part-I) vụ ngắt
• interrupt:interrupt number
• ISR: The name of the
function to be called when
an interrupt event is
generated.
• Mode: LOW; HIGH;RISING;
FALLING; CHANGE
•RISING: To trigger an interrupt when the pin transits from LOW to HIGH.
•FALLING: To trigger an interrupt when the pin transits from HIGH to LOW.
•CHANGE: To trigger an interrupt when the pin transits from LOW to HIGH
or HIGH to LOW (i.e., when the pin state changes ).
Experiment with Arduino
Example
void setup() {
pinMode(interruptPin, INPUT_PULLUP); // cấu hình chân ngắt
attachInterrupt(digitalPinToInterrupt(interruptPin), ISR, CHANGE); // đăng ký ngắt
Serial.begin(9600); // cấu hình Serial monitor
}
void loop() {
// thực hiện các hoạt động khác trong vòng lặp chính
}
void ISR() {
state = !state; // cập nhật trạng thái biến
Serial.println(state); // hiển thị giá trị trạng thái mới
}
Chapter 6
ANALOG TO DIGITAL CONVERSION (ADC)
ANALOG TO DIGITAL CONVERSION (ADC)
Objectives: After reading this chapter, the reader should be able to:
• illustrate the analog-to-digital conversion process;
• assess the quality of analog-to-digital conversion using the metrics of sampling rate,
quantization levels, number of bits used for encoding, and dynamic range;
• design signal conditioning circuits to interface sensors to analog-to-digital converters;
• implement signal conditioning circuits with operational amplifiers;
• describe the key registers used during an ATmega328 ADC;
• describe the steps to perform an ADC with the ATmega328;
• program the Arduino UNO R3 processing board to perform an ADC using the builtin features of the
Arduino Development Environment;
• program the ATmega328 to perform an ADC in C; and
• describe the operation of a digital-to-analog converter (DAC).
CH. 6: ANALOG TO DIGITAL CONVERTERS
• Hold – the action of holding the voltage for a brief amount of time by
use of a capacitor.
time
CH. 6: ANALOG TO DIGITAL CONVERTERS
time
• The Sample-and-Hold circuitry is designed so that this can be
accomplished very quickly so that it can disconnect from the input
signal as soon as possible to avoid altering its signal integrity.
CH. 6: ANALOG TO DIGITAL CONVERTERS
VR+
VR- time
• Input Voltage Range – The voltage is digitized within a range of
voltages from:
o Voltage Reference High (VR+)
o Voltage Reference High (VR-)
CH. 6: ANALOG TO DIGITAL CONVERTERS
VR+
VR- time
• The goal of the conversion is to convert the analog voltage into a
digital number.
• This is called digitizing, quantizing, or discretizing.
1
0
VR- time
n=1
Sample=0
• n represents the number of bits in the digital value of the conversion.
1
0
VR- time
n=1
Sample=0
• n represents the number of bits in the digital value of the conversion.
• The input voltage range is divided into 2n discrete zones.
1
0
VR- time
n=1
Sample=0
• The larger the n, the closer the digital value is to the actual analog
voltage.
VR- time
n=4
Sample=0100
• The larger the n, the closer the digital value is to the actual analog
voltage.
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4
Sample=0100
• The number of bits n is called the ADC’s resolution.
VR- time
n=4
Sample=0100
• The number of bits n is called the ADC’s resolution.
• MCU’s typically have ADC’s with resolutions of 8 to 16 bits.
VR- time
n=4
Sample=0100
• The number of bits n is called the ADC’s resolution.
• MCU’s typically have ADC’s with resolutions of 8 to 16 bits.
• The MSP430 has up to 12-bits of resolution.
15.1 ANALOG TO DIGITAL CONVERTERS
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4
Sample=0100
• The precision of an ADC is the smallest voltage that the LSB of the
digital output can represent.
VR- time
n=4
Sample=0100
• The precision of an ADC is the smallest voltage that the LSB of the
digital output can represent.
• This is found by dividing the input voltage
range by the number of discrete zones.
15.1 ANALOG TO DIGITAL CONVERTERS
CH. 15: ANALOG TO DIGITAL CONVERTERS
VR+
VR- time
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4
Sample=0100
• The original analog value is found by multiplying the digital
conversion result (NADC) with the resolution.
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4
Sample=0100
• The accuracy is how close the digital output is to the input signal.
VR- time
n=4
Sample=0100
• The accuracy is how close the digital output is to the input signal.
• By design, an ADC will only ever be able
to get within +/- ½ LSB of the original
analog value.
15.1 ANALOG TO DIGITAL CONVERTERS
CH. 15: ANALOG TO DIGITAL CONVERTERS
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4 0100
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4 0100
1000
VR- time
n=4 0100
1000
0111
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4 0100
1000
0111
0101
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4 0100
1000
0111 1001
0101
VR- time
n=4 0100
1000
0111 1001
0101 1101
VR- time
n=4 0100
1000
0111 1001 1110
0101 1101
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4 0100
1000
0111 1001 1110
0101 1101 1101
VR- time
n=4 0100
1000
0111 1001 1110
0101 1101 1101
TSA
• The sample period (TSA) is the time between samples.
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4 0100
1000
0111 1001 1110
0101 1101 1101
TSA
• The sampling rate is the frequency of sampling: fSA= 1/TSA
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4 0100
1000
0111 1001 1110
0101 1101 1101
TSA
• The sampling rate is the frequency of sampling: fSA= 1/TSA
• This has units of samples-per-second (i.e., ksps, Msps).
15.1 ANALOG TO DIGITAL CONVERTERS
CH. 15: ANALOG TO DIGITAL CONVERTERS
VR+
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
VR- time
n=4 0100
1000
0111 1001 1110
0101 1101 1101
• If you sample fast enough, you can reconstruct the original signal.
VR- time
n=4 0100
1000
0111 1001 1110
0101 1101 1101
• If you sample fast enough, you can reconstruct the original signal.
• Nyquist-Shannon Sampling Theorem states you need to sample at
least twice as fast as the frequency of the incoming signal to
accurately reconstruct the original waveform.
15.1 ANALOG TO DIGITAL CONVERTERS
Topics
• What is ADC and why do we need it?
• ADC major characteristics
• ADC in AVR
• Hardware Consideration
• AVR ADC Programming
• ADCH and ADCL
• ADMUX
• ADCSRA
• DAC
• Signal conditioning and sensors
What is ADC? Do we need it?
• Analogue vs. digital signal
Major Characteristic of ADC
Example
ADC major characteristics
• Conversion Time Step Size
• Resolution
• Vref
• Parallel vs. serial
• Input channels
Successive Approximation Method
Some of ADC Signals
• Dout = Vin / Step size
( in 8 bit ADC and Vref = 2.56 what is D out for 20mV input voltage?)
• Start of Conversion
• Channel Selector
ADC in AVR
• Atmega 16/32 have internal ADC
• 8 analogue input channel
• 7 differential input channel
• 2 differential input channel with 10x or 200x gain
• 3 source of Vref
• Internal 2.56V Vref generator
ATMEGA32 ADC FEATURES
Hardware Consideration
ADCH and ADCL Data registers
• ADCH:ADCL store the results
of conversion.
• The 10 bit result can be right
or left justified:
ADLAR = 0
ADLAR =1
ADMUX
ADC input selection
ADCSRA
ADMUX
ADC Prescaler
• PreScaler Bits let us change the clock frequency of ADC
• The frequency of ADC should not be more than 200 KHz
• Conversion time is longer in the first conversion
Programming ADC
Ex 1 Reading ADC Using Polling
Ex 1 Reading ADC Using Interrupt
DAC • What is DAC ?
• How to connect an DAC to AVR?
AVR Connection to DAC
Example
DAC Programming
Output
Signal conditioning
void setup() {
Serial.begin(9600);
}
void loop() {
digitalOutput = analogRead(inputAnalogPin);// read analog
channel value
Serial.print("digitalOutput = ");
Serial.println(digitalOutput); //print digital output on
serial monitor
delay(1000);
}
Chapter 7
TIMER/ COUNTER/ PWM STRUCTURE
TIMER
Measuring time: Timers are used to measure time in applications such as speed measurement, response time
measurement, waiting time measurement, time between events measurement, etc.
Frequency control: Timers are used to generate pulse signals with fixed or variable frequencies, which are used to
control peripheral devices such as motors, light bulbs, speakers, etc.
Communication: Timers are used to generate pulse signals for data communication between devices, as in protocols
such as UART, SPI, I2C, etc.
Display: Timers are used to scan LED lights to display numbers or characters on LED, LCD screens, etc.
Accuracy checking: Timers are used to check the accuracy of quartz crystals or other frequency sources.
Scheduling: Timers are used to set schedules for applications such as clocks, alarms, etc. Protection: Timers are used
to monitor system activities and protect them from errors such as overcurrent, overload.
TIMER
Timer là một chức năng quan trọng của vi điều khiển và có nhiều ứng dụng khác nhau trong các hệ thống
điện tử và các ứng dụng lập trình nhúng. Sau đây là một số ứng dụng của timer:
1.Đo thời gian: Timer được sử dụng để đo thời gian trong các ứng dụng như đo tốc độ, đo thời gian phản hồi,
đo thời gian chờ, đo thời gian giữa các sự kiện, vv.
2.Điều khiển tần số: Timer được sử dụng để tạo ra các tín hiệu xung với tần số cố định hoặc biến đổi, được
sử dụng để điều khiển các thiết bị ngoại vi như động cơ, bóng đèn, loa, vv.
3.Giao tiếp: Timer được sử dụng để tạo ra các tín hiệu xung để truyền thông dữ liệu giữa các thiết bị, như
trong các giao thức như UART, SPI, I2C, vv.
4.Hiển thị: Timer được sử dụng để quét các đèn LED để hiển thị các số hoặc ký tự trên các màn hình LED,
LCD, vv.
5.Kiểm tra độ chính xác: Timer được sử dụng để kiểm tra độ chính xác của các thạch anh hoặc các nguồn
tần số khác.
6.Lập lịch: Timer được sử dụng để thiết lập lịch cho các ứng dụng như đồng hồ, báo thức, vv.
7.Bảo vệ: Timer được sử dụng để giám sát các hoạt động của hệ thống và bảo vệ chúng khỏi các lỗi như quá
dòng, quá tải.
Counter mode and Timer mode
• There are counter registers in microcontrollers to count an
event or generate time delays.
• When we connect the external event source to the clock pin
of the counter register. This is counter mode.
• When we connect the oscillator to the clock pin of the
counter. This is timer mode
• one way to generate a time delay is to clear the counter at
the start time and wait until the counter reaches a certain
number.
Counter mode and Timer mode
• In the microcontrollers, there is a flag for each of the
counters. The flag is set when the counter overflows, and
is cleared by software.
• The second method to generate a time delay is to load
the counter register and wait until the counter overflows
and the flag is set.
• In ATmega32,ATmega16, there are three timers: Timer0,
Timer1, and Timer2. TimerO and Timer2 are 8-bit, while
Timer1 is 16-bit.
• In AVR, for each of the timers, there is a TCNTn
(timer/counter) register. In ATmega32 we have TCNTO,
TCNT1, and TCNT2.
• The TCNTn register is a counter. Upon reset, the TCNTn
contains zero. It counts up with each pulse. The contents
of the timers/ counters can be accessed using the
TCNTn. You can load/read a value into the TCNTn register
Basic Registers of Timers
• Each timer has a TOVn
(Timer Overflow) flag, When a
timer overflows, its TOVn flag is
set.
• Each timer also has the TCCRn
(timer/counter control register)
register for setting modes(timer
or counter) of operation.
• Each timer also has an OCRn
(Output Compare Register). The
content of the OCRn is
compared with the content of
the TCNTn. When they are
equal the OCFn (Output
Compare Flag) flag is set.
Timer0 Programming
• Timer0 is 8-bit in ATmega32; thus, TCNT0 (timer/ counter
register) is 8-bit.
1 1 Fast PWM
But we should use the option Prescaler = 64 sinece we can not use a decimal point.
Due to prescaler = 1024 each timer clock lasts 1024 × 0.125 µs = 128 µs.
Thus in order to generate a delay of 25.6 ms,
we should wait 25.6 ms / 128 µs = 200 clocks.
Notice that the comparator checks for equality; thus, if we load OCR0
register wuth a value smaller than TCNT0’s value, the counter will miss
the compare match and will count up until it reaches the maximum value
of 0xFF and rolls over. This causes a big delay and is not desirable in
many cases.
Registers Related to Timer0
• TCNT2 register - the number of pulse Timer2 counts
bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
Timer 2
TOV2 Timer2 Overflow flag bit
OCF2Timer2 output compare flag bit
ASSR (Asynchronous Status Register)
ASSR Register
AS2 TCN2UB OCR2UB TCR2UB
The DDRC.0=1;
// Timer/Counter 2 initialization
// Clock source: TOSC1 pin
Program // Clock value: PCK2/1024
// Mode: Normal top=0xFF
Code // OC2 output: Disconnected
ASSR=1<<AS2;
TCCR2=(0<<PWM2) | (0<<COM21) | (0<<COM20) | (0<<CTC2)
| (1<<CS22) | (1<<CS21) | (1<<CS20);
#include <mega32.h> TCNT2=0x00;
// Timer2 output OCR2=0x20;
compare interrupt service // Timer(s)/Counter(s) Interrupt(s) initialization
routine TIMSK=(1<<OCIE2) | (0<<TOIE2) | (0<<TICIE1) | (0<<OCIE1A) |
(0<<OCIE1B) | (0<<TOIE1) | (0<<OCIE0) | (0<<TOIE0);
interrupt [TIM2_COMP]
// Global enable interrupts
void
timer2_comp_isr(void) #asm("sei")
PORTC=0x00;
{ while (1)
PORTC.0=~PORTC.0; {
}
TCNT2=0x00;
}
}
Adding Virtual Instrument : Oscilloscope
Output in the Oscilloscope
Adding Signal Generators
The Outputs
Timer1 Programming
• Timer1 is a 16-bit timer and has lots of
capabilities.
• It is split into two bytes. These are referred to
TCNT1L and TCNT1H.
• Timer1 has two control registers, namely TCCR1A
(8-bit) and TCCR1B (8-bit).
• TOV1 flag bit goes high when overflow occurs.
• There are two OCR registers, namely OCR1A(16-
bit) and OCR1B(16-bit).
• There are two separate flags for each of two OCR
registers, which acts independently. The figure in
the next slide explains how they work.
Comparisons and Overflow in Timer1
Ref.
Reg. B
OCR1BH OCR1BL
= OCF1B flag
Timer
TCNT1H TCNT1L
Reg.
flag TOV1 = OCF1A flag
Ref.
Reg. A
OCR1AH OCR1AL
TIFR (Timer/Counter) Interrupt Flag
Register
TIFR Register
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0
Timer 1
TOV1 Timer1 overflow flag bit;
OCF1B Timer 1 output compare B match flag
OCF1A Timer 1 output compare A match flag
ICF1 Input Capture flag
TCCR1A & TCCR1B (Timer Counter Control
Registers)
TCCR1A Register
COM1A1 COM1A0 COM1B1 COM1B0 FOC1A1 FOC1B WGM11 WGM10
1 B1 B1
TCCR1B Register
ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10
1
FOC1A, FOC1B – Related to force compare
ICNC1, ICES1 – Related to Input Capture
COM1A1, COM1A0, COM1B1, COM1B0
– Related to Waveform
Generation
WGM13, WGM12, WGM11, WGM10 – Mode Selection
CS12, CS11, CS10 – Clock Selection
Block Diagram for Timer1
CLkI/O STOP 0
CLK 1
CLK/8 2
CLK/64 3
PRESCALER MUX
CLK/256 4
CLK/1024 5
Falling Edge
EDGE 6
DETECTOR Rising Edge
72 1 0
T1
CS11CS10
CS12
Mode Selection
Output
(PWM Wave of discrete frequency)
Timer Register Resets : Normal
Input
6. Input Capture in ICP1 pin, (Time Period & DC)
Different Cases (Discussed so far)
• Case #1- WGM: NORMAL & COM: Normal
• Case #2- 2a. WGM: NORMAL & COM: OC1A or OC1B
toggles at Compare Match
WGM: CTC & COM: OC1A or OC1B
toggles at Compare Match
• Case #3. WGM: Fast PWM & COM: OC1A or OC1B
output pin sets at Compare Match and clears
at
TOP or opposite
• Case #5. WGM: Normal & COM: Normal
Input Capture & OVERFLOW Interrupt is
enable and
Edge mode is selected
TCCR1A & TCCR1B (Timer Counter Control
Registers)
TCCR1A Register
COM1A1 COM1A0 COM1B1 COM1B0 FOC1A1 FOC1B WGM11 WGM10
1 B1 B1
TCCR1B Register
ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10
1
FOC1A, FOC1B – Related to force compare
ICNC1, ICES1 – Related to Input Capture
COM1A1, COM1A0, COM1B1, COM1B0
– Related to Waveform
Generation
WGM13, WGM12, WGM11, WGM10 – Mode Selection
CS12, CS11, CS10 – Clock Selection
Modes in Timer 1
What is Input Capture?
• In input capture function is widely used for many applications.
Among them, a few are
• Recording the arrival time of an event,
• Pulse width measurement and
• Period measurement.
• In ATmega32, Timer1 can be used as the Input Capture to detect
and measure the events happening outside the chip.
• Upon detection of an event, the TCNT1 register value is loaded
into ICR1 register.
• And the ICF1 flag is set
TIMSK Register
Input Capture
Principle of Calculating Time Period of
a Square Wave
First Next rising
rising edge
edge
ICP1
INT0
The Code (First char disp1[16];
Part) char disp2[16];
#include <mega32.h> int count_TP=0;
#include <stdlib.h> int count_DC=0;
#include <alcd.h>
float TP=0;
#include <string.h>
float TDC=0;
long int float freq=0;
new_value_TP=0;
float duty=0;
long int prv_value_TP=0;
long int float Ttick=1/(16*1e6);
new_value_DC=0; float Tov=65535/(16*1e6);
long int prv_value_DC=0;
int edge=1;
The Code (2nd Part)
// Timer1 overflow interrupt // Timer1 input capture interrupt
service routine service routine
interrupt [TIM1_OVF] void interrupt [TIM1_CAPT] void
timer1_ovf_isr(void) timer1_capt_isr(void)
{ {
count_TP++; new_value_TP=ICR1H*256+ICR1L;
TP=count_TP*Tov+(new_value_TP-
count_DC++;
prv_value_TP)*Ttick;
}
freq=1/TP;
prv_value_TP=new_value_TP;
count_TP=0;
}
The Code (3rd Part)
interrupt [EXT_INT0]
void ext_int0_isr(void)
{ else
if (edge==1) {
{ new_value_DC=TCNT1H*2
56+TCNT1L;
prv_value_DC=TCNT1H
*256+TCNT1L; TDC=count_DC*Tov+(new_
edge=2; value_DC-
prv_value_DC)*Ttick;
count_DC=0; edge=1;
} count_DC=0;
}
}
void main(void)
{ The Code (4th Part)
TCCR1A=(0<<COM1A1) | (0<<COM1A0)
| (0<<COM1B1) | (0<<COM1B0) | // Timer(s)/Counter(s) Interrupt(s)
(0<<WGM11) | (0<<WGM10); initialization
TIMSK=(0<<OCIE2) | (0<<TOIE2) |
TCCR1B=(0<<ICNC1) | (1<<ICES1) | (1<<TICIE1) | (0<<OCIE1A) |
(0<<WGM13) | (0<<WGM12) | (0<<OCIE1B) | (1<<TOIE1) |
(0<<CS12) | (0<<CS11) | (1<<CS10); (0<<OCIE0) | (0<<TOIE0);
TCNT1H=0x00;
TCNT1L=0x00; // External Interrupt(s)
initialization
ICR1H=0x00; GICR|=(0<<INT1) | (1<<INT0) |
ICR1L=0x00; (0<<INT2);
MCUCR=(0<<ISC11) | (0<<ISC10) |
OCR1AH=0x00; (0<<ISC01) | (1<<ISC00);
OCR1AL=0x00; MCUCSR=(0<<ISC2);
OCR1BH=0x00; GIFR=(0<<INTF1) | (1<<INTF0) |
(0<<INTF2);
OCR1BL=0x00;
The Code (5th Part)
lcd_init(16); lcd_clear();
// Global enable interrupts lcd_gotoxy(0,0);
#asm("sei") lcd_puts(disp2);
while (1) ftoa(duty,2,disp1);
{
strcpy(disp2,"duty (%) = ");
if (count_TP==0)
strcat(disp2,disp1);
{
lcd_gotoxy(0,1);
if (TDC!=0)
lcd_puts(disp2);
duty=100-TDC*100/TP;
}
ftoa(freq,2,disp1);
strcpy(disp2,"freq(Hz) = "); }
strcat(disp2,disp1); }
Input in Virtual Oscilloscope and Output in LCD
Display
1 div=0.2s
So, T = 5div =1s.
f=1Hz
Duty cycle
=1.8*100/5
1.8 div =36%
5
div
Generation of PWM having Variable Frequency
• Previously we discussed about fixed frequency
PWM
• It was fixed frequency because the Timer register
Resets at TOP value
• In order to obtain variable frequency PWM we
need to have a choice of WGM where Timer
Register Resents at ICR1 register value.
• Let us follow the diagram of the next slide.
Value increases
Value in in TCNT0 Register
ICR1
Your Set
Values in
OCR0
Time Period, T1
Connection at OC1A (PD.5) pin
Calculation
• Fosc=16MHz
• Ttick=(1/16) uS
• OCR1=1FFF h = 8191 d
• ICR1 = AFFF h = 45055 d
• Tp = ICR1 * Ttick
=45055 * (1/16) * (1e-6)=0.00282s=2.82mS
• TON=OCR1A * Ttick
=8191* (1/16) * (1e-6)=0.000511s=0.511mS
The Code
#include <mega32.h> TCNT1H=0x00;
void main(void) TCNT1L=0x00;
{ ICR1H=0xAF;
DDRD.5=1; ICR1L=0xFF;
TCCR1A=(1<<COM1A1) | OCR1AH=0x3F;
(0<<COM1A0) |
(0<<COM1B1) | OCR1AL=0xFF;
(0<<COM1B0) | OCR1BH=0x00;
(1<<WGM11) | OCR1BL=0x00;
(0<<WGM10);
TCCR1B=(0<<ICNC1) | while (1)
(0<<ICES1) | {
(1<<WGM13) | }
(1<<WGM12) | (0<<CS12)
| (0<<CS11) | (1<<CS10); }
Output in Virtual Oscilloscope
1 div =0.5 s
So,
TON=0.5 s
and
Tp=2.8 s
1
div 5.6
div
ARDUINO CODE TIMER
#include <TimerOne.h>
void setup() {
Serial.begin(9600); // Khởi tạo cổng Serial để in kết quả
Timer1.initialize(1000000); // Thiết lập timer0 với chu kỳ 1 giây
Timer1.attachInterrupt(timer_callback); // Bật ngắt khi timer0 đếm đến overflow
}
void loop() {
// Không có gì để làm trong hàm loop()
}
void timer_callback() {
count++; // Tăng biến đếm khi có ngắt xảy ra
Serial.println("Timer interrupt #" + String(count));
1 // In kết quả
}
div 5.6
div
ARDUINO CODE TIMER
// Khai báo chân kết nối encoder void loop() {
#define ENC_A 2 // Tính toán thời gian từ lần đọc trước đó đến hiện tại
#define ENC_B 3 unsigned long deltaTime = millis() - lastTime;
// Biến lưu trữ số lượng xung // Nếu thời gian đọc encoder đã đủ 1 giây
volatile int count = 0; if (deltaTime >= 1000) {
// Tính toán tốc độ dựa trên số lượng xung đọc được và thời
// Biến lưu trữ thời gian đọc encoder trước đó gian đã trôi qua
unsigned long lastTime = 0; speed = (float)count / deltaTime * 1000;
// Biến lưu trữ tốc độ hiện tại // Reset số lượng xung và thời gian đọc encoder trước đó
volatile float speed = 0; count = 0;
lastTime = millis();
void setup() {
// Khai báo chân kết nối encoder là INPUT_PULLUP // In ra tốc độ hiện tại trên Serial Monitor
pinMode(ENC_A, INPUT_PULLUP); Serial.print("Speed: ");
pinMode(ENC_B, INPUT_PULLUP); Serial.print(speed);
1 Serial.println(" RPM");
// Bật interrupt cho chân A của encoder div 5.6}
attachInterrupt(digitalPinToInterrupt(ENC_A), }
readEncoder, CHANGE); div
}
void readEncoder() {
// Đọc trạng thái của chân A và chân B của encoder
int a = digitalRead(ENC_A);
int b = digitalRead(ENC_B);
analogWrite(pin, number);
Serial Communication
Bit serial communication concepts
• Serial one bit at a time
• Most often using logic level signals
• Timing information needs to be shared Introduction to Mechatronics, Figure 7.2 p. 107.
http://www.quatech.com/support/figures/async1.gif
Margolis, M. (2012). Arduino Cookbook, O’Reilly Media, Inc., Sebastopol, CA, p. 422.
You may need to shift the voltage level from 5 V
(Arduino) to 3.3 V for some sensors
Margolis, M. (2012). Arduino Cookbook, O’Reilly Media, Inc., Sebastopol, CA, p. 423.
I2C protocol
• Master initiates transfer with a START bit (SDA from high to low while SCL is high
• Slave address (7 or 10 bits, 7 is most common)
• Transfer type (1 bit: 0 to write, 1 to read)
• All ICs compare address to their address
• If address matches, device sends an ACKNOWLEDGE signal
• If address does not match, device waits until bus is released by
STOP condition
• Once master receives ACKNOWLEDGE,
it then sends (writes) or receives (reads) data
• Receiver sends back ACKNOWLEDGE for each byte
received
• Master concludes the transfer with STOP bit
General structure of a 2-byte transfer
http://www.robot-
electronics.co.uk/acatalog/I2C_
Tutorial.html
Writing 2-bytes (shaded bits are put on the bus by the master)
Reading 2-bytes (shaded bits are put on the bus by the master)
http://www.byteparadigm.com/kb/article/AA-00255/22/Introduction-to-SPI-and-IC-protocols.html
http://garagelab.com/profiles/blogs/tutorial-arduino-i-o-port-expander-with-pcf8574
The Arduino can be ‘expanded’ using an I2C port
expander device (pcf8574)
http://garagelab.com/profiles/blogs/tutorial-arduino-i-o-port-expander-with-pcf8574
I2C device – SRF10 Ultrasonic Range Finder
• Devantech SRF10
• 3 cm – 6 m range
• 20 Hz max rep rate
• Range results in in., cm., or ms
(time of flight)
• Always a slave (default address is
0xE0)
• Four registers: http://www.robot-electronics.co.uk/htm/srf10tech.htm
Three commands:
Mode 2 Mode 3
▶ Serial.read()
▶ Reads incoming serial data
▶ Return Data
Part 4
SENSORS AND ACTUATORS
Basic Electronic
Component
▶ LED
▶ LDR
▶ Button
▶ Potentiometer
▶ Buzzer
LED