Download as pdf or txt
Download as pdf or txt
You are on page 1of 327

Microcontroller Course

Lecturer: Hoang Thang


Email: waveletthang@gmai.com
Phone: 0702509826
Đánh giá Trọng số
Chuyên cần 10%
Hỏi -đáp 10%
Giữa kì 20%
Kiểm tra cuối kì 60%

7h 8h 9h 10h 11h 12h 12h30 1h30 2h30 3h30 4h30 5h30

1 2 3 4 5 6 7 8 9 10
Chapter 1
INTRODUCTION TO EMBEDDED SYSTEM
System Example

What System mean


▶ is an arrangement in which all its unit
assemble work together according to
a set of rules.
▶ defined as a way of working,
organizing or doing one or many
tasks according to a fixed plan.
▶ in a system, all its
subcomponents depend on
each other.
Embedded System
Definition Example

▶ Embedded means something that is


attached to another thing.
▶ a computer hardware system
having software embedded in it
▶ An embedded system can be an
independent system or it can be a part of
a large system.
▶ An embedded system is a microcontroller
or microprocessor based system which is
designed to perform a specific task.
Embedded system Component

Hardware Software RTOS


Embedded System Characteristics
▶ Single Function
▶ Tightly constrained
Size, Speed, Power ,Cost
▶ Reactive and Real time
▶ Microprocessors based
▶ Memory
▶ Connected
Connected peripherals to connect input and output devices.
▶ HW-SW systems
Software is used for more features and flexibility. Hardware is used for
performance and security.
Basic Structure of Embedded System
Basic Structure of Embedded system
▶ Sensor − It measures the physical quantity and converts it to an electrical signal which can be
read by an observer or by any electronic instrument like an A2D converter. A sensor stores the
measured quantity to the memory.
▶ A-D Converter − An analog-to-digital converter converts the analog signal sent by the sensor into
a digital signal.
▶ Processor & ASICs − Processors process the data to measure the output and store it
to the memory.
▶ D-A Converter − A digital-to-analog converter converts the digital data fed by the processor
to analog data
▶ Actuator − An actuator compares the output given by the D-A Converter to the actual (expected)
output stored in it and stores the approved output.
Microprocessor VS Microcontroller
Microcontroller Microprocessor
▶ Single task oriented. ▶ multitasking in nature. Can perform
▶ RAM, ROM, I/O Ports, and Timers cannot be multiple tasks at a time.
added externally. These components are to be ▶ RAM, ROM, I/O Ports, and Timers can be
embedded together on a chip and are fixed in added externally and can vary in numbers.
numbers.
Microprocessor VS Microcontroller
microprocessors microcontroller
Architecture CISC and Von-Neumann RICS and Harvard
RAM, ROM; secondary storage memory All these peripherals are
I/O peripherals, timers: counters are combined in single integrated
placed on board circuit(IC)
CPU speed High speed Low speed
Design time High design time Low design time
Protection Low security high security

Cost Depend on system Depend on system

Application In computation systems; defense system; Watches, cell phone; Mp3


network communication
INTEGRATED CIRCUIT TECHNOLOGIES

11
Chip Density
Number of
Chip density transistor
SSI 10
MSI (1960s) 100
LSI(1970s) 1000
VLSI(1980s) 10000
ULSI(now) 1000000

IC Manufacturing

Source :DOI: 10.1038/s41467-020-15096-0 12


Chapter 2
AVR ARCHITECTURE AND ASSEMBLY
LANGUAGE PROGRAMMING
2.1 Overview Atmel Atmega32 highlights
An 8-bit microcontroller featuring:

• 3 separate on-chip memories (Harvard architecture)


• 2KB SRAM (for data – volatile; data lost on power off)
• 1KB EEPROM (for persistent data storage – holds data after power off)
• 32KB Flash (organized as 16K of 16-bit words for persistent program code)

• Native data size is 1 byte (SRAM and EEPROM)

• 16-bit data addressing


• Up to 64 KB (216 bytes) of data memory can be accessed

• 8-pin I/O ports named A, B, C, and D, program-configurable as:


• Digital input (for reading discrete external signals on each pin (0v or 5v) as data values 0 or 1)
• Digital output (for writing binary data values as discrete output signals (0v or 5v)
• Analog input (for reading continuous external signals (0v-5v) as data values)
• Serial/Parallel (for reading or writing streams of bytes)
• Pulse accumulator (for counting #changes of external signals)
14
The Atmega32 design is based on a Harvard
Architecture:
• Assigns data and program instructions
to different memory spaces.
• Program data occupies a different
and separate memory from the
program itself.
• Each memory space has a separate
bus, allowing:
1.Different timing, size, and structure
for program instructions and data
2.Concurrent access to data and
instructions (increases speed)
3.Clear partitioning of data and
instructions (better security)
• Drawback: Harder to program

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

Two Wire Interface

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

ATMega32 Programmer Model: Memory


Type Flash RAM EEPROM
F_END Size, RAM- Size, E_END Size,
kB END kB kB
Atmega8 $0FFF 8 $045F 1 $1FF 0.5
Atmega32 $3FFF 32 $085F 2 $3FF 1
Atmega64 $7FFF 64 $10FF 4 $7FF 2
Atmega128 $FFFF 128 $10FF 4 $FFF 4
Two kinds of memory
space: code memory
Programs are stored in 32KB
space and data Program Flash
memory space • Persistent: contents are retained when power is off
(non-volatile)
1) data memory space •Organized as 2-byte words; individual program
instructions generally take 2 bytes, but some take 4
bytes
Including three parts: • Each word has a unique 16-bit address (0-0x3FFF)
• Fast to read; slow to write
GPSs (general • Can only write entire “blocks” of memory at a time

purpose registers); I/O


memory; internal data
SRAM 2KB SRAM for temporary data storage
• Contents are lost when power is shut off (volatile)
• Fast read and write
• Native data size is 8 bits (1 byte)
• Each byte has a unique 16-bit address (0x60-
0x85F)

1KB EEPROM for persistent data storage


• Contents are retained when power is off (non-
volatile)
• Fast read; slow write
• Native data size is 8 bits (1 byte)
• Each byte has a unique 16-bit address
2) code memory space
Flash Program Memory layout
 There are 32KB of program memory
Reset and interrupt vector section
42 words (84 bytes)
(Flash memory)
$002A  Organized as 16K 2-byte words
 Because program instructions are
either 2 (common) or 4 (less
Your programs go here!
common) bytes long

 Each word (not byte) in Flash memory


has a unique address
 Beginning address $0000
 Ending address $3FFF

$3C00  Some Flash memory is reserved or


protected
Number of bytes depends on
user-definable configuration
 First 42 words (reserved)
 Last NNN words (protected)
21
2.2 General Purpose Registers
• There are 32 8-bit GP registers R0-
R31
• Used as accumulators – for most math
and logic
• X, Y, Z are 16-bit registers that
overlap R26-R31
• Used as address pointers
• Or to contain larger values (>255)

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

Program counter (PC, 16-bit)


 Holds address of next program
instruction to be loaded and
executed
 Automatically incremented when the
ALU executes an instruction

Status Register (SREG, 8-bit)


 Contains information of result of
most recent ALU operation

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

An Assembler converts human-readable assembly


language instructions into machine-executable
instruction that are stored in Program Flash Memory
Consider the assembly language instruction
add rD, rS
• add is a reserved assembly language instruction mnemonic

• rS and rD are operands that refer to source and destination


general-purpose registers

• This instruction adds the contents of register rS to register rD,


storing the sum in rD.
• Example: Substitute any actual register (R0-R31) for rS and rD
:
add r20, r5
• case is not important; the instruction can also be written as
ADD R20, R5
27
Let’s consider the case of how the ADD instruction is
represented as a machine-executable instruction
Example: ADD R20, R5
• A 16-bit machine instruction is generated (by the assembler) for this
particular case
• Machine instructions consist of an numeric opcode and operands
• The opcode in this case is 000011 (3)
• Each register operand is represented by 5 bits
• 5 bits are required to represent all possible register values
from 0-31
• ddddd represent the 5 bits that represent the destination
register value (20)
• rrrrr represent the 5 bits that represent the source register
value (5)
0000 11rd dddd rrrr
add r20, r5 is assembled to: Note: The bits ddddd
and rrrrr are “split” in
0000 1101 0100 0101 this instruction

This 16-bit binary word can be expressed in hexadecimal as 0x450d (with


the “high” byte being rightmost) 28
The ALU can only directly operate on data that has
been fetched into the Registers.
It cannot directly operate on SRAM or EEPROM data.
In the assembly language instruction
add r20, r5
• We (the programmer) must first load some values into these
registers. Once way of doing this is with the following
instructions:
ldi r20, 2 ; load value 2 into r20
lds r5, 0x60 ; load value at SRAM addr 0x60 into r5
add r20, r5 ; add them; result is in r20

Following the add, we normally store the sum (the value in


r20) someplace (like in SRAM). More on how to do that
later…how would you guess it might work?

29
Yet another Development System: AVRStudio

• Editor (for writing programs in assembly language)


• Assembler (like a compiler, but much simpler)
• Program downloader (loads the assembled code to
the Atmega32)
• Debugger
• Monitor – (remote debugging on the actual Atmega32)
• Simulator – (local dubugging using a simulation of the
running Atmega32)

30
31
Chapter 3
C PROGRAMMING in Arduino (AVR
microcontroller)
Arduino
Environment

Arduino board Software IDE Shields


• 8-bit microcontroller • Compiler • Unique functionalities
• USB programming • Debugger • Easy to attach
interface • Simulator • Good libraries provided
• I/O pins
Arduino Board
Microcontroller

ATmega328 • Write your code into


ATmega16U2 • To communication with USB

 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

▶ Pins are wires connected to the micro ▶ Output pins


controller • Voltages is determined by sketch
▶ Pins are the interface of micro • Other components can be controlled
controller through outputs
▶ Pins voltages are controlled by a ▶ Input pins
sketch • Input pins are controlled by other
▶ Pins voltages can be read by a sketch component
• Arduino read the voltage on the pin
allow it to respond to events
Analog Vs Digital

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

▶ to connect external voltage source


▶ GND the Ground of Arduino
▶ 5V Arduino supply you by 5V
▶ 3.3V Arduino supply you by 3.3V
 USB connector “to connect Arduino with
laptop”
 Power jack “to connect external power
source with Arduino
 Rest button “to restart the program”
Software

Firmware Application code


▶ Low level code support the main ▶ We write this code
function
▶ USB interface, power modes , reset
▶ Come with Arduino
Arduino IDE
Setup the Arduino IDE

▶ Download the IDE https://www.arduino.cc/en/Main/Donate


Setup the Arduino IDE

 Install Arduino app on your PC


 Connect the Board to your PC using USB cable
 Install USB and other drivers
 Launch the Arduino app
 Select your Arduino board “Tools >>board>> Arduino UNO
 Select serial port “Tools >>port>>COM’X’”
 Write your code
Sensors

▶ 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

• Allow the microcontroller receive info. From the environments

• Perform operation based on the state of environment

• Microcontroller sense voltage only

• Sensors logic must convert an environmental effect into voltage


Actuators

▶ Devices that cause something to happen


in the physical word

▶ Visual → LEDs , LCDs

▶ Audio → Buzzer , Speaker

▶ Motion → Motors , valves


Actuators

Digital Actuators Analog Actuators


• They only control the power • Many actuators need an analog voltage for
complete control
• Even complicated actuators can be
controlled via power • Arduino can’t generate analog outputs
• DAC will convert digital numbers to analog
voltage
• Most microcontrollers don’t have DAC
• Can by one attached
3.1 STRUCTURE OF PROGRAMING
Setup () Function
• Use for primary order
• Start by powering Arduino
void setup ()
{
arguments
}
Loop() function
• Work as long as Arduino work
• Start after setup function end
• The main code written in it
void loop()
{
Arguments
}
Basics symbol

Symbol Operation

; “semi Colom” Every line of code must ended by it

{} Group line of code


Curly bracket Every function must be start and ended by it

/*…….*/ To write comments between it


Variables
Variables Name Conditions Data Types Size
 A sequence of visible character
 Must start with a non-numerical
character
 No C language keywords
Variable Scope
Local Variable Formal Parameter Global Variables
Variables that are declared can be declared. In the definition of Global variables are defined outside
inside a function or block are function parameters of all the functions, usually at the top
of the program.
local variables. They can be
used only by the statements that
are inside that function or block
of code.
C – operator
▶ Arithmetic Operators
▶ Comparison Operators
▶ Boolean Operators
▶ Bitwise Operators
▶ Compound Operators
Arithmetic Operators
Comparison Operators
Boolean Operators
Bitwise
Operators
Compound Operators
Control Statements
▶ If statements
▶ If-else Statements
▶ If-else if – else statement
▶ Switch statement
If statement int sensorPin = A0; // chọn chân analog A0 cho cảm biến
int ledPin = 13; // chọn chân digital 13 cho đèn LED
if( expression ) void setup() {
{ pinMode(ledPin, OUTPUT); // khai báo chân 13 là đầu ra
}
Statement 1
void loop() {
} int sensorValue = analogRead(sensorPin); // đọc giá trị từ cảm biến
if (sensorValue > 500) {
else digitalWrite(ledPin, HIGH); // bật đèn LED nếu giá trị từ cảm biến lớn hơn 500
} else {
{
digitalWrite(ledPin, LOW); // tắt đèn LED nếu giá trị từ cảm biến nhỏ hơn hoặc bằng 500
statement 2 }
delay(100); // đợi 0.1 giây trước khi đọc giá trị từ cảm biến lần tiếp
} }
If –else if - else
if( expression1 )
{
Statement 1
}
If else (expression2 )
{
statement 2
}
else
{ statement3 }
Switch statement
switch (expression )
• Compere each case with
{ ,
case ‘const_expr1’ : stat1 expression and operate the case

break ; equal to expression


case ‘const_expr2’ : stat2
break ; • Default → operating when no

default : stat3 case is matching

}
• 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);

// Kiểm tra giá trị từ cảm biến


switch (expression ) switch (sensorValue) {
case 0:
{ Serial.println("Giá trị từ cảm biến là 0");
case ‘const_expr1’ : stat1 break;
case 100:
break ; Serial.println("Giá trị từ cảm biến là 100");
case ‘const_expr2’ : stat2 break;
case 500:
break ; Serial.println("Giá trị từ cảm biến là 500");
break;
default : stat3 default:
} Serial.println("Giá trị từ cảm biến không thuộc các giá trị được chỉ định");
break;
}

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>

Servo myservo; // Khai báo đối tượng servo


int pos = 0; // Khai báo biến để lưu vị trí của servo

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);
}

// Người dùng đã nhấn nút, thực hiện hành động A


digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);

}
Do-while
Loop
Nested
Loop

▶ use one loop inside another loop.


Infinite Loop
Functions
The relationship between assembly language and the C language in loops

• 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

• In order to prevent this unknown state,


pull up resistor is used.
• Pull ups are often used with button and
switches.
A switch connected at the
input pin with pull up resistor
Internal pull up resistor in AVR and its
control
• In AVR ATmega32
microcontroller, each of the
port pins have a pull up
resistor having the facility of
connecting or disconnecting
it with the pin.
• The provision of connection
or disconnection is
controlled by PORTx register.
[see the figure]
• If we put 1s into bits of Remember that during output of data
PORTx register, the pull up PORTx is the register in which data has
to be written to make it out.
resistors are activated.
Input and Output pins in a Single Port
Defining a pin as either Input or Output – The DDRx Registers

LDI R20,0xFF ;R20 = 0b01110101


OUT PORTx,R20 ;PORTA = R20
OUT DDRx,R20 ;DDRA = R20

DDRx = 0b01110101; /* Configuring I/O


pins
Summary Action During Output
• Step1: If we want to send (out) data through
a pin of a port, the corresponding bit of
DDRx Register has to be set to ‘1’.
• Step 2: Then if we want to send ‘1’ write ‘1’
to the corresponding bit of PORTx Register
and ‘0’ if we want to send ‘0’.
• Note: We can not send data (either ‘1’ or
‘0’) if we do not complete step 1. At START
UP or UPON RESET DDRx register contains
0x00, that is all pins remain at input state.
Summary Action During Input
• Step1: If we want to read (in) data through a pin of a
port, the corresponding bit of DDRx Register has to be
set to ‘0’.
• Step 2: Whatever data is in that pin of the port the data
will appear in the corresponding bit of PINx register, so
we have read that bit of PINx.
• Step 3: Each pin has a provision of connecting a pull up
resistor internally. If we want to connect that resistor,
we have to write ‘1’ to the corresponding bit of PORTx
register.
• Note: At START UP or UPON RESET, DDRx register
contains 0x00. That is the port remains at Input state.
But if it is used as OUTPUT at one stage of program,
afterwards, we can not read data from a pin if we do
not complete step 1.
A Practical example of Outputting Data
through a Port
• Let us assume that 8 LEDs are connected to 8-pins of PORTC
of an Atmega32 chip
• We want to glow all of the eight LEDs.
• And they will be switched off after1 sec and it will be
repeated continuously.
• Write a C code for the above mentioned output operations.
What is an LED?
• Light Emitting Diode (LED) is a
special diode that emits light
when electric voltage is applied
to it. It is a common electronic
equipment used in many devices
for indication purpose.
• There are two leads of an LED
that are used to supply input
voltage. The longer lead is
positive and known as ‘Post’, and
the smaller is negative known as
‘Anvil’
Connection of LEDs with a Port
ATmega32

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

• Returns the state of an input pin


• Returns either LOW or HIGH
digitalRead(pin)
Digital input function
analogRead()
• Returns the state of an input pin
• Returns either value
int voltage =analogRead(A0)
Pin
• analog” “A0:A5 for analog pins
Digital input function
analogWrite(pin, value)
• Assign the state of an output pin
• Assign either value
analogRead(pin, value)
Pin
• Is the number of the pin “0:13 for
digital
Chapter 5
INTERRUPTS STRUCTURE
What is Interrupt
It is an internal or external events that inform the CPU something needs to be serviced

Real life Example of External Interrupts


• Warning of not wearing seat belt in a car.
• Pressing a key on a keypad.
• Power failure detection in a microcontroller-based system.
• Counting the number of products in a production line.
Interrupts and Polling
• Interrupts: Signals sent by external devices to processor to get attention,
interrupting its current task for handling incoming signal, ensuring efficient
communication without continuous polling.
• Polling: Processor regularly checks status of each device to determine
action required, less efficient than interrupts, but useful in situations where
interrupts are not feasible or devices have low priority.
• Interrupts and polling are important techniques for managing
communication between computers and external devices.
• Interrupts allow for efficient communication, while polling can be useful in
certain situations.
• Both techniques have their own advantages and limitations.
• Interrupts and polling are complementary methods used by computers to
manage communication with external devices.
Interrupt Service Route (ISR)
•ISR executes when interrupt signal is sent.
•Used for handling tasks from peripherals.
•Important for embedded devices and real-time apps.
•System automatically calls corresponding ISR when interrupt is triggered.
•After completing its task, system returns to previous state and continues executing
tasks.
Interrupt Vector Table for ATmega32 AVR
Steps in executing an Interrupt
1.It finishes the instruction it is currently executing and saves the address of the next instruction (program
counter) on the stack
1.Execution completion and program counter storing on stack after current instruction
2.It jumps to a fixed location in memory called the interrupt vector table. The interrupt vector table directs
the microcontroller to the address of the interrupt service routine (ISR).
2.Using interrupt vector table's fixed memory location to guide microcontroller to ISR
address.
3.The microcontroller starts to execute the interrupt service subroutine until it reaches the last instruction of
the subroutine, which is RETI (return from interrupt).
3.Execution of ISR subroutine by microcontroller until reaching the final instruction,
which is RETI for returning from interrupt
4.Upon executing the RETI instruction, the microcontroller returns to the place where it was interrupted.
First, it gets the program counter (PC) address from the stack by popping the top bytes of the stack into the
PC. Then it starts to execute from that address.
4. After executing the RETI instruction, microcontroller retrieves the interrupted Program
Counter (PC) address by popping top bytes of the stack and begins execution from that
address.
Internal and External Interrupt Sources
• The AVR 8-bits microcontroller provide both internal
and external interrupt sources. The internal interrupts
are associated with the microcontroller's peripherals.
• They are the Timer/Counter, Analog Comparator,
etc.
• The external interrupts are triggered via external pins.
• On AVR ATmega32 microcontroller there are four (4)
external interrupts:
• RESET Interrupt - Triggered from pin 9.
• External Interrupt 0 (INT0) - Triggered from pin 16.
• External Interrupt 1 (INT1) - Triggered from pin 17.
• External Interrupt 2 (INT2) - Triggered from pin 3.
External Interrupt Pins
External Interrupts
• The number of external hardware interrupts varies in
different AVRs.
• The ATmega32 has three external interrupts: pin PD2
(PORTD.2), PD3 (PORTD.3) and PB2 (PORTB.2), designated as
INT0, INT1 and INT2 respectively.
• Upon activation of these pins, the AVR is interrupted in
whatever it is doing and jumps to the vector table to perform
the interrupt service routine.
External Interrupts INT0, INT1 and INT2
• The interrupt vector table locations $2, $4 and $6 are set
aside for INT0, INT1 and INT2, respectively.
• The hardware interrupts must be enabled before they
can take effect.
• This is done using INTx bit located in GICR (General
Interrupt Control Register).
GICR Register
INT1 INT0 INT2 - - - IVSEL IVCE
Interrupt Sense Control bits for INT0
MCUCR (MCU Control Register)

SE SM1 SM2 SM0 ISC11 ISC10 ISC01 ISC00

ISC01 and ISC00 - These bits define the level or


edge on the external INT0 pin that activates the
interrupts, as shown in the following table
ISC0 ISC00 Description
1
0 0 The low level of INT0 generates an interrupt request
0 1 Change on INT0 generates an interrupt request
1 0 Falling edge of INT0 generates an interrupt request
1 1 Rising edge of INT0 generates an interrupt request
Interrupt Sense Control bits for INT1
MCUCR Register
SE SM1 SM2 SM0 ISC11 ISC10 ISC01 ISC00

ISC11 and ISC10 - These bits define the level or edge


on the external INT1 pin that activates the interrupts,
as shown in the following table
ISC11 ISC10 Description
0 0 The low level of INT1 generates an interrupt request
0 1 Change on INT1 generates an interrupt request
1 0 Falling edge of INT1 generates an interrupt request
1 1 Rising edge of INT1 generates an interrupt request
Interrupt Sense Control bit for INT2
• Interrupt 2 (INT2) can only be configures as edge triggered
mode.
• In other words it can not be configured as level triggered.
• ISC2 bit of MCUCSR (MCU Control and Status Register)
defines whether INT2 interrupt will activate on falling or rising
edge.
MCUCSR Register
JTD ISC2 - JTRF WDRF BORF EXTRF PORF
IS2 Description
0 Falling edge of INT2 generates an interrupt
request
1 Rising edge of INT2 generates an interrupt
request
Sampling the edge-triggered and level-
triggered interrupts
• The edge-interrupt (the falling edge, the rising
edge or the change level) is latched by the
AVR.
• It is latched by the INTFx bits of GIFR (General
Interrupt Flag Register).
• This means that when an external interrupt is
in an edge-triggered mode (falling edge, rising
edge or level change), upon triggering an
interrupt request, the related INTFx flag
becomes set.
Sampling………
• If the interrupt is active (the INTx bit is set and the
I-bit is SREG is one), the AVR will jump to
corresponding vector location.

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

#include <mega32.h> interrupt [EXT_INT0] void


#include <alcd.h> ext_int0_isr(void)
#include <delay.h> {
lcd_clear();
#include <stdlib.h>
strcpy(d1,"i = ");
#include <string.h> itoa(i,display);
strcat(d1,display);
int i=0; lcd_gotoxy(0,0);
char d1[16]; lcd_puts(d1);
char display[16]; }
Code (Part-II)
GICR Register
// Alphanumeric LCD initialization
INT1 INT0 INT2 - - - IVSEL IVCE // Connections
MCUCR // RS - PORTD Bit 4
SE SM1 SM2 SM0 ISC11 ISC10 ISC01 ISC00 // RD - PORTD Bit 5
void main(void) // EN - PORTD Bit 6
{ // D4 - PORTC Bit 4
// External Interrupt(s) // D5 - PORTC Bit 5
initialization // D6 - PORTC Bit 6
// INT0: On // D7 - PORTC Bit 7
// INT0 Mode: Falling Edge lcd_init(16);
// INT1: Off #asm("sei")
// INT2: Off while (1)
GICR|=(0<<INT1) | (1<<INT0) | {
(0<<INT2);
for(i=0;i<10000;i++);
MCUCR=(0<<ISC11) | (0<<ISC10)
| (1<<ISC01) | (0<<ISC00); }
MCUCSR=(0<<ISC2); }
Experiment with Arduino
attachInterrupt()
Syntax: attachInterrupt(interrupt, ISR, mode);

• 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

const int interruptPin = 2; // số chân được sử dụng cho ngắt


volatile int state = LOW; // trạng thái biến được cập nhật bởi ISR

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

6.1 ANALOG TO DIGITAL CONVERTERS


• Analog-to-Digital Converter (ADC or A2D) – a circuit that takes in
an analog voltage and produces a digital representation of its value.

15.1 ANALOG TO DIGITAL CONVERTERS


time

15.1 ANALOG TO DIGITAL CONVERTERS


time
• Sample – the action of duplicating the voltage value of the input
signal.

• 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.

15.1 ANALOG TO DIGITAL CONVERTERS


VR+

1
0
VR- time
n=1
Sample=0
• n represents the number of bits in the digital value of the conversion.

15.1 ANALOG TO DIGITAL CONVERTERS


VR+

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.

15.1 ANALOG TO DIGITAL CONVERTERS


VR+

1
0
VR- time
n=1
Sample=0
• The larger the n, the closer the digital value is to the actual analog
voltage.

15.1 ANALOG TO DIGITAL CONVERTERS


VR+
11
10
01
00
VR- time
n=2
Sample=01
• The larger the n, the closer the digital value is to the actual analog
voltage.

15.1 ANALOG TO DIGITAL CONVERTERS


VR+
111
110
101
100
011
010
001
000
VR- time
n=3
Sample=010
• The larger the n, the closer the digital value is to the actual analog
voltage.

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 larger the n, the closer the digital value is to the actual analog
voltage.

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
Sample=0100
• The number of bits n is called the ADC’s 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 number of bits n is called the ADC’s resolution.
• MCU’s typically have ADC’s with resolutions of 8 to 16 bits.

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 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.

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.
• 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

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
Sample=0100
• The original analog value is found by multiplying the digital
conversion result (NADC) with the resolution.

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

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
Sample=0100
• The accuracy is how close the digital output is to the input signal.

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 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

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

• The voltage can be sampled over time to create a list of digital


values.

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

• The voltage can be sampled over time to create a list of digital


values.

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 0100
1000
0111

• The voltage can be sampled over time to create a list of digital


values.

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
0101

• The voltage can be sampled over time to create a list of digital


values.

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
0101

• The voltage can be sampled over time to create a list of digital


values.

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 0100
1000
0111 1001
0101 1101

• The voltage can be sampled over time to create a list of digital


values.

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 0100
1000
0111 1001 1110
0101 1101

• The voltage can be sampled over time to create a list of digital


values.

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

• The voltage can be sampled over time to create a list of digital


values.

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 0100
1000
0111 1001 1110
0101 1101 1101

TSA
• The sample period (TSA) is the time between samples.

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

TSA
• The sampling rate is the frequency of sampling: fSA= 1/TSA

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

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.

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 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

• Thermo couple provides temp in form of uV


• PT100 provides temp in form of resistance
• Some humidity sensor provide the result in form of
Capacitance

• -> We have to change these signals to Voltage to convert it


by ADC
• This job is called signal conditioning
Sensor Interfacing
Arduino analogRead()
int inputAnalogPin = A0; // Analog input pin for potentiometer
int digitalOutput = 0;// variable which store input value from
potentiometer

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.

• TCCRO (Timer/Counter Control Register) register is an 8-bit


register used for control of Timer0.
• CS02:CS00 (Timer0 clock source)
• These bits in the TCCRO register are used to choose the
clock source. If CS02:CS00 = 000, then the counter is
stopped. If CS02:CS00 have values between 001 and 101,
the oscillator is used as clock source and the timer/counter
acts as a timer. In this case, the timers are often used for
time delay generation. If CS02:CS00 are 110 or 111, the
external clock source is used and it acts as a counter
Bit D7 D6 D5 D4 D3 D2 D1 D0
FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00
Read/Write W RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0
FOC0 D7 Force compare match: this is a write-only bit, which can be used while generating a wave. Writing 1 to
it causes the wave generator to act as if a compare match had occurred.
WGM00, WGM01 D6 D3 Timer0 mode selector bits
0 0 Normal

0 1 CTC (Clear Timer on Compare Match)

1 0 PWM, Phase Correct

1 1 Fast PWM

COM01 COM00 D5 D4 Compare Output Mode:


These bits control the waveform generator (See chapter 15)

CS02 CS01 CS00 D2 D1 D0 Timer0 Clock Selector


0 0 0 No clock source (Timer/Counter stopped)
0 0 1 CLK (No Pre-scaling)
0 1 0 CLK / 8
0 1 1 CLK / 64
1 0 0 CLK / 256
1 0 1 CLK / 1024
1 1 0 External clock source on T0 pin. Clock on falling edge
1 1 1 External clock source on T0 pin. Clock on rising edge
WGM01:WGM00
• Timer0 can work in four different modes: Normal,
phase correct PWM, CTC, and Fast PWM. The
WGM01 and WGMOO bits are used to choose one of
them. We will discuss the PWM options in Chapter
16.
Timer0 Programming
TIFR (Timer/counter Interrupt Flag Register)
• The TIFR contains the flags of different timers.
Bit D7 D6 D5 D4 D3 D2 D1 D0
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0
Read/Write RW RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0

TOV0 D0 Timer0 Overflow Flag bit

0= Timer0 did not overflow

1= Timer 0 has overflowed (going from 0xFF to 0x00)

OCF0 D1 Timer0 Output Compare flag bit


0= Compare match did not occur
1= Compare match occurred
TOV1 D2 Timer1 Overflow Flag bit
OCF1B D3 Timer1 Output Compare B match flag
OCF1A D4 Timer1 Output Compare A match flag
ICF1 D5 Input Capture Flag
TOV2 D6 Timer2 Overflow Flag
OCF2 D7 Timer2 Output Compare match flag
Timer0 Programming
TOV0 (Timer0 Overflow)
• The flag is set when the timer rolls over from FF to 00. The
TOV0 flag is set to 1 and it remains set until the software
clears it.
• The strange thing about this flag is that in order to clear it
we need to write 1 to it.
• Indeed this rule applies to all flags of the AVR chip. In AVR,
when we want to clear a given flag of a register we write 1 to
it and 0 to the other bits.
Normal mode
• In this mode, the content of the timer/counter increments
with each clock. It counts up until it reaches its max of FF.
When it rolls over from FF to 00, it sets high a flag bit called
TOV0 (Timer Overflow).
Steps to program Timer0 in Normal mode
1. Load the TCNT0 register with the initial count
value.
2. Load the value into the TCCR0 register,
indicating which mode (8-bit or 16-bit) is to be
used and the prescaler option. When you select
the clock source, the timer/counter starts to
count, and each tick causes the content of the
timer/counter to increment by 1.
3. Keep monitoring the timer overflow flag (TOVO)
to see if it is raised. Get out of the loop when
TOVO becomes high.
4. Stop the timer by disconnecting the clock
source, using the following instructions:
5. Clear the TOVO flag for the next round.
6. Go back to Step 1 to load TCNT0 again.
LET’S CODE IT!
toggle bits of PORTB continuously with
some delay
Timer0 Programming
// toggle bits of PORTB continuously with some delay.
#include <avr/io.h>
void T0Delay ();
int main (){
DDRB = 0xFF; // PORTB output port
PORTB = 0x55;
while(1){ //repeat forever
PORTB = ~PORTB;
T0Delay(); //delay size unknown
}
}
void T0Delay(){
TCNT0 = 0x20; // load TCNT0 (RUN AGAIN FOR TCCR0=2)
TCCR0 = 0x01; // Run Timer0, Normal mode, no prescaler
while ((TIFR & 0x01)==0); // wait for TF0 to roll over
TCCR0 = 0; // Stop Timer
TIFR = 1; //clear TF0
}
Timer0 Programming
Calculating Delay Length of Previous Program
Assume XTAL = 8 MHz.
Sol: XTAL = 8MHz ► Clock Period = 1/8 MHz
= 0.125 µs
Timer Counts = (1+0xFF- 0x20) = 0xE0 = 224
Delay = 224 × 0.125 µs = 28 µs
Note: There will also be an Overhead Due to
Instructions
Timer0 Programming
Timer0 Programming
Calculating Delay Length Using Timers

Q Write a C program to toggle only the


PORTB.4 bit continuously every 70 µs.
Use TimerO, Normal mode, and 1:8
prescaler to create the delay. Assume
XTAL = 8 MHz.
Solution:
XTAL = 8MHz ► Tmachine Cycle = 1/8 MHz
Prescaler = 1:8 ► TClock = 8×1/8MHz = 1µs
70µs/1µs = 70 clocks
► (1 + 0xFF) – 70
= 256 - 70 = 186 = 0xBA = -70
Timer0 Programming
// toggle bits of PORTB continuously with some delay.
#include <avr/io.h>
void T0Delay ();
int main (){
DDRB = 0xFF; // PORTB output port
while(1){ //repeat forever
PORTB = 0x55;
T0Delay(); //delay size unknown
PORTB = 0xAA;
T0Delay();
}
}
void T0Delay(){
TCNT0 = -70; // load TCNT0
TCCR0 = 0x02; // Run Timer0, Normal mode,1:8 prescaler
while ((TIFR & 0x01)==0); // wait for TF0 to roll over
TCCR0 = 0; // Stop Timer
TIFR = 1; //clear TF0
}
Timer0 Programming
Example
Assuming XTAL = 8 MHz, write a program to generate a delay of 1ms.
Solution:
Prescaler Timer Clock Timer Period Timer Value
none 8 MHz 1/8MHz = 0.125 µs 1ms / 0.125 µs = 8000
64 8 MHz / 64 = 125KHz 1/125KHz = 8 µs 1ms / 8 µs = 125
256 8 MHz / 256 = 31.25KHz 1/31.25KHz = 32 µs 1ms / 32 µs = 31.25
1024 8 MHz / 1024 = 7.8125 KHz 1/7.8125 KHz = 128 µs 1ms / 128 µs = 7.8125
From the above calculation we can only use the options Prescaler = 64, Prescaler = 256 or
Prescaler = 1024.

But we should use the option Prescaler = 64 sinece we can not use a decimal point.

To wait 125 clocks we should load OCR0 with 125-1 = 124


Timer0 Programming
// toggle bits of PORTB continuously with some delay.
#include <avr/io.h>
void T0Delay ();
int main (){
DDRB = 0xFF; // PORTB output port
while(1){ //repeat forever
PORTB = 0x55;
T0Delay(); //delay size unknown
PORTB = 0xAA;
T0Delay();
}
}
void T0Delay(){
TCNT0 = 0; // timer starts from 00
OCR0 = 124; // Output Compare Register has value 124
TCCR0 = 0x0B; // Run Timer0,(CTC)Clear Timer on Compare Match,
// 1:64 Prescaler
while ((TIFR & 0x02)==0); // wait for OCF0 to roll over
TCCR0 = 0; // Stop Timer
TIFR = 0x02; //clear TF0
} // In Theory Delay = (124+1)*8 us = 1ms (for 8MHz Clock)
Example
Assuming XTAL = 8 MHz, write a program to generate a delay of 25.6 ms.
Use Timer0, CTC mode, with prescaler = 1024.
Solution:

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.

Therefore the OCR0 register should be loaded with 200-1 = 199.

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

 OCR2 register - the value with which the comparison is


made bit6
bit7 bit5 bit4bit7 bit3 bit2 bit1 bit0

 TIMSK register – all INTERRUPT ENABLE BITS (all Timers)


OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 OCIE0 TOIE0

 TIFR registers - all INTERRUPT FLAGS (all Timers)


OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0
TIFR (Timer/Counter) Interrupt Flag
Register
TIFR Register
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0

Timer 2 Timer 1 Timer 0


TOV0 Timer0 flag bit; 0- did not overflow, 1-has overflowed (FF->00)
OCF0 Timer0 output compare flag bit; 0-did nor match, 1-matched
TOV1 Timer1 flag bit;
OCF1B Timer 1 output compare B match flag
OCF1A Timer 1 output compare A match flag
ICF1 Input Capture flag
TOV2 Timer2 flag bit
OCF2 Timer2 output compare flag bit
TIMSK Register
OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 OCIE0 TOIE0

TOIE0 Timer0 Overflow Interrupt Enable


OCIE0 Timer0 Output Compare Interrupt Enable
TOIE1 Timer1 Overflow Interrupt Enable;
OCIE1BTimer 1 Output Compare B match Interrupt Enable
OCIE1A Timer 1 Output Compare A match Interrupt Enable
TICIE1 Timer/Counter1, Input Capture Interrupt Enable
TOIE2 Timer2 Overflow interrupt Enable
OCIE2 Timer2 output compare Interrupt Enable
Timer2 Programming
• Timer2 is very similar to Time0, both being 8-bit timers.
• But there are two distinct differences between the two.
• Timer2 can be connected to real time counter. For that, we
should connect a crystal of 32.768 kHz to TOSC1 and TOSC2
terminals and set AS2 bit of ASSR register.
• Timer2 can NOT be used as counter of external events. Rather
all setting of CS22:CS20 (3bits of TCCR2 register) are for
internal frequency select. Of course the meaning of some of
the combinations have different meaning than that of Timer0.
TOSC1 & TOSC2 Pins
Timer2 Programming
TCCR2 Register
FOC2 WGM20 COM21 COM20 WGM21 CS22 CS21 CS20

 FOC2 – Bit 7 – Force Compare Match. This is a


write only bit, writing 1 to it causes to act as if a
compare match has occurred.
 WGM20, WGM21 – Bit 6 and 3 – Mode Selector
0 0 – Normal
0 1 – CTC (Clear Timer on Compare Match)
1 0 – PWM, Phase Correct
1 1 – Fast PWM
Timer2 Programming (Contd.)
TCCR2 Register
FOC2 WGM20 COM21 COM20 WGM21 CS22 CS21 CS20
• COM 21:20 – Bit 5 and 4
Compare output mode This mode controls the
waveform generator (will be discussed in another
lecture)
• CS22:20 – Bit 2, 1 and 0 – Timer clock selector
(see the next slide)
Block Diagram for Timer2
CLkI/O STOP 0
CLK 1 WGM21 WGM20
CLK/8 2
CLK/32 3
CONTROL
PRESCALER CLK/64 4 MUX UNIT
CLK/128 5
CLK/256 6 COUNT UP/ CLEAR
CLK/1024 DOWN OCR2
72 1 0
TCNT2
AS2 CLK
TOV2 COMPARATOR =
CS01CS00
T/C Oscillator CS02
OCF2
CLKI/O
TOSC1 TOSC2
TIFR (Timer/Counter) Interrupt Flag
Register
TIFR Register
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0

Timer 2
TOV2 Timer2 Overflow flag bit
OCF2Timer2 output compare flag bit
ASSR (Asynchronous Status Register)

ASSR Register
AS2 TCN2UB OCR2UB TCR2UB

AS2 – When it is zero, Timer2 is clocked from


CLKI/O,
When it is set Timer2 works as RTC
The Circuit Developed in Proteus
Generation of a Train of Rectangular Pulses of a
Fixed Frequency Using Timer2
• Let us say, we want to generate a train of rectangular pulses having a
frequency of 0.5 Hz.
• Therefore, the time period will be (1/0.5) sec or 2 sec.
• So the time in half cycle will be 1 sec.
• If we send high signal to a port pin for 1 Sec and then low for next 1
Sec and repeat this sequence, a train of pulse of 0.5 Hz will be
generated.
• If we configure TIMER2 to be interrupted at every 1 Sec, and if we
toggle a Port pin we shall obtain desired wave shape.
• Let us use external clock of 32.768 kHz with a Prescaling factor of
1024. Therefore duration of each pulse will be of (1024/32768) Sec.
• In other words, we need 32768/1024 or 32 (or 0x20) number of
pulses for a time of 1 Sec.
• Therefore, in compare method, TCNT2=0x00; OCR2=0x20;
• And in TCCR2 > CS22:CS21:CS20=111;
One Correction in Calculation of Initial Value for TCNTn
Registers for Overflow Method
• In order to count ‘n’ number of pulses, the number to be
loaded in TCNTn Register (in Overflow method)
= 255-n+1
NOT 256-n+1
Because the decimal corresponding to FF is
255
void main(void)
{

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

Mode WGM13 WGM12 WGM11 WGM10 Description of


Mode
0 0 0 0 0 Normal
4 0 1 0 0 CTC for OCR1A
12 1 1 0 0 CTC for ICR1
Others 0/1 0/1 0/1 0/1 All related to
PWM
An Exercise
• Write a program to toggle only the PORTB.5 bit
continuously every second. Use timer 1, Normal
mode, and 1:256 prescaler to create the delay.
Assume XTAL=8 MHz.
Solution:
• XTAL=8 MHz  T machine cycle = 1/8 uSec=0.125 uS
• Prescaler=1:256  Tclock = 256 X 0.125 = 32 uS
• So, number of clock necessary to make a delay of
1sec is (1s/32uS)=31250
• Therefore, the number to be loaded in the timer
register is (65535-31250+1)=34286=0x85EE
• So, TCNT1L=0xEE and TCNT1H=0x85
The Program Using Timer1
#include …. void T1Delay ()
void T1Delay() {
int main() { TCNT1L=0XEE;
DDRB=0xFF;
TCNT1H=0X85;
while (1) {
T1Delay(); TCCR1A=0x00;
PORTB=~PORTB; TCCR1B=0x04;
} while ((TIFR&04)==0);
} TIFR=0x04;
}
Summary on Operation of Timer1
Timer0 and Timer2 also
Can be obtained using

1. No auto output is required


2. Auto output in OC1A or OC1B pin, (Square Wave)
Timer Register Resets : (2a.Normal) or (2b. CTC)
3. Auto output in OC1A or OC1B pin,

Output
(PWM Wave of discrete frequency)
Timer Register Resets : Normal

4. Auto output in OC1A or OC1B pin,


(PWM Wave of Variable frequency)
Timer Register Resets : Normal

5. Input Capture in ICP1 pin, (Time Period)

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

OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 OCIE0 TOIE0


TIFR Register

OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0


ICP1 Pin

Input Capture
Principle of Calculating Time Period of
a Square Wave
First Next rising
rising edge
edge

Say, No. of count,


Time Period n=5
So, total number of
Count=1 Count=3 Count=5 clock pulse,
Count=2 Count=4
N = y+n*65536-x

ICR1 Register ICR1 Register


Value at first rising Value at next
edge (say)=x rising edge
decimal (say)=y decimal
Bits in TCCR1x Registers
TCCR1A Register
COM1A1 COM1A0 COM1B1 COM1B0 FOC1A1 FOC1B WGM11 WGM10
1 B1 B1
TCCR1B Register
ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10
1

ICNC1 – Input Capture Noise Canceller , normally not set


ICES1 – Input Select Edge Select, 0-falling and 1- rising
edge
Steps for the Calculation of the Period of
a Square Wave
• Step#1: Enable both TOV1 and TICIE1 bit of TIMSK register.
• Step#2: In the ISR for Timer overflow increment a count,
indicating number of overflow, n between two successive
input edges.
• Step#3: In the ISR for input capture, store the number in
ICR1 register as a present value, y.
• Step#4: Subtract this present value, y from the previous
value, x stored in the previous input capture and add with
number of ticks in the complete cycle of overflow. The
number, N=y+n*256-x.
• Step#5: Calculate the time for the number of total ticks (N).
This time is the time period.
• Step#6: Replace the previous value with the present value
and reset the value of the count.
The Code (1st Part)
#include <mega32.h>
#include <stdlib.h>
#include <alcd.h>

long int new_value=0;


long int prv_value=0;
char disp[16];
int count=0;
float Tp=0;
float Ttick=1/(2000*1e3);
float Tov=65535*Ttick;
The Code (2nd Part)
// Timer1 overflow interrupt ftoa(Tp,6,disp);
service routine
interrupt [TIM1_OVF] void lcd_clear();
timer1_ovf_isr(void) lcd_gotoxy(0,0);
{ lcd_puts(disp);
count++;
itoa(count,disp);
}
// Timer1 input capture lcd_gotoxy(0,1);
interrupt service routine lcd_puts(disp);
interrupt [TIM1_CAPT] void count=0;
timer1_capt_isr(void)
{ }
new_value=ICR1H*256+ICR1L;
Tp=count*Tov+(new_value-
prv_value)*Tpulse;
prv_value=new_value;
void main(void)
{
The Code
TCCR1A=(0<<COM1A1) | (3rd Part)
(0<<COM1A0) | (0<<COM1B1) |
(0<<COM1B0) | (0<<WGM11) | // Timer(s)/Counter(s) Interrupt(s)
(0<<WGM10); initialization
TCCR1B=(0<<ICNC1) | (1<<ICES1) | TIMSK=(0<<OCIE2) | (0<<TOIE2) |
(0<<WGM13) | (0<<WGM12) | (1<<TICIE1) | (0<<OCIE1A) |
(0<<CS12) | (1<<CS11) | (0<<CS10); (0<<OCIE1B) | (1<<TOIE1) |
(0<<OCIE0) | (0<<TOIE0);
TCNT1H=0x00;
lcd_init(16);
TCNT1L=0x00;
// Global enable interrupts
ICR1H=0x00;
#asm("sei")
ICR1L=0x00;
while (1)
OCR1AH=0x00;
{
OCR1AL=0x00;
}
OCR1BH=0x00;
}
OCR1BL=0x00;
The Input in Virtual Oscilloscope and Output in
LCD Display

5 div, 1 div = 0.2 s, Tp = 1s


How Duty Cycle is Measured Using Input
Capturing ?
• Period is measured by input capturing as we explained earlier.
• The pulse width is measured by using interrupt with sensing at
“triggering at both edge”
• The time measurement technique is done by using the values stored
in Input Capture Register and the value of the count.
• The duty cycle is then obtained from TON/Tperiod.
The Simulation

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

WGM = FAST PWM with ICR1A as RESET Value Pulses


Output
at OC0 TON
pin

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>

int count = 0; // Biến đếm số lần ngắt xảy ra

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);

// Nếu chân A thay đổi


if (a != b) {
// Tăng biến đếm số lượng xung
count++;
} else {
// Giảm biến đếm số lượng xung
count--;
}
}
analogWriteFrequency(pwmPin, 5000);
analogWrite()

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.

between sender and receiver


• Transitions between bits, duration of a bit

 Two major types of bit serial


protocols
 Synchronous (shared clock)
 Ex. SPI, I2C
 Asynchronous (no shared clock)
 Sender and receiver maintain
independent clocks
 Ex. RS-232, USB

http://www.quatech.com/support/figures/async1.gif

16-May-23 BJ Furman SJSU Mechanical and Aerospace Engineering ME 106 284


Synchronous serial communication
• Characteristics of synchronous serial
• At least one connection for serial data
• A clock connection
• Shared ground
• Common types
• Serial Peripheral Interface (SPI, developed by Freescale)
• Inter-Integrated Circuit bus (I2C, developed by Philips (NXT))
• Arduino support
• I2C and SPI
• See next slide

16-May-23 BJ Furman SJSU Mechanical and Aerospace Engineering ME 106 285


I2C • Developed in 1982 by
Philips (now NXP)
• To connect CPU to
peripherals in televisions
• Two signal lines, both are
‘open drain’, thus pull-up
resistors are needed
• SDA (serial data)
• SCL (serial clock)
• Devices are either masters
or slaves
• Master is the device that
always drives SCL and http://www.byteparadigm.com/kb/article/AA-00255/22/Introduction-to-SPI-and-IC-protocols.html
initiates a transfer
• Each device has an address
Use 1.2k - 2.2k pull up resistors for Vcc = 3.3 V
• Data is sent in 8 bit bytes or 1.8 - 3.3k resistors for Vcc = 5 V

16-May-23 BJ Furman SJSU Mechanical and Aerospace Engineering ME 106 286


Analog pins 4 (SCL) and 5 (SDA) must be pulled
up, and a common ground is needed

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

16-May-23 BJ Furman SJSU Mechanical and Aerospace Engineering ME 106 289


Many digital components use I2C
• See the list from:
http://forums.parallax.com/showthread.php?99160-List-of-I2C-devices
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
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:

16-May-23 BJ Furman SJSU Mechanical and Aerospace Engineering ME 106 293


SPI interface and protocol
• At least one ‘master’ and ‘slave’
needed
• Master controls:
• Unidirectional data line, MOSI
• Master Out, Slave In (data from
the master to the slave)
• Shared clock line, SCK
(synchronizes the data transfer)
• Slave select line(s), SS*
• Which slave to be addressed
• Slave controls:
• Unidirectional data line, MISO
Introduction to Mechatronics, Figure 7.4 p. 109.
• Master In, Slave Out (data from
slave to the master)
• Shared by slaves
• Non-selected slaves, “tri-state”
their MISO outputs
• SPI is a ‘data exchange’ protocol
• As a bit is clocked out of the
master and received by the slave,
the slave clocks out a bit that is
received by the master

Introduction to Mechatronics, Figure 7.5 p. 110.

BJ Furman SJSU Mechanical and Aerospace


16-May-23 294
Engineering ME 285
SPI data transfer modes
• Four transfer modes Mode 0 Mode 1
• Mode 0: SCK idle low, rising edge
• Mode 1: SCK idle low, falling edge
• Mode 2: SCK idle high, falling edge
• Mode 3: SCK idle high, rising edge
• Used most often

Mode 2 Mode 3

Introduction to Mechatronics, Figure 7.6 p. 111.

BJ Furman SJSU Mechanical and Aerospace Engineering ME


16-May-23 295
285
Many digital components use SPI
• See the (partial) list of SPI devices:
http://www.mct.net/faq/spi.html
Part 3
ARDUINO C
Pin mode function

• These function allow access to the pins


• Set a pin to act as an INPUT or OUTOUT
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
• Assign the state of an output pin
• Assign either LOW or HIGH
digitalWrite(pin , Value)
Value
• HIGH
• LOW
Digital input
function
• Returns the state of an input pin
• Returns either LOW or HIGH
digitalRead(pin)
Analog input
function
• Returns the state of an analog pin
• Returns an integer number from 0 to 1023
• 0 for 0Volt 1023 for 5Volts
analogRead(pin)
Pulse Width
Modulation
▶ On-Time −Duration of time signal is high.
▶ Off-Time −Duration of time signal is low.
▶ Period −It is represented as the sum of
on-time and off-time of PWM signal.
▶ Duty Cycle −It is represented as the
percentage of time signal that remains on
during the period of the PWM signal.
Analog Output Function

▶ writes an analog value (PWM wave) to a pin


▶ this function works on pins 3, 5, 6, 9, 10, and 11.
▶ Values from 0 to 255
▶ 0 mean Zero Volt
▶ 255 mean 5 Volt
analogWrite(pin,value)
Delay
function
• Pauses the program for milliseconds
• Useful for human interaction
▶ delay(m sec)
Delay
Microseconds()
▶ The same function of normal “delay” but
▶ Normal delay measure in mille second
▶ This function measure in micro second
delayMicroseconds(time);
pulse
In()
• We use this function to calculate time from Arduino call it to end of code
• Frist argument is the pin number
• Second argument is the pulse level we want to detect
pulseIn (Pin, State);
Communication
serial
communication
▶ Used for communication between the Arduino board and a computer or
other devices.
▶ All Arduino boards have at least one serial port
▶ It communicates on digital pins 0 (RX) and 1 (TX) as well as with the
computer via USB.
▶ Thus, if you use these functions, you cannot also use pins 0 and 1 for
digital input or output.
Serial
functions
 Serial . begin(Baud Rate)
▶ To start communication with other devices
▶ Sets the data rate in bits per second (baud) for serial data transmission
 Serial . print(Value, Format)
▶ To show data received from Arduino on serial monitor on your PC .
▶ Format is optional Parameter [BIN, OCT, HEX, DEC]
▶ Printed Data shown in the same line
Serial
Communication
▶ Serial.available()
▶ Get the number of bytes available for reading from the serial port.
▶ Data Returned stored in Serial Buffer Register

▶ Serial.read()
▶ Reads incoming serial data
▶ Return Data
Part 4
SENSORS AND ACTUATORS
Basic Electronic
Component
▶ LED
▶ LDR
▶ Button
▶ Potentiometer
▶ Buzzer
LED

 Two terminal “ anode + the long terminal


cathode – the short terminal “

 Current only flow in one direction + to –

 Anode – cathode voltage must be above


threshold

 LEDs have a maximum current limit

 Don’t connect LEDs directly with power


supply
Push
button
• Closing switch complete circuit
• Voltage on both terminal is identical when switch is closed
Potentiometer

A potentiometer, informally a pot, is a three-terminal resistor with a sliding or rotating


contact that forms an adjustable voltage divider. If only two terminals are used, one end
and the wiper, it acts as a variable resistor or rheostat.
Light Depended Resistor “
LDR”
• Two terminal device
• Analog sensor
• In darkness resistance increase
• In brightness resistance decrease
Buzze
r
• Two input :- signal / ground
• Produces a sound when applying voltage
Most Important
Modules
▶ Liquid Crystal Display (LCD)
▶ Ultrasonic HC-SR04
▶ Relay Module
▶ H-Bridge
▶ Bluetooth Module HC-05
Liquid Crystal
Display
▶ Has it’s own Library to use with Arduino
▶ Need variable resistor to control display
contrast
▶ Use Parallel interface
Ultrasoni
c
▶ 4 terminal device
• Vcc → 5V
• GND → 0V
• Trig → output
• Echo→ input

▶ To calculate distance in cm use the


following equation
Time in micro second /58 = distance in cm
Relay
Module
▶ Use to Control High Power Devices
▶ Digital Control
▶ NC → Normally Open
▶ NO → Normally Close
Bluetooth
Module
▶ Use Serial Communication
▶ TX in Bluetooth connected to RX with
Arduino and Vise Versa
H-
Bridge
▶ Each motor has two control Line
▶ Can control both direction and speed
▶ Need external power source
H-bridge truth
table
DC-
Motors
▶ Need H-bridge to control
▶ Never Connect directly with Arduino
Servo
Motor

• You can control in it’s angle


• Use PWM to control
• Only 180 degree rotate
Part 5
CIRCUIT DIAGRAMS

You might also like