SlideShare uma empresa Scribd logo
1 de 99
Baixar para ler offline
2013

Beginners Guide To
Embedded Systems & Robotics

Vivekanand goud j
www.myembeddedrobotics.blogspot.in
vivekanandgoud4@gmail.com
Contribution
mazidi
Abhijeet Gupta
Ankur Agrawal
Tanmay Gangwani

Acknowledgement

Robocon Team, IIT Kanpur
Robotics Club, IIT Kanpur
Electronics Club, IIT Kanpur
Centre for Mechatronics, IIT Kanpur

2|Page

Designed by vivekanand goud j| my embedded robotics
Contents
Section A: Digital Electronics

Chapter 1

Basics ....................................................................................... 8

1.1

What is a Digital system? .................................................................................................... 8

1.2

Assigning States .................................................................................................................. 8

1.3

Number Systems in digital electronics................................................................................ 8

1.4

Types of Digital Circuits....................................................................................................... 8

1.5

Clock: Building block of a sequential circuit ....................................................................... 9

1.6

Logic Gates: Building block of a combinatorial circuitry..................................................... 9

1.7

Practical Circuiting Elements ............................................................................................ 10

1.7.1

Resistor: .................................................................................................................... 10

1.7.2

Capacitor: .................................................................................................................. 10

1.7.3

Breadboard: .............................................................................................................. 11

1.7.4

Integrated Circuits (IC) .............................................................................................. 11

1.7.5

LED ............................................................................................................................ 12

Chapter 2
2.1

Some Integrated Circuits and Implementation ....................... 13

555 .................................................................................................................................... 13

2.1.1

Monostable mode..................................................................................................... 13

2.1.2

Astable mode ............................................................................................................ 14

2.2

4029 counter..................................................................................................................... 15

2.2.1
2.3

Pin Description .......................................................................................................... 15

7447: BCD to 7 segment display decoder ......................................................................... 16

2.3.1

Pin Description .......................................................................................................... 16

2.4

LDR (Light Dependent Resistor) ........................................................................................ 17

2.5

Operational Amplifier (Opamp) ........................................................................................ 17

2.5.1
2.6

Opamp as a comparator ........................................................................................... 18

7805 Voltage Regulator .................................................................................................... 18

3|Page

Designed by vivekanand goud j| my embedded robotics
Section B: Embedded Systems

Chapter 3

Introduction to Microcontrollers ........................................... 20

3.1

Compiler / IDE (Integrated Development Environment) .................................................. 22

3.2

Programmer ...................................................................................................................... 22

Chapter 4
23

Code Vision AVR (CVAVR) ......................................................

4.1

CHIP:.................................................................................................................................. 24

4.2

PORT: ................................................................................................................................ 25

Chapter 5
5.a

Introduction to Atmega 16 Microcontroller ........................... 26

Introduction to Atmega 16 Microcontroller

5.1

Features ............................................................................................................................ 26

5.2

Pin Configuration .............................................................................................................. 26

5.3

Block Diagram ................................................................................................................... 27

5.4

Pin Descriptions ................................................................................................................ 28

5.5

Digital Input Output Port .................................................................................................. 29

5.6 Registers............................................................................................................................ 29
5.b Introduction to 8051 Microcontroller
•
5.1 What is 8051 Standard?
•
5.2 8051 Microcontroller's pins
•
5.3 Input/Output Ports (I/O Ports)
•
5.4 8051 Microcontroller Memory Organisation
•
5.5 SFRs (Special Function Registers)
•
5.6 Counters and Timers
•
5.7 UART (Universal Asynchronous Receiver and Transmitter)
•
5.8 8051 Microcontroller Interrupts
5.9 8051 Microcontroller Power Consumption Control

Chapter 6

I/O Ports: ............................................................................... 30

6.1

DDRX (Data Direction Register) ........................................................................................ 30

6.2
31

PORTX (PORTX Data Register)...........................................................................................

6.2.1

Output Pin................................................................................................................. 31

6.2.2

Input Pin.................................................................................................................... 31

6.3

PINX (Data Read Register)................................................................................................. 32

4|Page

Designed by vivekanand goud j| my embedded robotics
Chapter 7

LCD Interfacing ...................................................................... 33

7.1

Circuit Connection ............................................................................................................ 33

7.2

Setting up in Microcontroller............................................................................................ 33

7.3

Printing Functions ............................................................................................................. 34

7.3.1

lcd_clear() ................................................................................................................. 34

7.3.2

lcd_gotoxy(x,y).......................................................................................................... 34

7.3.3

lcd_putchar(char c) ................................................................................................... 35

7.3.4

lcd_putsf(constant string)......................................................................................... 35

5|Page

Designed by vivekanand goud j| my embedded robotics
7.3.5

lcd_puts(char arr) ..................................................................................................... 35

7.3.6

itoa(int val, char arr[])............................................................................................... 35

7.3.7

ftoa(float val, char decimal_places, char arr[])......................................................... 35

Chapter 8

UART Communication ............................................................ 36

8.1

UART: Theory of Operation .............................................................................................. 36

8.2

Serial Port of Computer .................................................................................................... 37

8.3

Setting up UART in microcontroller .................................................................................. 38

8.3.1

putchar() ................................................................................................................... 39

8.3.2

getchar().................................................................................................................... 39

8.3.3

putsf()........................................................................................................................ 39

8.4

Docklight ........................................................................................................................... 40

Chapter 9

Timers .................................................................................... 41

9.1

Basic Theory ...................................................................................................................... 41

9.2

Fast PWM Mode ............................................................................................................... 42

9.3

CTC Mode.......................................................................................................................... 43

Chapter 10

SPI: Serial Peripheral Interface ............................................. 44

10.1

Theory of Operation ..................................................................................................... 44

10.2

Setting up SPI in Microcontroller .................................................................................. 45

10.2.1

Master Microcontroller ........................................................................................ 45

10.2.2

Slave Microcontroller............................................................................................ 45

10.3

Data Functions .............................................................................................................. 45

10.3.1

Transmit Data........................................................................................................ 45

10.3.2

Receive Data ......................................................................................................... 45

Chapter 11
46

ADC: Analog to Digital Converter .........................................

11.1

Theory of operation ...................................................................................................... 46

11.2

Setting up Microcontroller............................................................................................ 46

11.3

Function for getting ADC .............................................................................................. 47

Chapter 12

Interrupts............................................................................. 48

Example .................................................................................................................................. 48
6|Page

Designed by vivekanand goud j| my embedded robotics
12.1

Polling ........................................................................................................................... 48

12.2

Hardware interrupt....................................................................................................... 48

12.3

Hardware Interrupt or polling?..................................................................................... 48

12.4

Setting up Hardware Interrupt in Microcontroller ....................................................... 49

12.5

Functions of Interrupt Service Routine......................................................................... 49

Section C: Robotics

Chapter 13
13.1

Introduction to Autonomous Robots ................................... 51

Robot Chassis Designing ............................................................................................... 51

13.1.1

Robot with steering wheel:................................................................................... 51

13.1.2

Robot with differential drive: ............................................................................... 52

Chapter 14

Motor Driver ........................................................................ 54

14.1

H- Bridge: ...................................................................................................................... 54

14.2
55

Motor Driver ICs: L293/L293D and L298.......................................................................

14.2.1

Difference between L293 and L298: ..................................................................... 56

14.2.2

Speed Control: ...................................................................................................... 56

Chapter 15

Sensors ................................................................................ 57

15.1

Analog Sensor ............................................................................................................... 57

15.2
58

Digital IR Sensor - TSOP Sensor.....................................................................................

6|Page

Designed by vivekanand goud j| my embedded robotics
Section A
Digital Electronics

7|Page

Designed by vivekanand goud j| my embedded robotics
Chapter 1 Basics
1.1 What is a Digital system?
In most general terms, this system’s behavior is sufficiently explained by using only two of its
states can be Voltage(more than x volts or less?),distance covered(more than 2.5 km or less?],truefalse or weight of an elephant(will my weighing machine withstand it?) )

Note that although in every case, the all the intermediate states ARE POSSIBLE AND DO
EXIST, our point of interest are such that we don’t require their explicit description. In electronic
systems we mostly deal with Voltage levels as digital entities.

1.2 Assigning States
There is no specific fixed definition of logic levels in electronics. Most commonly used level
designation is the one used in CMOS and TTL (transistor transistor logic) families:
Logic high –> designated as ‘1’
Logic low –> designated as ‘0’
Where high and low are actually ‘higher’ and ‘lower’ with respect to a reference voltage
level (ideally taken as 2.5V)

GOOGLY: Why assign ‘0’and ‘1’ and not ‘a ‘and ‘b’, ’x’ and ‘y ,’cat ‘and ‘dog’?
ANS: Computational ease!

1.3 Number Systems in digital electronics
1. Binary: Only ‘0’ and ‘1’.
2. Hexadecimal: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

1.4 Types of Digital Circuits

Combinatorial Circuits: In these circuits, the past states are immaterial
and the output depends only upon the present state. Example logic gates

Sequential circuits: In these circuits, the next state is completely
determined by the past states. Hence these follow a predictable structure
and essentially require a timing device. Ex. counters, flip flops.

8|Page

Designed by vivekanand goud j| my embedded robotics
1.5 Clock: Building block of a sequential circuit
A clock is simply alternate high and low states of voltage with time i.e. essentially a square wave.
Important terms related to clock are its duty cycle and its frequency:
Duty cycle: It is the ratio of T and T +T
h
h
l

𝐷=

𝑇ℎ
𝑇𝑙+𝑇ℎ

1.6 Logic Gates: Building block of a combinatorial circuitry
These are essentially combinatorial circuits used to implement logical Boolean operations like AND,
NAND, OR, XOR and NOT. NOT and NAND are called universal gates as any other gate can be
formed using either of them!

Figure 1

9|Page

Figure 2: Table of Logic
Gates

Designed by vivekanand goud j| my embedded robotics
1.7 Practical Circuiting Elements

1.7.1 Resistor:
A color scheme is followed to give the specifications of a resistor. The table for color code is
shown below:

The 1st two bands specify the 2 digits of the resistor value whereas the
3rd band specifies the multiplier in terms of the power to which 10 is
raised and multiplied to the 2 digits.
The tolerance tells the possible % variation of the resistor value about
the value indicated by bands.
Figure 3: Table of Resistance

1.7.2 Capacitor:
The 2 types of capacitors we frequently use in circuits are ceramic and electrolytic capacitors. While
ceramic capacitors do not have a fixed polarity; electrolytic capacitors should be connected in their
specified polarities only else they might blow off! This polarity is usually provided on the side of the
capacitors ‘corresponding leg.

Figure 5: Electrolytic cap with –ve polarity leg seen

10 | P a g e

Figure 4: Ceramic cap with value 15x104 pF

Designed by vivekanand goud j| my embedded robotics
1.7.3 Breadboard:
This is the base used for setting up the circuit. This has embedded metal strips in it that form a grid
of connections inside its body. This allows us to take multiple connections from a single point
without any need of soldering/disordering as in PCBs. It is always a good habit to test the circuit on
breadboard before making it on a PCB.

Figure 6: Top view showing the connecting holes. Bottom view shows the contact metal strips

1.7.4 Integrated Circuits (IC)
ICs or Integrated Circuits are packaged circuits designed for some
fixed purpose. An IC has its fixed IC name/number that can be used
to get catalog of its functions and pin configuration. ICs come in
various sizes and packages depending upon the purpose.
NOTE: Numbering scheme of IC pins will be explained in the
lab session. Different ICs may have different number of pins.

Figure 7: IC

11 | P a g e

Designed by vivekanand goud j| my embedded robotics
1.7.5 LED
LED (Light Emitting Diode) is frequently used to display the outputs at various stages of the circuit. It
is essentially a Diode with the energy released in the form of photons due to electron transitions
falling in the visible region. Hence normal diode properties apply to it.
It glows only in fwd bias mode i.e. with p junction connected to +ve voltage and n junction to
negative.
Diodes are essentially low power devices. The current through the LED should be less than
20mA.Hence always put a 220 ohm resistor in series with the LED.
Never forget that LEDs consume a significant amount of power of the outputs of the ICs (CMOS
based).Hence it is advisable to only use them for checking the voltage level (high or low) and then
remove them.

Figure 8:
LEDs

12 | P a g e

Designed by vivekanand goud j| my embedded robotics
Chapter 2 Some Integrated Circuits and Implementation
2.1 555
555 is an IC used to generate a clock .The
two attributes of a clock are
Frequency
Duty cycle.
Both of these can be changed using this IC,
however the duty cycle is always <50%.
There are two modes in which 555 can run.

Figure 9: Pin Configuration of 555

2.1.1 Monostable mode
As the name suggests; in this mode the output is stable in only one (mono) state i.e. ‘off’ state.
Thus it can stay only for a finite time, if triggered, to the other state i.e. ‘on’ state. This time can be
set choosing appropriate values of resistances in the formula:

T = 1.1 x R1 x C1

Figure 10: 555 in monostable mode

13 | P a g e

Designed by vivekanand goud j| my embedded robotics
2.1.2 Astable mode
In this mode; the output is stable neither in ‘high’ state nor in ‘low ’ state. Hence it oscillates from one
state to another giving us a square wave or clock. We can set the clock frequency and Duty cycle D by
the formulae:

F=

� .𝟒𝟒
𝑹� +� 𝑹� 𝑪�

D=

(𝑹� +𝑹� )
(𝑹� +� 𝑹� )

Figure 11: 555 in astable mode

NOTE: Capacitor C2 is just to filter the noise and its value can be suitably chosen to be 0.01µF. It
can also be neglected.

14 | P a g e

Designed by vivekanand goud j| my embedded robotics
2.2 4029 counter
With the clock made, we are ready to count the number of pulses passed into the circuit. Note that
any kind of counting requires a memory (you got to know that you have just counted ‘3’ to go to
‘4’!). Hence 4029 can also be used as a memory element that remembers its immediate previous
state.

Figure 12: 4029 pin
configuration

2.2.1 Pin Description
PIN No.
1

Name
Parallel load

2
3
4
5

Output Bit 3
Parallel input bit 3
Parallel input bit 0
Clock enable bar

6
7

Output Bit 0
TC bar

8
9

Gnd
Binary/Hex bar

10

Up/Down bar count

11
12
13
14
15
16

Output bit 1
Parallel input bit 1
Parallel input bit 2
Output bit 2
Clock pulse
Vdd

15 | P a g e

Pin function
If given high; loads the value of
Parallel bit into the o/p bits
Most significant bit of o/p
Most significant bit of parallel i/p
Least significant bit of parallel i/p
Low on this pin enables counting as
per the clock received
Least significant bit of parallel o/p
Output bit that gives a low when the
count is complete. Can be used to signal
the end of counting.
Needed for powering
To choose b/w binary and
hexadecimal modes
To choose b/w up counting and
down counting modes
2nd bit of o/p
2nd bit of i/p
3rd bit of i/p
3rd bit of o/p
Clock pulse is given here
Needed for powering

Designed by vivekanand goud j| my embedded robotics

Connection reqd.
Gnd
To pin 6 of 7447
Input
Input
Gnd
To pin 7 of 7447
None if you don’t
want to use it
Gnd
low for count 0-15
high for count 0-9
Low for down count
High for up count
To pin 1 of 7447
Input
Input
To pin 2 of 7447
Clock from 555
+5 V
2.3 7447: BCD to 7 segment display decoder
For displaying the number in the counter output on a seven segment display (i.e. 7 LEDs making up a
figure of ‘8’ as in a general calculator. See fig. ) we need to decode the 4 bits and match them to the 7
pins for lighting the LEDs corresponding to the number. This work is done by 7447.

Figure 13: 7447 pin configuration

2.3.1 Pin Description

PIN
no.
1
2
3

4
5
6
7
8
9-15
16

Name

Function
2nd bit(O1) of 4029’s o/p
3rd bit(O2) of 4029’s o/p
Used to check that all LEDs of 7
seg are working.

i/p B
i/p C
Lamp Test
bar
BI /RBI
RBI
i/p D
i/p A
Gnd
a-g as per the
fig
Vcc

Kept high to allow normal function
Blanks ‘0’ from being displayed
Most significant bit(O3) of 4029’s
o/p
3rd bit(O2) of 4029’s o/p
For power
The o/p pins to 7segment display
For power

Connection reqd.
To O1 of 4029
To O2 of 4029
High for normal fn
Low to glow all
LEDs
Kept high
Kept high
To O2 of 4029
To O2 of 4029
Connected to gnd
To 7 seg display
Connected to +5 V

NOTE:
The COM pins are to be connected to Vcc via 220 ohm resistor. Why resistor is required??
The dot pin is just for display of decimal point and essentially only makes the upper and
lower sides distinguishable from each other for a single display. without the asymmetry
produced by dot how will we be able to see which side is upper and which is lower?

16 | P a g e

Designed by vivekanand goud j| my embedded robotics
2.4 LDR (Light Dependent Resistor)
Light Dependent Resistor (LDR) or photo resistor is a device that acts like a resistance and its
resistance varies with the intensity of light incident on it. In this device, if photons of sufficient
energy fall on it, the resistance drops drastically as the electrons in the semiconductor are able to
jump from the valence band to the conduction band and are available for conduction. The LDRs used
are mostly responsive to visible light. The resistance might drop from as high as 1MΩ in the dark to 1
k Ω in bright light.

Figure 14: LDRs. The coiled portion is responsive to light

2.5 Operational Amplifier (Opamp)
Opamp is a very important device used in everyday electronics .It is essentially a differential
amplifier with a very high gain of the order of 105!By differential amplifier I mean that it amplifies
the difference of 2 signals and gives the output.
Opamp equation:

Vout= A (V+ - V- )

where A is the gain of the order 105.

Ironically, this high gain in open loop makes it impossible to use it as a general purpose
differential amplifier directly.

GOOGLY: If (V+-V-) = 0.005V; Vss = 12V what will be the output??

17 | P a g e

Designed by vivekanand goud j| my embedded robotics
2.5.1 Opamp as a comparator
Simplest use of Opamp is as a comparator. It can be used to convert an analog signal to a digital
signal defined by a fixed threshold. Set V- as the threshold voltage say 2.5 V and apply the analog
signal to be digitized at V+ .What will be the output? Well if you have worked out the googly; this
should be a piece of cake!

2.6 7805 Voltage Regulator
7805 voltage regulator is used to get +5 V output out of a higher voltage supply (7.5V-20V).We use
adapter’s supply to generate +5V here. Connect the gnd and +12V of adapter to the pins as shown
and get +5V directly as an output out of the 3rd pin. Current up to 0.5 A can be obtained from this
regulator without any significant fall in voltage level.

NOTE: Use 2 capacitors of value say 0.1µF to filter the noise in the input and output of regulator’s
supply as shown.

18 | P a g e

Designed by vivekanand goud j| my embedded robotics
Section B
Embedded Systems

19 | P a g e

Designed by vivekanand goud j| my embedded robotics
Chapter 3 Introduction to Microcontrollers
You must be knowing about Digital Integrated Circuits (ICs) right ? For example:
7404: Hex Inverter
7408: Quad 2-input AND gate
7410: Triple 3-input NAND Gate
7432: Quad 2-input OR Gate
7457: 60:1 Frequency divider

There are AND, XOR, NAND, NOR, OR logic gate ICs, Counters, Timers, Seven Segment
Display Drivers and much more. Just check out 7400 Series and 4000 Series of Integrated
Circuits.
Now let’s take Quad 2 input AND gate IC. It has 4 AND gates, each having 2 pins for input
and 1 pin for output. The truth table or the function table of each gate is fixed. This is as
follows,
Input 1

Input 2

Output

0

0

0

0

1

0

1

0

0

1

1

1

Similarly all the Integrated circuits have their function tables and input and output pins fixed.
You cannot change the function and no input pin act as output and vice versa. So whenever
you want to design some circuit you first have to get the output as a function of inputs and
then design it using gates or whatever the requirement is.
So once a circuit is built we cannot change its function ! Even if you want to make some
changes again you have to consider all the gates and components involved. Now if you are
designing any circuit which involves change of the function table every now and then you are
in trouble ! For example if I want to design an Autonomous Robot which should perform
various tasks and I don’t just want to fix the task. Suppose I make it to move in a path then I
want to change the path ! How to do that ?
Here comes the use of Microcontrollers ! Now if I give you an Integrated Circuit with 20 pins
and tell you that you can make any pin as output or input also you can change the function
table by programming the IC using your computer ! Then your reactions will be wow ! that’s
nice :-) That’s what the most basic function of a microcontroller is. It has set of pins called as
PORT and you can make any pin either as output or input. After configuring pins you can
program it to perform according to any function table you want. You can change the
configuration or the function table as many times you wants.
There are many Semiconductor Companies which manufactures
microcontrollers. Some of them are:
Intel
Atmel
Microchip
Motorola

20 | P a g e

Designed by vivekanand goud j| my embedded robotics
We will discuss about Atmel Microcontrollers commonly known as AVR in this
section.

Question: How a microcontroller works !
Answer: Well I cannot go into lot of details about the working because it is a vast topic in
itself. I can just give an overview.
Microcontroller consists of an Microprocessor (CPU that is Central processing Unit) which is
interfaced to RAM (Random Access Memory) and Flash Memory (one your pen drive has !).
You feed your program in the Flash Memory on the microcontroller. Now when you turn on
the microcontroller, CPU accesses the instruction from RAM which access your code from
Flash. It sets the configuration of pins and start performing according to your program.
Question: How to make the code ?
Answer: You basically write the program on your computer in any of the high level
languages like C, C++, JAVA etc. Then you compile the code to generate the machine file.
Now you will ask what this machine file is ? All the machines understand only one language,
0 & 1 that is on and off. Now this 0 & 1 both corresponds to 2 different voltage levels for
example 0 volt for 0 logic and +5 volt for 1 logic. Actually the code has to be written in this
0, 1 language and then saved in the memory of the microcontroller. But this will be very
difficult for us ! So we write the code in the language we understand (C) and then compile
and make the machine file (.hex). After we make this machine file we feed this to the
memory of the microcontroller.
Question: How to feed the code in the flash of Microcontroller ?
Answer: Assuming you have the machine file (.hex) ready and now you want to feed that to
the flash of the microcontroller. Basically you want to make communication between your
computer and microcontroller. Now computer has many communication ports such as Serial
Port, Parallel Port and USB (Universal Serial Bus).
Lets take Serial Port, it has its own definition that is voltage level to define 0 & 1 (yeah all
the data communication is a just collection of 0 & 1 ) Serial Port's protocol is called as UART
(Universal Asynchronous Receiver & Transmitter) Its voltage levels are :-12 volt for 0 logic
and +12 volt for 1 logic.
Now the voltage levels of our microcontroller are based on CMOS (Complementary Metal
Oxide Semiconductor) technology which has 0 volt for 0 logic and +5 volt for 1 logic.
Two different machines with 2 different ways to define 0 & 1 and we want to exchange
information between them. Consider microcontroller as a French and Computer's Serial Port
as an Indian person (obviously no common language in between !) If they want to exchange
information they basically need a mediator who knows both the language. He will listen one
person and then translate to other person. Similarly we need a circuit which converts CMOS
(microcontroller) to UART (serial port) and vice versa. This circuit is called as programmer.
Using this circuit we can connect computer to the microcontroller and feed the machine file
to the flash.

21 | P a g e

Designed by vivekanand goud j| my embedded robotics
3.1 Compiler / IDE (Integrated Development Environment)

Atmel Microcontrollers are very famous as they are very easy to use. There are many
development tools available for them. First of all we need an easy IDE for developing code. I
suggest beginners to use CVAVR (Code Vision AVR) Evaluation version is available for free
download from the website. It has limitation of code size. It works on computers with
Windows platform that is Windows XP & Vista.
Some famous compilers/development tools supporting Windows for Atmel Microcontrollers
are:
WINAVR (AVRGCC for Windows)
Code Vision AVR (CVAVR)
AVR Studio (Atmel's free developing tool)

AVRGCC is a very nice open source compiler used by most of the people.

3.2

Programmer

Programmer basically consists of two parts:
Software (to open .hex file on your computer)
Hardware (to connect microcontroller)

Hardware depends on the communication port you are using on the computer (Serial, Parallel
or USB). I suggest beginners to use Serial Programmer as it is very easy to build. Software
for that is Pony Prog. Some famous Windows (XP, Vista) programmers are:
Pony Prog (Serial, Parallel)
AVRdude (supports many hardwares)
AVRStudio (supports Atmel's hardware)
ATProg (Serial)
USB-ASP (USB)

22 | P a g e

Designed by vivekanand goud j| my embedded robotics
Chapter 4 Code Vision AVR (CVAVR)

An IDE has following functions:
Preprocessing
Compilation
Assembly
Linking
Object Translation
Text Editor
If we just use compiler and linker independently we still need to get a text editor. So
combining everything will actually mess things up. So the best way is to get Software which
has it all. That’s called an Integrated Development Environment, in short IDE.
I consider Code-Vision-AVR to be the best IDE for getting started with AVR
programming on Windows XP, Vista. It has a very good Code Wizard which generate codes
automatically ! You need not mess with the assembly words. So in all my tutorials I will be
using CVAVR. You can download evaluation version for free which has code size limitation
but good enough for our purpose.
For all my examples I will be using Atmega-16 as default microcontroller because it very
easily available and is powerful enough with sufficient number of pins and peripherals we
use. You can have a look on the datasheet of Atmega-16 in the datasheet section.
Let’s take a look on the software. The main window looks like following,

23 | P a g e

Designed by vivekanand goud j| my embedded robotics
Now click on File ---> New --->Project
A pop up window will come asking whether you want to use Code Wizard AVR,
obviously select yes because that is the reason we are using CVAVR !
Now have a look on this Wizard. It has many tabs where we can configure PORTS,
TIMERS, LCD, ADC etc. I am explaining some of them

4.1 CHIP:
Select the chip for which you are going to write the program. Then select the frequency at
which Chip is running. By default all chips are set on Internal Oscillator of 1 MHz so select 1
MHz if that is the case. If you want to change the running clock frequency of the chip then
you have to change its fuse bits (I will talk more about this in fuse bits section).

24 | P a g e

Designed by vivekanand goud j| my embedded robotics
4.2 PORT:
PORT is usually a collection of 8 pins.
From this tab you can select which pin you want to configure as output and which as
input. It basically writes the DDR and PORT register through this setting. Registers are
basically RAM locations which configure various peripherals of microcontroller and by
changing value of these registers we can change the function it is performing. I will talk more
about registers later. All the details are provided in the datasheet.
So you can configure any pin as output or input by clicking the box.
For Atmega-16 which has 4 Ports we can see 4 tabs each corresponding to one Port. You
can also set initial value of the Pins you want to assign. or if you are using a pin as input then
whether you want to make it as pull-up or tristated, again I will talk in details about these
functions later.
Similarly using this code wizard you can very easily configure all the peripherals on the
Atmega.
Now for generating code just go to File ----> Generate, Save and Exit (of the code
wizard)
Now it will ask you name and location for saving three files. Two being project files and
one being the .C file which is your program. try to keep same names of all three files to avoid
confusion. By default these files are generated in C:CVAVRbin
The generated program will open in the text editor. Have a look it has some declarations
like PORT, DDR, TCCR0 and many more. These are all registers which configures various
functions of Atmega and by changing these value we make different functions. All the details
about the registers are commented just below them. Now go down and find following infinite
while loop there. We can start writing our part of program just before the while loop. And as
for most of the applications we want microcontroller to perform the same task forever we put
our part of code in the infinite while loop provided by the code wizard !
while
{
// Place your code here

(1)

};
}
See how friendly this code wizard is, all the work (configuring registers) automatically
done and we don’t even need to understand and go to the details about registers too !
Now we want to generate the hex file, so first compile the program. Either press F9 or go
to Project ---> Compile.
It will show compilation errors if any. If program is error free we can proceed to making
of hex file. So either press Shift+F9 or go to Project ----> Make. A pop up window will
come with information about code size and flash usage etc.
So the machine file is ready now ! It is in the same folder where we saved those 3 files.

25 | P a g e

Designed by vivekanand goud j| my embedded robotics
Chapter 5 Introduction to Atmega 16 Microcontroller
5.1 Features
Advanced RISC Architecture
Up to 16 MIPS Throughput at 16 MHz
16K Bytes of In-System Self-Programmable Flash
512 Bytes EEPROM
1K Byte Internal SRAM
32 Programmable I/O Lines
In-System Programming by On-chip Boot Program
8-channel, 10-bit ADC
Two 8-bit Timer/Counters with Separate Prescalers and Compare Modes
One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture
Four PWM Channels
Programmable Serial USART
Master/Slave SPI Serial Interface
Byte-oriented Two-wire Serial Interface
Programmable Watchdog Timer with Separate On-chip Oscillator
External and Internal Interrupt Sources

5.2 Pin Configuration

26 | P a g e

Designed by vivekanand goud j| my embedded robotics
5.3 Block Diagram

27 | P a g e

Designed by vivekanand goud j| my embedded robotics
5.4 Pin Descriptions

VCC: Digital supply voltage. (+5V)
GND: Ground. (0 V) Note there are 2 ground Pins.
Port A (PA7 - PA0)
Port A serves as the analog inputs to the A/D Converter. Port A also serves as an 8-bit bidirectional I/O port, if the A/D Converter is not used. When pins PA0 to PA7 are used as inputs and
are externally pulled low, they will source current if the internal pull-up resistors are activated. The
Port A pins are tri-stated when a reset condition becomes active, even if the clock is not running.
Port B (PB7 - PB0)
Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). Port
B also serves the functions of various special features of the ATmega16 as listed on page 58 of
datasheet.
Port C (PC7 - PC0)
Port C is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). Port
C also serves the functions of the JTAG interface and other special features of the ATmega16 as
listed on page 61 of datasheet. If the JTAG interface is enabled, the pull-up resistors on pins
PC5(TDI), PC3(TMS) and PC2(TCK) will be activated even if a reset occurs.
Port D (PD7 - PD0)
Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit).
Port D also serves the functions of various special features of the ATmega16 as listed on page 63 of
datasheet.
RESET: Reset Input. A low level on this pin for longer than the minimum pulse length will
generate a reset, even if the clock is not running.
XTAL1: External oscillator pin 1
XTAL2: External oscillator pin 2
AVCC: AVCC is the supply voltage pin for Port A and the A/D Converter. It should be
externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected
to VCC through a low-pass filter.
AREF: AREF is the analog reference pin for the A/D Converter.

28 | P a g e

Designed by vivekanand goud j| my embedded robotics
5.5 Digital Input Output Port

So let’s start with understanding the functioning of AVR. We will first discuss about I/O
Ports. Again I remind you that I will be using and writing about Atmega-16. Let’s first have
a look at the Pin configuration of Atmega-16. Image is attached, click to enlarge.

You can see it has 32 I/O (Input/Output) pins grouped as A, B, C & D with 8 pins in each
group. This group is called as PORT.
PA0 - PA7 (PORTA)
PB0 - PB7 (PORTB)
PC0 - PC7 (PORTC)
PD0 - PD7 (PORTD)

Notice that all these pins have some function written in bracket. These are additional function
that pin can perform other than I/O. Some of them are.
ADC (ADC0 - ADC7 on PORTA)
UART (Rx,Tx on PORTD)
TIMERS (OC0 - OC2)
SPI (MISO, MOSI, SCK on PORTB)
External Interrupts (INT0 - INT2)

5.6

Registers

All the configurations in microcontroller is set through 8 bit (1 byte) locations in RAM
(RAM is a bank of memory bytes) of the microcontroller called as Registers. All the
functions are mapped to its locations in RAM and the value we set at that location that is at
that Register configures the functioning of microcontroller. There are total 32 x 8bit registers
in Atmega-16. As Register size of this microcontroller is 8 bit, it called as 8 bit
microcontroller.

5. B 8051 Microcontroller Architecture


5.1 What is 8051 Standard?



5.2 8051 Microcontroller's pins



5.3 Input/Output Ports (I/O Ports)



5.4 8051 Microcontroller Memory Organisation



5.5 SFRs (Special Function Registers)



5.6 Counters and Timers



5.7 UART (Universal Asynchronous Receiver and Transmitter)



5.8 8051 Microcontroller Interrupts



5.9 8051 Microcontroller Power Consumption Control
2.1 What is 8051 Standard?
Microcontrollers’ producers have been struggling for a long time for attracting more and more choosy
customers. Every couple of days a new chip with a higher operating frequency, more memory and more
high-quality A/D converters comes on the market.
Nevertheless, by analyzing their structure it is concluded that most of them have the same (or at least very
similar) architecture known in the product catalogs as “8051 compatible”. What is all this about?
The whole story began in the far 80s when Intel launched its series of the microcontrollers labelled with
MCS 051. Although, several circuits belonging to this series had quite modest features in comparison to the
new ones, they took over the world very fast and became a standard for what nowadays is ment by a word
microcontroller.
The reason for success and such a big popularity is a skillfully chosen configuration which satisfies needs of
a great number of the users allowing at the same time stable expanding ( refers to the new types of the
microcontrollers ). Besides, since a great deal of software has been developed in the meantime, it simply was
not profitable to change anything in the microcontroller’s basic core. That is the reason for having a great
number of various microcontrollers which actually are solely upgraded versions of the 8051 family. What is
it what makes this microcontroller so special and universal so that almost all the world producers
manufacture it today under different name ?

As shown on the previous picture, the 8051 microcontroller has nothing impressive at first sight:


4 Kb program memory is not much at all.



128Kb RAM (including SFRs as well) satisfies basic needs, but it is not imposing amount.



4 ports having in total of 32 input/output lines are mostly enough to make connection to peripheral
environment and are not luxury at all.

As it is shown on the previous picture, the 8051 microcontroller have nothing impressive at first sight:
The whole configuration is obviously envisaged as such to satisfy the needs of most programmers who work
on development of automation devices. One of advantages of this microcontroller is that nothing is missing
and nothing is too much. In other words, it is created exactly in accordance to the average user‘s taste and
needs. The other advantage is the way RAM is organized, the way Central Processor Unit (CPU) operates
and ports which maximally use all recourses and enable further upgrading.

2.2 8051 Microcontroller's pins
Pins 1-8: Port 1 Each of these pins can be configured as input or output.
Pin 9: RS Logical one on this pin stops microcontroller’s operating and erases the contents of most registers.
By applying logical zero to this pin, the program starts execution from the beginning. In other words, a
positive voltage pulse on this pin resets the microcontroller.
Pins10-17: Port 3 Similar to port 1, each of these pins can serve as universal input or output . Besides, all of
them have alternative functions:
Pin 10: RXD Serial asynchronous communication input or Serial synchronous communication output.
Pin 11: TXD Serial asynchronous communication output or Serial synchronous communication clock
output.
Pin 12: INT0 Interrupt 0 input
Pin 13: INT1 Interrupt 1 input
Pin 14: T0 Counter 0 clock input
Pin 15: T1 Counter 1 clock input
Pin 16: WR Signal for writing to external (additional) RAM
Pin 17: RD Signal for reading from external RAM
Pin 18, 19: X2, X1 Internal oscillator input and output. A quartz crystal which determines operating
frequency is usually connected to these pins. Instead of quartz crystal, the miniature ceramics resonators can
be also used for frequency stabilization. Later versions of the microcontrollers operate at a frequency of 0 Hz
up to over 50 Hz.
Pin 20: GND Ground
Pin 21-28: Port 2 If there is no intention to use external memory then these port pins are configured as
universal inputs/outputs. In case external memory is used then the higher address byte, i.e. addresses A8-A15
will appear on this port. It is important to know that even memory with capacity of 64Kb is not used ( i.e.
note all bits on port are used for memory addressing) the rest of bits are not available as inputs or outputs.
Pin 29: PSEN If external ROM is used for storing program then it has a logic-0 value every time the
microcontroller reads a byte from memory.
Pin 30: ALE Prior to each reading from external memory, the microcontroller will set the lower address byte
(A0-A7) on P0 and immediately after that activates the output ALE. Upon receiving signal from the ALE
pin, the external register (74HCT373 or 74HCT375 circuit is usually embedded ) memorizes the state of P0
and uses it as an address for memory chip. In the second part of the microcontroller’s machine cycle, a signal
on this pin stops being emitted and P0 is used now for data transmission (Data Bus). In this way, by means of
only one additional (and cheap) integrated circuit, data multiplexing from the port is performed. This port at
the same time used for data and address transmission.
Pin 31: EA By applying logic zero to this pin, P2 and P3 are used for data and address transmission with no
regard to whether there is internal memory or not. That means that even there is a program written to the
microcontroller, it will not be executed, the program written to external ROM will be used instead.
Otherwise, by applying logic one to the EA pin, the microcontroller will use both memories, first internal and
afterwards external (if it exists), up to end of address space.
Pin 32-39: Port 0 Similar to port 2, if external memory is not used, these pins can be used as universal inputs
or outputs. Otherwise, P0 is configured as address output (A0-A7) when the ALE pin is at high level (1) and
as data output (Data Bus), when logic zero (0) is applied to the ALE pin.
Pin 40: VCC Power supply +5V

2.3 Input/Output Ports (I/O Ports)
All 8051 microcontrollers have 4 I/O ports, each consisting of 8 bits which can be configured as inputs or
outputs. This means that the user has on disposal in total of 32 input/output lines connecting the
microcontroller to peripheral devices.
A logic state on a pin determines whether it is configured as input or output: 0=output, 1=input. If a pin on
the microcontroller needs to be configured as output, then a logic zero (0) should be applied to the
appropriate bit on I/O port. In this way, a voltage level on the appropriate pin will be 0.
Similar to that, if a pin needs to be configured as input, then a logic one (1) should be applied to the
appropriate port. In this way, as a side effect a voltage level on the appropriate pin will be 5V (as it is case
with any TTL input). This may sound a bit confusing but everything becomes clear after studying a
simplified electronic circuit connected to one I/O pin.
Input/Output (I/O) pin
This is a simplified overview of what is connected to a pin inside the microcontroller. It concerns all pins
except those included in P0 which do not have embedded pullup resistor.

Output pin
A logic zero (0) is applied to a bit in the P register. By turning output FE transistor on, the appropriate pin is
directly connected to ground.

Input pin
A logic one (1) is applied to a bit in the P register. Output FE transistor is turned off. The appropriate pin
remains connected to voltage power supply through a pull-up resistor of high resistance.

A logic state (voltage) on any pin can be changed or read at any moment. A logic zero (0) and logic one (1)
are not equal. A logic one (0) represents almost short circuit to ground. Such a pin is configured as output.
A logic one (1) is “loosely” connected to voltage power supply through resistors of high resistance. Since
this voltage can be easily “pulled down” by an external signal, such a pin is configured as input.
Port 0
It is specific to this port to have a double purpose. If external memory is used then the lower address byte
(addresses A0-A7) is applied on it. Otherwise, all bits on this port are configured as inputs or outputs.
Another characteristic is expressed when it is configured as output. Namely, unlike other ports consisting of
pins with embedded pull-up resistor ( connected by its end to 5 V power supply ), this resistor is left out here.
This, apparently little change has its consequences:

If any pin on this port is configured as input then it performs as if it “floats”. Such input has unlimited input
resistance and has no voltage coming from “inside”.

When the pin is configured as output, it performs as “open drain”, meaning that by writing 0 to some port’s
bit, the appropriate pin will be connected to ground (0V). By writing 1, the external output will keep on
“floating”. In order to apply 1 (5V) on this output, an external pull-up resistor must be embedded.

Only in case P0 is used for addressing external memory ( only in that case), the microcontroller will provide internal
power supply source in order to establish logical ones on pins. There is no need to add external pullup resistors.
Port 1

This is a true I/O port, because there are no role assigning as it is the case with P0. Since it has embedded
pull-up resistors it is completely compatible with TTL circuits.
Port 2

Similar to P0, when using external memory, lines on this port occupy addresses intended for external
memory chip. This time it is the higher address byte with addresses A8-A15. When there is no additional
memory, this port can be used as universal input-output port similar by its features to the port 1.
Port 3

Even though all pins on this port can be used as universal I/O port, they also have an alternative function.
Since each of these functions use inputs, then the appropriate pins have to be configured like that. In other
words, prior to using some of reserve port functions, a logical one (1) must be written to the appropriate bit
in the P3 register. From hardware’s perspective , this port is also similar to P0, with the difference that its
outputs have a pull-up resistor embedded.
Current limitations on pins

When configured as outputs ( logic zero (0) ), single port pins can "receive" current of 10mA. If all 8 bits on
a port are active, total current must be limited to 15mA (port P0: 26mA). If all ports (32 bits) are active, total
maximal current must be limited to 71mA. When configured as inputs (logic 1), embedded pull-up resistor
provides very weak current, but strong enough to activate up to 4 TTL inputs from LS series.

It may be seen from description of some ports, that even though all pins have more or less similar internal
structure, it is necessary to pay attention to which of them will be used for what and how.
For example: If they are used as outputs with high voltage level (5V), then port 0 should be avoided because
its pins do not have added resistor for connection to +5V. Only low logic level can be obtained therefore, if
another port is used for the same purpose, one should have in mind that pull-up resistors have a relatively
high resistance. Consequentaly it can be counted on only several hundreds microamperes of current coming
out of a pin.

2.4 8051 Microcontroller Memory Organisation
The microcontroller memory is divided into Program Memory and Data Memory. Program Memory (ROM)
is used for permanent saving program being executed, while Data Memory (RAM) is used for temporarily
storing and keeping intermediate results and variables. Depending on the model in use ( still referring to the
whole 8051 microcontroller family) at most a few Kb of ROM and 128 or 256 bytes of RAM can be used.
However…
All 8051 microcontrollers have 16-bit addressing bus and can address 64 kb memory. It is neither a mistake
nor a big ambition of engineers who were working on basic core development. It is a matter of very clever
memory organization which makes these controllers a real “ programmers’ tidbit“ .
Program Memory

The oldest models of the 8051 microcontroller family did not have internal program memory . It was added
from outside as a separate chip. These models are recognizable by their label beginning with 803 ( for ex.
8031 or 8032). All later models have a few Kbytes ROM embedded, Even though it is enough for writing
most of the programs, there are situations when additional memory is necessary. A typical example of it is
the use of so called lookup tables. They are used in cases when something is too complicated or when there
is no time for solving equations describing some process. The example of it can be totally exotic (an estimate
of self-guided rockets’ meeting point) or totally common( measuring of temperature using non-linear thermo
element or asynchronous motor speed control). In those cases all needed estimates and approximates are
executed in advance and the final results are put in the tables ( similar to logarithmic tables ).

How does the microcontroller handle external memory depends on the pin EA logic state:
EA=0 In this case, internal program memory is completely ignored, only a program stored in external
memory is to be executed.
EA=1 In this case, a program from builtin ROM is to be executed first ( to the last location). Afterwards, the
execution is continued by reading additional memory.
in both cases, P0 and P2 are not available to the user because they are used for data nd address transmission.
Besides, the pins ALE and PSEN are used too.
Data Memory

As already mentioned, Data Memory is used for temporarily storing and keeping data and intermediate
results created and used during microcontroller’s operating. Besides, this microcontroller family includes
many other registers such as: hardware counters and timers, input/output ports, serial data buffers etc. The
previous versions have the total memory size of 256 locations, while for later models this number is
incremented by additional 128 available registers. In both cases, these first 256 memory locations (addresses
0-FFh) are the base of the memory. Common to all types of the 8051 microcontrollers. Locations available to
the user occupy memory space with addresses from 0 to 7Fh. First 128 registers and this part of RAM is
divided in several blocks.
The first block consists of 4 banks each including 8 registers designated as R0 to R7. Prior to access them, a
bank containing that register must be selected. Next memory block ( in the range of 20h to 2Fh) is bitaddressable, which means that each bit being there has its own address from 0 to 7Fh. Since there are 16 such
registers, this block contains in total of 128 bits with separate addresses (The 0th bit of the 20h byte has the
bit address 0 and the 7th bit of th 2Fh byte has the bit address 7Fh). The third group of registers occupy
addresses 2Fh-7Fh ( in total of 80 locations) and does not have any special purpose or feature.
Additional Memory Block of Data Memory
In order to satisfy the programmers’ permanent hunger for Data Memory, producers have embedded an
additional memory block of 128 locations into the latest versions of the 8051 microcontrollers. Naturally, it’s
not so simple…The problem is that electronics performing addressing has 1 byte (8 bits) on disposal and due
to that it can reach only the first 256 locations. In order to keep already existing 8-bit architecture and
compatibility with other existing models a little trick has been used.
Using trick in this case means that additional memory block shares the same addresses with existing
locations intended for the SFRs (80h- FFh). In order to differentiate between these two physically separated
memory spaces, different ways of addressing are used. A direct addressing is used for all locations in the
SFRs, while the locations from additional RAM are accessible using indirect addressing.
How to extend memory?

In case on-chip memory is not enough, it is possible to add two external memory chips with capacity of
64Kb each. I/O ports P2 and P3 are used for their addressing and data transmission.
From the users’ perspective, everything functions quite simple if properly connected because the most
operations are performed by the microcontroller itself. The 8051 microcontroller has two separate reading
signals RD#(P3.7) and PSEN#. The first one is activated byte from external data memory (RAM) should be
read, while another one is activated to read byte from external program memory (ROM). These both signals
are active at logical zero (0) level. A typical example of such memory extension using special chips for RAM
and ROM, is shown on the previous picture. It is called Hardward architecture.
Even though the additional memory is rarely used with the latest versions of the microcontrollers, it will be
described here in short what happens when memory chips are connected according to the previous schematic.
It is important to know that the whole process is performed automatically, i.e. with no intervention in the
program.


When the program during execution encounters the instruction which resides in exter nal memory (ROM), the
microcontroller will activate its control output ALE and set the first 8 bits of address (A0-A7) on P0. In this
way, IC circuit 74HCT573 which "lets in" the first 8 bits to memory address pins is activated.



A signal on the pin ALE closes the IC circuit 74HCT573 and immediately afterwards 8 higher bits of address
(A8-A15) appear on the port. In this way, a desired location in addtional program memory is completely
addressed. The only thing left over is to read its content.



Pins on P0 are configured as inputs, the pin PSEN is activated and the microcon troller reads content from
memory chip. The same connections are used both for data and lower address byte.
Similar occurs when it is a needed to read some location from external Data Memory. Now, addressing is
performed in the same way, while reading or writing is performed via signals which appear on the control
outputs RD or WR .
Addressing

While operating, processor processes data according to the program instructions. Each instruction consists of
two parts. One part describes what should be done and another part indicates what to use to do it. This later
part can be data (binary number) or address where the data is stored. All 8051 microcontrollers use two ways
of addressing depending on which part of memory should be accessed:
Direct Addressing

On direct addressing, a value is obtained from a memory location while the address of that location is
specified in instruction. Only after that, the instruction can process data (howdepends on the type of
instruction: addition, subtraction, copy…). Obviously, a number being changed during operating a variable
can reside at that specified address. For example:
Since the address is only one byte in size ( the greatest number is 255), this is how only the first 255
locations in RAM can be accessed in this case the first half of the basic RAM is intended to be used freely,
while another half is reserved for the SFRs.
MOV A,33h; Means: move a number from address 33 hex. to accumulator

Indirect Addressing

On indirect addressing, a register which contains address of another register is specified in the instruction. A
value used in operating process resides in that another register. For example:
Only RAM locations available for use are accessed by indirect addressing (never in the SFRs). For all latest
versions of the microcontrollers with additional memory block ( those 128 locations in Data Memory), this is
the only way of accessing them. Simply, when during operating, the instruction including “@” sign is
encountered and if the specified address is higher than 128 ( 7F hex.), the processor knows that indirect
addressing is used and jumps over memory space reserved for the SFRs.
MOV A,@R0; Means: Store the value from the register whose address is in the R0 register
into accumulator

On indirect addressing, the registers R0, R1 or Stack Pointer are used for specifying 8-bit addresses. Since
only 8 bits are avilable, it is possible to access only registers of internal RAM in this way (128 locations in
former or 256 locations in latest versions of the microcontrollers). If memory extension in form of additional
memory chip is used then the 16-bit DPTR Register (consisting of the registers DPTRL and DPTRH) is used
for specifying addresses. In this way it is possible to access any location in the range of 64K.

2.5 SFRs (Special Function Registers)
SFRs are a kind of control table used for running and monitoring microcontroller’s operating. Each of these
registers, even each bit they include, has its name, address in the scope of RAM and clearly defined purpose (
for example: timer control, interrupt, serial connection etc.). Even though there are 128 free memory
locations intended for their storage, the basic core, shared by all types of 8051 controllers, has only 21 such
registers. Rest of locations are intensionally left free in order to enable the producers to further improved
models keeping at the same time compatibility with the previous versions. It also enables the use of programs
written a long time ago for the microcontrollers which are out of production now.
A Register (Accumulator)

This is a general-purpose register which serves for storing intermediate results during operating. A number
(an operand) should be added to the accumulator prior to execute an instruction upon it. Once an arithmetical
operation is preformed by the ALU, the result is placed into the accumulator. If a data should be transferred
from one register to another, it must go through accumulator. For such universal purpose, this is the most
commonly used register that none microcontroller can be imagined without (more than a half 8051
microcontroller's instructions used use the accumulator in some way).
B Register

B register is used during multiply and divide operations which can be performed only upon numbers stored
in the A and B registers. All other instructions in the program can use this register as a spare accumulator
(A).

During programming, each of registers is called by name so that their exact address is not so important for the user.
During compiling into machine code (series of hexadecimal numbers recognized as instructions by the
microcontroller), PC will automatically, instead of registers’ name, write necessary addresses into the microcontroller.
R Registers (R0-R7)
This is a common name for the total 8 generalpurpose registers (R0, R1, R2 ...R7). Even they are not true
SFRs, they deserve to be discussed here because of their purpose. The bank is active when the R registers it
includes are in use. Similar to the accumulator, they are used for temporary storing variables and
intermediate results. Which of the banks will be active depends on two bits included in the PSW Register.
These registers are stored in four banks in the scope of RAM.
The following example best illustrates the useful purpose of these registers. Suppose that mathematical
operations on numbers previously stored in the R registers should be performed: (R1+R2) - (R3+R4).
Obviously, a register for temporary storing results of addition is needed. Everything is quite simple and the
program is as follows :
MOV A,R3; Means: move number from R3 into accumulator
ADD A,R4; Means: add number from R4 to accumulator (result remains in accumulator)
MOV R5,A; Means: temporarily move the result from accumulator into R5
MOV A,R1; Means: move number from R1 into accumulator
ADD A,R2; Means: add number from R2 to accumulator
SUBB A,R5; Means: subtract number from R5 ( there are R3+R4 )

PSW Register (Program Status Word)

This is one of the most important SFRs. The Program Status Word (PSW) contains several status bits that
reflect the current state of the CPU. This register contains: Carry bit, Auxiliary Carry, two register bank
select bits, Overflow flag, parity bit, and user-definable status flag. The ALU automatically changes some of
register’s bits, which is usually used in regulation of the program performing.
P - Parity bit. If a number in accumulator is even then this bit will be automatically set (1), otherwise it will
be cleared (0). It is mainly used during data transmission and receiving via serial communication.
- Bit 1. This bit is intended for the future versions of the microcontrollers, so it is not supposed to be here.
OV Overflow occurs when the result of arithmetical operation is greater than 255 (deci mal), so that it can
not be stored in one register. In that case, this bit will be set (1). If there is no overflow, this bit will be
cleared (0).
RS0, RS1 - Register bank select bits. These two bits are used to select one of the four register banks in
RAM. By writing zeroes and ones to these bits, a group of registers R0-R7 is stored in one of four banks in
RAM.
RS1

RS2

Space in RAM

0

0

Bank0 00h-07h

0

1

Bank1 08h-0Fh

1

0

Bank2 10h-17h

1

1

Bank3 18h-1Fh

F0 - Flag 0. This is a general-purpose bit available to the user.
AC - Auxiliary Carry Flag is used for BCD operations only.
CY - Carry Flag is the (ninth) auxiliary bit used for all arithmetical operations and shift instructions.
DPTR Register (Data Pointer)

These registers are not true ones because they do not physically exist. They consist of two separate registers:
DPH (Data Pointer High) and (Data Pointer Low). Their 16 bits are used for external memory addressing.
They may be handled as a 16-bit register or as two independet 8-bit registers.Besides, the DPTR Register is
usually used for storing data and intermediate results which have nothing to do with memory locations.

SP Register (Stack Pointer)

A value of the Stack Pointer ensures that the Stack Pointer will point to valid RAM and permits Stack
availability. By starting each subprogram, the value in the Stack Pointer is incremented by 1. In the same
manner, by ending subprogram, this value is decremented by 1. After any reset, the value 7 is written to the
Stack Pointer, which means that the space of RAM reserved for the Stack starts from this location. If another
value is written to this register then the entire Stack is moved to a new location in the memory.
P0, P1, P2, P3 - Input/Output Registers

In case that external memory and serial communication system are not in use then, 4 ports with in total of 32
input-output lines are available to the user for connection to peripheral environment. Each bit inside these
ports coresponds to the appropriate pin on the microcontroller. This means that logic state written to these
ports appears as a voltage on the pin ( 0 or 5 V). Naturally, while reading, the opposite occurs – voltage on
some input pins is reflected in the appropriate port bit.
The state of a port bit, besides being reflected in the pin, determines at the same time whether it will be
configured as input or output. If a bit is cleared (0), the pin will be configured as output. In the same manner,
if a bit is set to 1 the pin will be configured as input. After reset, as well as when turning the microcontroller
on , all bits on these ports are set to one (1). This means that the appropriate pins will be configured as
inputs.

Conditionally said, I/O ports are directly connected to the microcontroller’s pins. This means that a logic
state of these registers can be checked by voltmeter and vice versa-voltage on the pins can be checked by
testing their bits!

2.6 Counters and Timers
As explained in the previous chapter, the main oscillator of the microcontroller uses quartz crystal for its
operating. As the frequency of this oscillator is precisely defined and very stable, these pulses are the most
suitable for time measuring (such oscillators are used in quartz clocks as well). In order to measure time
between two events it is only needed to count up pulses from this oscillator. That is exactly what the timer is
doing. Namely, if the timer is properly programmed, the value written to the timer register will be
incremented or decremented after each coming pulse, i.e. once per each machine cycle cycle. Taking into
account that one instruction lasts 12 quartz oscillator periods (one machine cycle), by embedding quartz with
oscillator frequency of 12MHz, a number in the timer register will be changed million times per second, i.e.
each microsecond.
The 8051 microcontrollers have 2 timer counters called T0 and T1. As their names tell, their main purpose is
to measure time and count external events. Besides, they can be used for generating clock pulses used in
serial communication, i.e. Baud Rate.
Timer T0

As it is shown in the picture below, this timer consists of two registers – TH0 and TL0. The numbers these
registers include represent a lower and a higher byte of one 16-digit binary number.
This means that if the content of the timer 0 is equal to 0 (T0=0) then both registers it includes will include 0.
If the same timer contains for example number 1000 (decimal) then the register TH0 (higher byte) will
contain number 3, while TL0 (lower byte) will contain decimal number 232.

Formula used to calculate values in registers is very simple:
TH0 × 256 + TL0 = T
Matching the previous example it would be as follows :
3 × 256 + 232 = 1000

Since the timers are virtually 16-bit registers, the greatest value that could be written to them is 65 535. In
case of exceeding this value, the timer will be automatically reset and afterwords that counting starts from 0.
It is called overflow. Two registers TMOD and TCON are closely connected to this timer and control how it
operates.
TMOD Register (Timer Mode)

This register selects mode of the timers T0 and T1. As illustrated in the following picture, the lower 4 bits
(bit0 - bit3) refer to the timer 0, while the higher 4 bits (bit4 - bit7) refer to the timer 1. There are in total of 4
modes and each of them is described here in this book.

Bits of this register have the following purpose:


GATE1 starts and stops Timer 1 by means of a signal provided to the pin INT1 (P3.3):
o
o



1 - Timer 1 operates only if the bit INT1 is set
0 - Timer 1 operates regardless of the state of the bit INT 1

C/T1 selects which pulses are to be counted up by the timer/counter 1:
o
o



1 - Timer counts pulses provided to the pin T1 (P3.5)
0 - Timer counts pulses from internal oscillator

T1M1,T1M0 These two bits selects the Timer 1 operating mode.
T1M1

T1M0

Mode

Description

0

0

0

13-bit timer

0

1

1

16-bit timer

1

0

2

8-bit autoreload

1

1

3

Split mode



GATE0 starts and stops Timer 1, using a signal provided to the pin INT0 (P3.2):
o
o



1 - Timer 0 operates only if the bit INT0 is set
0 - Timer 0 operates regardless of the state of the bit INT0

C/T0 selects which pulses are to be counted up by the timer/counter 0:
o
o



1 - Timer counts pulses provided to the pin T0(P3.4)
0 - Timer counts pulses from internal oscillator

T0M1,T0M0 These two bits select the Timer 0 operating mode.

T0M1

T0M0

Mode

Description

0

0

0

13-bit timer

0

1

1

16-bit timer

1

0

2

8-bit autoreload

1

1

3

Split mode

Timer 0 in mode 0 (13-bit timer)

This is one of the rarities being kept only for compatibility with the previuos versions of the
microcontrollers. When using this mode, the higher byte TH0 and only the first 5 bits of the lower byte TL0
are in use. Being configured in this way, the Timer 0 uses only 13 of all 16 bits. How does it operate? With
each new pulse coming, the state of the lower register (that one with 5 bits) is changed. After 32 pulses
received it becomes full and automatically is reset, while the higher byte TH0 is incremented by 1. This
action will be repeated until registers count up 8192 pulses. After that, both registers are reset and counting
starts from 0.
Timer 0 in mode 1 (16-bit timer)

All bits from the registers TH0 and TL0 are used in this mode. That is why for this mode is being more
commonly used. Counting is performed in the same way as in mode 0, with difference that the timer counts
up to 65 536, i.e. as far as the use of 16 bits allows.

Timer 0 in mode 2 (Auto-Reload Timer)

What does auto-reload mean? Simply, it means that such timer uses only one 8-bit register for counting, but
it never counts from 0 but from an arbitrary chosen value (0- 255) saved in another register.
The advantages of this way of counting are described in the following example: suppose that for any reason
it is continuously needed to count up 55 pulses at a time from the clock generator.
When using mode 1 or mode 0, It is needed to write number 200 to the timer registers and check constantly
afterwards whether overflow occured, i.e. whether the value 255 is reached by counting . When it has
occurred, it is needed to rewrite number 200 and repeat the whole procedure. The microcontroller performs
the same procedure in mode 2 automatically. Namely, in this mode it is only register TL0 operating as a
timer ( normally 8-bit), while the value from which counting should start is saved in the TH0 register.
Referring to the previous example, in order to register each 55th pulse, it is needed to write the number 200
to the register and configure the timer to operate in mode 2.

Timer 0 in Mode 3 (Split Timer)

By configuring Timer 0 to operate in Mode 3, the 16-bit counter consisting of two registers TH0 and TL0 is
split into two independent 8-bit timers. In addition, all control bits which belonged to the initial Timer 1
(consisting of the registers TH1 and TL1), now control newly created Timer 1. This means that even though
the initial Timer 1 still can be configured to operate in any mode ( mode 1, 2 or 3 ), it is no longer able to
stop, simply because there is no bit to do that. Therefore, in this mode, it will uninterruptedly “operate in the
background “.
The only application of this mode is in case two independent 'quick' timers are used and the initial Timer 1
whose operating is out of control is used as baud rate generator.
TCON - Timer Control Register

This is also one of the registers whose bits directly control timer operating.
Only 4 of all 8 bits this register has are used for timer control, while others are used for interrupt control
which will be discussed later.



TF1 This bit is automatically set with the Timer 1 overflow



TR1 This bit turns the Timer 1 on
o

1 - Timer 1 is turned on

o

0 - Timer 1 is turned off



TF0 This bit is automatically set with the Timer 0 overflow.



TR0 This bit turns the timer 0 on
o

1 - Timer 0 is turned on

o

0 - Timer 0 is turned off

How to start Timer 0 ?

Normally, first this timer and afterwards its mode should be selected. Bits which control that are resided in
the register TMOD:
This means that timer 0 operates in mode 1 and counts pulses from internal source whose frequency is equal
to 1/12 the quartz frequency.
In order to enable the timer, turn it on:

Immediately upon the bit TR0 is set, the timer starts operating. Assuming that a quartz crystal with frequency
of 12MHz is embedded, a number it contains will be incremented every microsecond. By counting up to
65.536 microseconds, the both registers that timer consists of will be set. The microcontroller automatically
reset them and the timer keeps on repeating counting from the beginning as far as the bit’s value is logic one
(1).
How to 'read' a timer ?

Depending on the timer’s application, it is needed to read a number in the timer registers or to register a
moment they have been reset.
- Everything is extremely simple when it is needed to read a value of the timer which uses only one register
for counting (mode 2 or Mode 3) . It is sufficient to read its state at any moment and it is it!
- It is a bit complicated to read a timer’s value when it operates in mode 2. Assuming that the state of the
lower byte is read first (TL0) and the state of the higher byte (TH0) afterwards, the result is:
TH0 = 15 TL0 = 255
Everything seems to be in order at first sight, but the current state of register at the moment of reading was:
TH0 = 14 TL0 = 255
In case of negligence, this error in counting ( 255 pulses ) may occur for not so obvious but quite logical
reason. Reading the lower byte is correct ( 255 ), but at the same time the program counter “ was taking “ a
new instruction for the TH0 state reading, an overflow occurred and both registers have changed their
contents ( TH0: 14→15, TL0: 255→0). The problem has simple solution: the state of the higher byte should
be read first, then the state of the lower byte and once again the state of the higher byte. If the number stored
in the higher byte is not the same both times it has been read then this sequence should be repeated ( this is a
mini- loop consisting of only 3 instructions in a program).
There is another solution too. It is sufficient to simply turn timer off while reading ( the bit TR0 in the
register TCON should be 0), and turn it on after that.
Detecting Timer 0 Overflow

Usually, there is no need to continuously read timer registers’ contents. It is sufficient to register the moment
they are reset, i.e. when counting starts from 0. It is called overflow. When this has occurred, the bit TF0
from the register TCON will be automatically set. The microcontroller is waiting for that moment in a way
that program will constantly check the state of this bit. Furthermore, an interrupt to stop the main program
execution can be enabled. Assuming that it is needed to provide a program pause ( time the program
appeared to be stopped) in duration of for example 0.05 seconds ( 50 000 machine cycles ):
First, it is needed to calculate a number that should be written to the timer registers:

This number should be written to the timer registers TH0 and TL0:

Once the timer is started it will continue counting from the written number. Program instruction checks if the
bit TF0 is set, which happens at the moment of overflow, i.e. after exactly 50.000 machine cycles and 0.05
seconds respectively.
How to measure pulses?
Suppose it is needed to measure the duration of an event, for example how long some device has been turned
on? Look at the picture of the timer and pay attention to the purpose of the bit GATE0 ( which resides in the
TMOD register ). If this bit is cleared then the state on the pin P3.2 does not affect the timer operating. If
GATE0 = 1 the timer will operate as far as the pin P3.2 has logic one (1) value. If this pin is supplied with
5V through some external switch at the moment the device is being turned on, the timer will measure
duration of its operating, which actually was the aim.
How to count up pulses?

This time, the answer lies in the register TCON, and bit C/T0 respectively. Similar to the previous example,
this bit brings into an external signal. If the bit is cleared everything occurs in the same way as in the
previous examples and the timer counts pulses from oscillator of defined frequency, i.e. measures the time
that went by. If the bit is set, the timer input is provided with pulses from the pin P3.4 (T0). Since these
pulses do not have some definite time or order, it is not possible to measure time by counting them. For that
reason, this timer is turned into the counter. The highest frequency that could be measured by such a counter
is 1/24 frequency of used quartz-crystal.
Timer 1

Referring to its characteristics, this timer is “ a twin brother “ to the Timer 0. This means that they have the
same purpose, their operating is controlled by the same registers TMOD and TCON and both of them can
operate in one of 4 different modes.
2.7 UART (Universal Asynchronous Receiver and Transmitter)
One of the features that makes this microcontroller so powerful is an integrated UART, better known as a
serial port. It is a duplex port, which means that it can transmit and receive data simultaneously. Without it,
serial data sending and receiving would be endlessly complicated part of the program where the pin state
continuously is being changed and checked according to strictly determined rhythm. Naturally, it does not
happen here because the UART resolves it in a very elegant manner. All the programmer needs to do is to
simply select serial port mode and baud rate. When the programmer is such configured, serial data sending is
done by writing to the register SBUF while data receiving is done by reading the same register. The
microcontroller takes care of all issues necessary for not making any error during data exchange.

Serial port should be configured prior to being used. That determines how many bits one serial “word”
contains, what the baud rate is and what the pulse source for synchronization is. All bits controlling this are
stored in the SFR Register SCON (Serial Control).
SCON Register (Serial Port Control Register)



SM0 - bit selects mode



SM1 - bit selects mode



SM2 - bit is used in case that several microcontrollers share the same interface. In normal circumstances this
bit must be cleared in order to enable connection to function normally.



REN - bit enables data receiving via serial communication and must be set in order to enable it.



TB8 - Since all registers in microcontroller are 8-bit registers, this bit solves the problem of sending the 9th bit
in modes 2 and 3. Simply, bits content is sent as the 9th bit.


RB8 - bit has the same purpose as the bit TB8 but this time on the receiver side. This means that on receiving
data in 9-bit format , the value of the last ( ninth) appears on its location.



TI - bit is automatically set at the moment the last bit of one byte is sent when the USART operates as a
transmitter. In that way processor “knows” that the line is available for sending a new byte. Bit must be clear
from within the program!



RI - bit is automatically set once one byte has been received. Everything functions in the similar way as in the
previous case but on the receive side. This is line a “doorbell” which announces that a byte has been received
via serial communication. It should be read quickly prior to a new data takes its place. This bit must also be
also cleared from within the program!

As seen, serial port mode is selected by combining the bits SM0 and SM2 :
SM0

SM1

Mode

Description

Baud Rate

0

0

0

8-bit Shift Register

1/12 the quartz frequency

0

1

1

8-bit UART

Determined by the timer 1

1

0

2

9-bit UART

1/32 the quartz frequency (1/64
the quartz frequency)

1

1

3

9-bit UART

Determined by the timer 1

In mode 0, the data are transferred through the RXD pin, while clock pulses appear on the TXD pin. The
bout rate is fixed at 1/12 the quartz oscillator frequency. On transmit, the least significant bit (LSB bit) is
being sent/received first. (received).
TRANSMIT - Data transmission in form of pulse train automatically starts on the pin RXD at the moment
the data has been written to the SBUF register.In fact, this process starts after any instruction being
performed on this register. Upon all 8 bits have been sent, the bit TI in the SCON register is automatically
set.
RECEIVE - Starts data receiving through the pin RXD once two necessary conditions are met: bit REN=1
and RI=0 (both bits reside in the SCON register). Upon 8 bits have been received, the bit RI (register SCON)
is automatically set, which indicates that one byte is received.

Since, there are no START and STOP bits or any other bit except data from the SBUF register, this mode is
mainly used on shorter distance where the noise level is minimal and where operating rate is important. A
typical example for this is I/O port extension by adding cheap IC circuit ( shift registers 74HC595, 74HC597
and similar).
Mode 1

In Mode1 10 bits are transmitted through TXD or received through RXD in the following manner: a START
bit (always 0), 8 data bits (LSB first) and a STOP bit (always 1) last. The START bit is not registered in this
pulse train. Its purpose is to start data receiving mechanism. On receive the STOP bit is automatically written
to the RB8 bit in the SCON register.
TRANSMIT - A sequence for data transmission via serial communication is automatically started upon the
data has been written to the SBUF register. End of 1 byte transmission is indicated by setting the TI bit in the
SCON register.

RECEIVE - Receiving starts as soon as the START bit (logic zero (0)) appears on the pin RXD. The
condition is that bit REN=1and bit RI=0. Both of them are stored in the SCON register. The RI bit is
automatically set upon receiving has been completed.

The Baud rate in this mode is determined by the timer 1 overflow time.
Mode 2

In mode 2, 11 bits are sent through TXD or received through RXD: a START bit (always 0), 8 data bits
(LSB first), additional 9th data bit and a STOP bit (always 1) last. On transmit, the 9th data bit is actually the
TB8 bit from the SCON register. This bit commonly has the purpose of parity bit. Upon transmission, the 9th
data bit is copied to the RB8 bit in the same register ( SCON).The baud rate is either 1/32 or 1/64 the quartz
oscillator frequency.
TRANSMIT - A sequence for data transmission via serial communication is automatically started upon the
data has been written to the SBUF register. End of 1 byte transmission is indicated by setting the TI bit in the
SCON register.

RECEIVE - Receiving starts as soon as the START bit (logic zero (0)) appears on the pin RXD. The
condition is that bit REN=1and bit RI=0. Both of them are stored in the SCON register. The RI bit is
automatically set upon receiving has been completed.

Mode 3

Mode 3 is the same as Mode 2 except the baud rate. In Mode 3 is variable and can be selected.

The parity bit is the bit P in the PSW register. The simplest way to check correctness of the received byte is
to add this parity bit to the transmit side as additional bit. Simply, immediately before transmit, the message
is stored in the accumulator and the bit P goes into the TB8 bit in order to be “a part of the message”. On the
receive side is the opposite : received byte is stored in the accumulator and the bit P is compared with the bit
RB8 ( additional bit in the message). If they are the same- everything is OK!
Baud Rate

Baud Rate is defined as a number of send/received bits per second. In case the UART is used, baud rate
depends on: selected mode, oscillator frequency and in some cases on the state of the bit SMOD stored in the
SCON register. All necessary formulas are specified in the table :
Baud Rate
Mode 0

Mode 1

Mode 2

Mode 3

BitSMOD

Fosc. / 12
1 Fosc.
16 12 (256TH1)
Fosc. / 32
Fosc. / 64
1 Fosc.
16 12 (256TH1)

BitSMOD

1
0
Timer 1 as a baud rate generator

Timer 1 is usually used as a baud rate generator because it is easy to adjust various baud rate by the means of
this timer. The whole procedure is simple:


First, Timer 1 overflow interrupt should be disabled



Timer T1 should be set in auto-reload mode



Depending on necessary baud rate, in order to obtain some of the standard values one of the numbers from the
table should be selected. That number should be written to the TH1 register. That's all.
Fosc. (MHz)

Baud Rate

Bit SMOD
11.0592

12

14.7456

150

40 h

30 h

00 h

300

A0 h

98 h

80 h

75 h

52 h

0

600

D0 h

CC h

C0 h

BB h

A9 h

0

1200

E8 h

E6 h

E0 h

DE h

D5 h

0

2400

F4 h

F3 h

F0 h

EF h

EA h

0

F3 h

EF h

EF h

4800
4800

FA h

F8 h

9600

FD h

16

20
0

1

FC h

9600
19200

F5 h

0
F5 h

FD h

0

1

FC h

1

38400

FE h

1

76800

FF h

1

Multiprocessor Communication

As described in the previous text, modes 2 and 3 enable the additional 9th data bit to be part of message. It
can be used for checking data via parity bit. Another useful application of this bit is in communication
between two microcontrollers, i.e. multiprocessor communication. This feature is enabled by setting the SM2
bit in the SCON register. The consequence is the following: when the STOP bit is ready, indicating end of
message, the serial port interrupt will be requested only in case the bit RB8 = 1 (the 9th bit).
The whole procedure will be performed as follows:
Suppose that there are several connected microcontrollers having to exchange data. That means that each of
them must have its address. The point is that each address sent via serial communication has the 9th bit set
(1), while data has it cleared (0). If the microcontroller A should send data to the microcontroller C then it at
will place first send address of C and the 9th bit set to 1. That will generate interrupt and all microcontrollers
will check whether they are called.
Of course, only one of them will recognize this address and immediately clear the bit SM2 in the SCON
register. All following data will be normally received by that microcontroller and ignored by other
microcontrollers.

2.8 8051 Microcontroller Interrupts
There are five interrupt sources for the 8051, which means that they can recognize 5 different event that can
interrupt regular program execution. Each interrupt can be enabled or disabled by setting bits in the IE
register. Also, as seen from the picture below the whole interrupt system can be disabled by clearing bit EA
from the same register.
Now, one detail should be explained which is not completely obvious but refers to external interrupts- INT0
and INT1. Namely, if the bits IT0 and IT1 stored in the TCON register are set, program interrupt will occur
on changing logic state from 1 to 0, (only at the moment). If these bits are cleared, the same signal will
generate interrupt request and it will be continuously executed as far as the pins are held low.
IE Register (Interrupt Enable)



EA - bit enables or disables all other interrupt sources (globally)
o
o



0 - (when cleared) any interrupt request is ignored (even if it is enabled)
1 - (when set to 1) enables all interrupts requests which are individually enabled

ES - bit enables or disables serial communication interrupt (UART)
o
o



0 - UART System can not generate interrupt
1 - UART System enables interrupt

ET1 - bit enables or disables Timer 1 interrupt
o
o



0 - Timer 1 can not generate interrupt
1 - Timer 1 enables interrupt

EX1 - bit enables or disables INT 0 pin external interrupt
o
o



0 - change of the pin INT0 logic state can not generate interrupt
1 - enables external interrupt at the moment of changing the pin INT0 state

ET0 - bit enables or disables timer 0 interrupt
o
o



0 - Timer 0 can not generate interrupt
1 - enables timer 0 interrupt

EX0 - bit enables or disables INT1 pin external interrupt
o

0 - change of the INT1 pin logic state can not cause interrupt

o

1 - enables external interrupt at the moment of changing the pin INT1 state

Interrupt Priorities

It is not possible to predict when an interrupt will be required. For that reason, if several interrupts are
enabled. It can easily occur that while one of them is in progress, another one is requested. In such situation,
there is a priority list making the microcontroller know whether to continue operating or meet a new interrupt
request.
The priority list cosists of 3 levels:
1. Reset! The apsolute master of the situation. If an request for Reset omits, everything is stopped and the
microcontroller starts operating from the beginning.
2. Interrupt priority 1 can be stopped by Reset only.
3. Interrupt priority 0 can be stopped by both Reset and interrupt priority 1.

Which one of these existing interrupt sources have higher and which one has lower priority is defined in the
IP Register ( Interrupt Priority Register). It is usually done at the beginning of the program. According to
that, there are several possibilities:


Once an interrupt service begins. It cannot be interrupted by another inter rupt at the same or lower priority
level, but only by a higher priority interrupt.



If two interrupt requests, at different priority levels, arrive at the same time then the higher priority interrupt is
serviced first.



If the both interrupt requests, at the same priority level, occur one after another , the one who came later has to
wait until routine being in progress ends.



If two interrupts of equal priority requests arrive at the same time then the interrupt to be serviced is selected
according to the following priority list :

1. External interrupt INT0
2. Timer 0 interrupt
3. External Interrupt INT1
4. Timer 1 interrupt
5. Serial Communication Interrupt
IP Register (Interrupt Priority)

The IP register bits specify the priority level of each interrupt (high or low priority).



PS - Serial Port Interrupt priority bit
o
o



Priority 0
Priority 1

PT1 - Timer 1 interrupt priority
o

Priority 0

o

Priority 1


PX1 - External Interrupt INT1 priority
o
o



Priority 0
Priority 1

PT0 - Timer 0 Interrupt Priority
o
o



Priority 0
Priority 1

PX0 - External Interrupt INT0 Priority
o

Priority 0

o

Priority 1

Handling Interrupt

Once some of interrupt requests arrives, everything occurs according to the following order:
1. Instruction in progress is ended
2. The address of the next instruction to execute is pushed on the stack
3. Depending on which interrupt is requested, one of 5 vectors (addresses) is written to the program counter in
accordance to the following table:
4.
Interrupt Source

Vector (address)

IE0

3h

TF0

Bh

TF1

1B h

RI, TI

23 h

All addresses are in hexadecimal format

5. The appropriate subroutines processing interrupts should be located at these addresses. Instead of
them, there are usually jump instructions indicating the location where the subroutines reside.
6. When interrupt routine is executed, the address of the next instruction to execute is poped from the stack to the
program counter and interrupted program continues operating from where it left off.

From the moment an interrupt is enabled, the microcontroller is on alert all the time. When interrupt request
arrives, the program execution is interrupted, electronics recognizes the cause and the program “jumps” to
the appropriate address (see the table above ). Usually, there is a jump instruction already prepared
subroutine prepared in advance. The subroutine is executed which exactly the aim- to do something when
something else has happened. After that, the program continues operating from where it left off…
Reset

Reset occurs when the RS pin is supplied with a positive pulse in duration of at least 2 machine cycles ( 24
clock cycles of crystal oscillator). After that, the microcontroller generates internal reset signal during which
all SFRs, excluding SBUF registers, Stack Pointer and ports are reset ( the state of the first two ports is
indefinite while FF value is being written to the ports configuring all pins as inputs). Depending on device
purpose and environment it is in, on power-on reset it is usually push button or circuit or both connected to
the RS pin. One of the most simple circuit providing secure reset at the moment of turning power on is
shown on the picture.

Everything functions rather simply: upon the power is on, electrical condenser is being charged for several
milliseconds through resistor connected to the ground and during this process the pin voltage supply is on.
When the condenser is charged, power supply voltage is stable and the pin keeps being connected to the
ground providing normal operating in that way. If later on, during the operation, manual reset button is
pushed, the condenser is being temporarily discharged and the microcontroller is being reset. Upon the
button release, the whole process is repeated…
Through the program- step by step...

The microcontrollers normally operate at very high speed. The use of 12 Mhz quartz crystal enables
1.000.000 instructions per second to be executed! In principle, there is no need for higher operating rate. In
case it is needed, it is easy to built-in crystal for high frequency. The problem comes up when it is necessary
to slow down. For example, when during testing in real operating environment, several instructions should be
executed step by step in order to check for logic state of I/O pins.
Interrupt system applied on the 8051 microcontrollers practically stops operating and enables instructions to
be executed one at a time by pushing button. Two interrupt features enable that:


Interrupt request is ignored if an interrupt of the same priority level is being in progress.




Upon interrupt routine has been executed, a new interrupt is not executed until at least one instruction from the
main program is executed.



In order to apply this in practice, the following steps should be done:
1. External interrupt sensitive to the signal level should be enabled (for example INT0).
2. Three following instructions should be entered into the program (start from address 03hex.):
What is going on? Once the pin P3.2 is set to “0” (for example, by pushing button), the microcontroller will
interrupt program execution jump to the address 03hex, will be executed a mini-interrupt routine consisting
of 3 instructions is located at that address.
The first instruction is being executed until the push button is pressed ( logic one (1) on the pin P3.2). The
second instruction is being executed until the push button is released. Immediately after that, the instruction
RETI is executed and processor continues executing the main program. After each executed instruction, the
interrupt INT0 is generated and the whole procedure is repeated ( push button is still pressed). Button Press =
One Instruction.

2.9 8051 Microcontroller Power Consumption Control
Conditionally said microcontroller is the most part of its “lifetime” is inactive for some external signal in
order to takes its role in a show. It can make a great problem in case batteries are used for power supply. In
extremely cases, the only solution is to put the whole electronics to sleep in order to reduce consumption to
the minimum. A typical example of this is remote TV controller: it can be out of use for months but when
used again it takes less than a second to send a command to TV receiver. While normally operating, the
AT89S53 uses current of approximately 25mA, which shows that it is not too sparing microcontroller.
Anyway, it doesn’t have to be always like this, it can easily switch the operation mode in order to reduce its
total consumption to approximately 40uA. Actually, there are two power-saving modes of operation: Idle and
Power Down.
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j
Embedded systems-and-robotics-by vivekanand goud j

Mais conteúdo relacionado

Mais procurados

bonino_thesis_final
bonino_thesis_finalbonino_thesis_final
bonino_thesis_final
Dario Bonino
 
Perl &lt;b>5 Tutorial&lt;/b>, First Edition
Perl &lt;b>5 Tutorial&lt;/b>, First EditionPerl &lt;b>5 Tutorial&lt;/b>, First Edition
Perl &lt;b>5 Tutorial&lt;/b>, First Edition
tutorialsruby
 
Lecture notes on hybrid systems
Lecture notes on hybrid systemsLecture notes on hybrid systems
Lecture notes on hybrid systems
AOERA
 

Mais procurados (20)

bonino_thesis_final
bonino_thesis_finalbonino_thesis_final
bonino_thesis_final
 
Math for programmers
Math for programmersMath for programmers
Math for programmers
 
Scikit learn 0.16.0 user guide
Scikit learn 0.16.0 user guideScikit learn 0.16.0 user guide
Scikit learn 0.16.0 user guide
 
Sg246776
Sg246776Sg246776
Sg246776
 
Ns doc
Ns docNs doc
Ns doc
 
Introduction to objectual philosophy
Introduction to objectual philosophyIntroduction to objectual philosophy
Introduction to objectual philosophy
 
Akka java
Akka javaAkka java
Akka java
 
Integrating wind and solar energy in india for a smart grid platform
Integrating wind and solar energy in india for a smart grid platformIntegrating wind and solar energy in india for a smart grid platform
Integrating wind and solar energy in india for a smart grid platform
 
10.1.1.652.4894
10.1.1.652.489410.1.1.652.4894
10.1.1.652.4894
 
I do like cfd vol 1 2ed_v2p2
I do like cfd vol 1 2ed_v2p2I do like cfd vol 1 2ed_v2p2
I do like cfd vol 1 2ed_v2p2
 
Dsa
DsaDsa
Dsa
 
Gcrypt
GcryptGcrypt
Gcrypt
 
Operating Systems (printouts)
Operating Systems (printouts)Operating Systems (printouts)
Operating Systems (printouts)
 
RF Management Applications Using ZigBee Networks
RF Management Applications Using ZigBee NetworksRF Management Applications Using ZigBee Networks
RF Management Applications Using ZigBee Networks
 
Perl &lt;b>5 Tutorial&lt;/b>, First Edition
Perl &lt;b>5 Tutorial&lt;/b>, First EditionPerl &lt;b>5 Tutorial&lt;/b>, First Edition
Perl &lt;b>5 Tutorial&lt;/b>, First Edition
 
Electrónica digital: Logicsim
Electrónica digital: LogicsimElectrónica digital: Logicsim
Electrónica digital: Logicsim
 
C++ For Quantitative Finance
C++ For Quantitative FinanceC++ For Quantitative Finance
C++ For Quantitative Finance
 
Final_report
Final_reportFinal_report
Final_report
 
R intro
R introR intro
R intro
 
Lecture notes on hybrid systems
Lecture notes on hybrid systemsLecture notes on hybrid systems
Lecture notes on hybrid systems
 

Semelhante a Embedded systems-and-robotics-by vivekanand goud j

Embeded microcontroler
Embeded microcontrolerEmbeded microcontroler
Embeded microcontroler
Yugo Sulistyo
 
BE Project Final Report on IVRS
BE Project Final Report on IVRSBE Project Final Report on IVRS
BE Project Final Report on IVRS
Abhishek Nadkarni
 
Report on e-Notice App (An Android Application)
Report on e-Notice App (An Android Application)Report on e-Notice App (An Android Application)
Report on e-Notice App (An Android Application)
Priyanka Kapoor
 
Cenet-- capability enabled networking: towards least-privileged networking
Cenet-- capability enabled networking: towards least-privileged networkingCenet-- capability enabled networking: towards least-privileged networking
Cenet-- capability enabled networking: towards least-privileged networking
Jithu Joseph
 

Semelhante a Embedded systems-and-robotics-by vivekanand goud j (20)

Final Report
Final ReportFinal Report
Final Report
 
Wireless m-bus-quick-start-guide
Wireless m-bus-quick-start-guideWireless m-bus-quick-start-guide
Wireless m-bus-quick-start-guide
 
Ns doc
Ns docNs doc
Ns doc
 
PowerElectronicsHandbookbyMuhammadH.Rashid.pdf
PowerElectronicsHandbookbyMuhammadH.Rashid.pdfPowerElectronicsHandbookbyMuhammadH.Rashid.pdf
PowerElectronicsHandbookbyMuhammadH.Rashid.pdf
 
Project report on Eye tracking interpretation system
Project report on Eye tracking interpretation systemProject report on Eye tracking interpretation system
Project report on Eye tracking interpretation system
 
Embeded microcontroler
Embeded microcontrolerEmbeded microcontroler
Embeded microcontroler
 
BE Project Final Report on IVRS
BE Project Final Report on IVRSBE Project Final Report on IVRS
BE Project Final Report on IVRS
 
Report on e-Notice App (An Android Application)
Report on e-Notice App (An Android Application)Report on e-Notice App (An Android Application)
Report on e-Notice App (An Android Application)
 
87793
8779387793
87793
 
Capturing Knowledge Of User Preferences With Recommender Systems
Capturing Knowledge Of User Preferences With Recommender SystemsCapturing Knowledge Of User Preferences With Recommender Systems
Capturing Knowledge Of User Preferences With Recommender Systems
 
Distributed Mobile Graphics
Distributed Mobile GraphicsDistributed Mobile Graphics
Distributed Mobile Graphics
 
LATENT FINGERPRINT MATCHING USING AUTOMATED FINGERPRINT IDENTIFICATION SYSTEM
LATENT FINGERPRINT MATCHING USING AUTOMATED FINGERPRINT IDENTIFICATION SYSTEMLATENT FINGERPRINT MATCHING USING AUTOMATED FINGERPRINT IDENTIFICATION SYSTEM
LATENT FINGERPRINT MATCHING USING AUTOMATED FINGERPRINT IDENTIFICATION SYSTEM
 
Cenet-- capability enabled networking: towards least-privileged networking
Cenet-- capability enabled networking: towards least-privileged networkingCenet-- capability enabled networking: towards least-privileged networking
Cenet-- capability enabled networking: towards least-privileged networking
 
eclipse.pdf
eclipse.pdfeclipse.pdf
eclipse.pdf
 
Milan_thesis.pdf
Milan_thesis.pdfMilan_thesis.pdf
Milan_thesis.pdf
 
OAuth with Restful Web Services
OAuth with Restful Web Services OAuth with Restful Web Services
OAuth with Restful Web Services
 
html-css-bootstrap-javascript-and-jquery
html-css-bootstrap-javascript-and-jqueryhtml-css-bootstrap-javascript-and-jquery
html-css-bootstrap-javascript-and-jquery
 
O reilly cisco ios access lists
O reilly   cisco ios access listsO reilly   cisco ios access lists
O reilly cisco ios access lists
 
Oreilly cisco ios access lists
Oreilly   cisco ios access listsOreilly   cisco ios access lists
Oreilly cisco ios access lists
 
Manual
ManualManual
Manual
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Último (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

Embedded systems-and-robotics-by vivekanand goud j

  • 1. 2013 Beginners Guide To Embedded Systems & Robotics Vivekanand goud j www.myembeddedrobotics.blogspot.in vivekanandgoud4@gmail.com
  • 2. Contribution mazidi Abhijeet Gupta Ankur Agrawal Tanmay Gangwani Acknowledgement Robocon Team, IIT Kanpur Robotics Club, IIT Kanpur Electronics Club, IIT Kanpur Centre for Mechatronics, IIT Kanpur 2|Page Designed by vivekanand goud j| my embedded robotics
  • 3. Contents Section A: Digital Electronics Chapter 1 Basics ....................................................................................... 8 1.1 What is a Digital system? .................................................................................................... 8 1.2 Assigning States .................................................................................................................. 8 1.3 Number Systems in digital electronics................................................................................ 8 1.4 Types of Digital Circuits....................................................................................................... 8 1.5 Clock: Building block of a sequential circuit ....................................................................... 9 1.6 Logic Gates: Building block of a combinatorial circuitry..................................................... 9 1.7 Practical Circuiting Elements ............................................................................................ 10 1.7.1 Resistor: .................................................................................................................... 10 1.7.2 Capacitor: .................................................................................................................. 10 1.7.3 Breadboard: .............................................................................................................. 11 1.7.4 Integrated Circuits (IC) .............................................................................................. 11 1.7.5 LED ............................................................................................................................ 12 Chapter 2 2.1 Some Integrated Circuits and Implementation ....................... 13 555 .................................................................................................................................... 13 2.1.1 Monostable mode..................................................................................................... 13 2.1.2 Astable mode ............................................................................................................ 14 2.2 4029 counter..................................................................................................................... 15 2.2.1 2.3 Pin Description .......................................................................................................... 15 7447: BCD to 7 segment display decoder ......................................................................... 16 2.3.1 Pin Description .......................................................................................................... 16 2.4 LDR (Light Dependent Resistor) ........................................................................................ 17 2.5 Operational Amplifier (Opamp) ........................................................................................ 17 2.5.1 2.6 Opamp as a comparator ........................................................................................... 18 7805 Voltage Regulator .................................................................................................... 18 3|Page Designed by vivekanand goud j| my embedded robotics
  • 4. Section B: Embedded Systems Chapter 3 Introduction to Microcontrollers ........................................... 20 3.1 Compiler / IDE (Integrated Development Environment) .................................................. 22 3.2 Programmer ...................................................................................................................... 22 Chapter 4 23 Code Vision AVR (CVAVR) ...................................................... 4.1 CHIP:.................................................................................................................................. 24 4.2 PORT: ................................................................................................................................ 25 Chapter 5 5.a Introduction to Atmega 16 Microcontroller ........................... 26 Introduction to Atmega 16 Microcontroller 5.1 Features ............................................................................................................................ 26 5.2 Pin Configuration .............................................................................................................. 26 5.3 Block Diagram ................................................................................................................... 27 5.4 Pin Descriptions ................................................................................................................ 28 5.5 Digital Input Output Port .................................................................................................. 29 5.6 Registers............................................................................................................................ 29 5.b Introduction to 8051 Microcontroller • 5.1 What is 8051 Standard? • 5.2 8051 Microcontroller's pins • 5.3 Input/Output Ports (I/O Ports) • 5.4 8051 Microcontroller Memory Organisation • 5.5 SFRs (Special Function Registers) • 5.6 Counters and Timers • 5.7 UART (Universal Asynchronous Receiver and Transmitter) • 5.8 8051 Microcontroller Interrupts 5.9 8051 Microcontroller Power Consumption Control Chapter 6 I/O Ports: ............................................................................... 30 6.1 DDRX (Data Direction Register) ........................................................................................ 30 6.2 31 PORTX (PORTX Data Register)........................................................................................... 6.2.1 Output Pin................................................................................................................. 31 6.2.2 Input Pin.................................................................................................................... 31 6.3 PINX (Data Read Register)................................................................................................. 32 4|Page Designed by vivekanand goud j| my embedded robotics
  • 5. Chapter 7 LCD Interfacing ...................................................................... 33 7.1 Circuit Connection ............................................................................................................ 33 7.2 Setting up in Microcontroller............................................................................................ 33 7.3 Printing Functions ............................................................................................................. 34 7.3.1 lcd_clear() ................................................................................................................. 34 7.3.2 lcd_gotoxy(x,y).......................................................................................................... 34 7.3.3 lcd_putchar(char c) ................................................................................................... 35 7.3.4 lcd_putsf(constant string)......................................................................................... 35 5|Page Designed by vivekanand goud j| my embedded robotics
  • 6. 7.3.5 lcd_puts(char arr) ..................................................................................................... 35 7.3.6 itoa(int val, char arr[])............................................................................................... 35 7.3.7 ftoa(float val, char decimal_places, char arr[])......................................................... 35 Chapter 8 UART Communication ............................................................ 36 8.1 UART: Theory of Operation .............................................................................................. 36 8.2 Serial Port of Computer .................................................................................................... 37 8.3 Setting up UART in microcontroller .................................................................................. 38 8.3.1 putchar() ................................................................................................................... 39 8.3.2 getchar().................................................................................................................... 39 8.3.3 putsf()........................................................................................................................ 39 8.4 Docklight ........................................................................................................................... 40 Chapter 9 Timers .................................................................................... 41 9.1 Basic Theory ...................................................................................................................... 41 9.2 Fast PWM Mode ............................................................................................................... 42 9.3 CTC Mode.......................................................................................................................... 43 Chapter 10 SPI: Serial Peripheral Interface ............................................. 44 10.1 Theory of Operation ..................................................................................................... 44 10.2 Setting up SPI in Microcontroller .................................................................................. 45 10.2.1 Master Microcontroller ........................................................................................ 45 10.2.2 Slave Microcontroller............................................................................................ 45 10.3 Data Functions .............................................................................................................. 45 10.3.1 Transmit Data........................................................................................................ 45 10.3.2 Receive Data ......................................................................................................... 45 Chapter 11 46 ADC: Analog to Digital Converter ......................................... 11.1 Theory of operation ...................................................................................................... 46 11.2 Setting up Microcontroller............................................................................................ 46 11.3 Function for getting ADC .............................................................................................. 47 Chapter 12 Interrupts............................................................................. 48 Example .................................................................................................................................. 48 6|Page Designed by vivekanand goud j| my embedded robotics
  • 7. 12.1 Polling ........................................................................................................................... 48 12.2 Hardware interrupt....................................................................................................... 48 12.3 Hardware Interrupt or polling?..................................................................................... 48 12.4 Setting up Hardware Interrupt in Microcontroller ....................................................... 49 12.5 Functions of Interrupt Service Routine......................................................................... 49 Section C: Robotics Chapter 13 13.1 Introduction to Autonomous Robots ................................... 51 Robot Chassis Designing ............................................................................................... 51 13.1.1 Robot with steering wheel:................................................................................... 51 13.1.2 Robot with differential drive: ............................................................................... 52 Chapter 14 Motor Driver ........................................................................ 54 14.1 H- Bridge: ...................................................................................................................... 54 14.2 55 Motor Driver ICs: L293/L293D and L298....................................................................... 14.2.1 Difference between L293 and L298: ..................................................................... 56 14.2.2 Speed Control: ...................................................................................................... 56 Chapter 15 Sensors ................................................................................ 57 15.1 Analog Sensor ............................................................................................................... 57 15.2 58 Digital IR Sensor - TSOP Sensor..................................................................................... 6|Page Designed by vivekanand goud j| my embedded robotics
  • 8. Section A Digital Electronics 7|Page Designed by vivekanand goud j| my embedded robotics
  • 9. Chapter 1 Basics 1.1 What is a Digital system? In most general terms, this system’s behavior is sufficiently explained by using only two of its states can be Voltage(more than x volts or less?),distance covered(more than 2.5 km or less?],truefalse or weight of an elephant(will my weighing machine withstand it?) ) Note that although in every case, the all the intermediate states ARE POSSIBLE AND DO EXIST, our point of interest are such that we don’t require their explicit description. In electronic systems we mostly deal with Voltage levels as digital entities. 1.2 Assigning States There is no specific fixed definition of logic levels in electronics. Most commonly used level designation is the one used in CMOS and TTL (transistor transistor logic) families: Logic high –> designated as ‘1’ Logic low –> designated as ‘0’ Where high and low are actually ‘higher’ and ‘lower’ with respect to a reference voltage level (ideally taken as 2.5V) GOOGLY: Why assign ‘0’and ‘1’ and not ‘a ‘and ‘b’, ’x’ and ‘y ,’cat ‘and ‘dog’? ANS: Computational ease! 1.3 Number Systems in digital electronics 1. Binary: Only ‘0’ and ‘1’. 2. Hexadecimal: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F 1.4 Types of Digital Circuits Combinatorial Circuits: In these circuits, the past states are immaterial and the output depends only upon the present state. Example logic gates Sequential circuits: In these circuits, the next state is completely determined by the past states. Hence these follow a predictable structure and essentially require a timing device. Ex. counters, flip flops. 8|Page Designed by vivekanand goud j| my embedded robotics
  • 10. 1.5 Clock: Building block of a sequential circuit A clock is simply alternate high and low states of voltage with time i.e. essentially a square wave. Important terms related to clock are its duty cycle and its frequency: Duty cycle: It is the ratio of T and T +T h h l 𝐷= 𝑇ℎ 𝑇𝑙+𝑇ℎ 1.6 Logic Gates: Building block of a combinatorial circuitry These are essentially combinatorial circuits used to implement logical Boolean operations like AND, NAND, OR, XOR and NOT. NOT and NAND are called universal gates as any other gate can be formed using either of them! Figure 1 9|Page Figure 2: Table of Logic Gates Designed by vivekanand goud j| my embedded robotics
  • 11. 1.7 Practical Circuiting Elements 1.7.1 Resistor: A color scheme is followed to give the specifications of a resistor. The table for color code is shown below: The 1st two bands specify the 2 digits of the resistor value whereas the 3rd band specifies the multiplier in terms of the power to which 10 is raised and multiplied to the 2 digits. The tolerance tells the possible % variation of the resistor value about the value indicated by bands. Figure 3: Table of Resistance 1.7.2 Capacitor: The 2 types of capacitors we frequently use in circuits are ceramic and electrolytic capacitors. While ceramic capacitors do not have a fixed polarity; electrolytic capacitors should be connected in their specified polarities only else they might blow off! This polarity is usually provided on the side of the capacitors ‘corresponding leg. Figure 5: Electrolytic cap with –ve polarity leg seen 10 | P a g e Figure 4: Ceramic cap with value 15x104 pF Designed by vivekanand goud j| my embedded robotics
  • 12. 1.7.3 Breadboard: This is the base used for setting up the circuit. This has embedded metal strips in it that form a grid of connections inside its body. This allows us to take multiple connections from a single point without any need of soldering/disordering as in PCBs. It is always a good habit to test the circuit on breadboard before making it on a PCB. Figure 6: Top view showing the connecting holes. Bottom view shows the contact metal strips 1.7.4 Integrated Circuits (IC) ICs or Integrated Circuits are packaged circuits designed for some fixed purpose. An IC has its fixed IC name/number that can be used to get catalog of its functions and pin configuration. ICs come in various sizes and packages depending upon the purpose. NOTE: Numbering scheme of IC pins will be explained in the lab session. Different ICs may have different number of pins. Figure 7: IC 11 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 13. 1.7.5 LED LED (Light Emitting Diode) is frequently used to display the outputs at various stages of the circuit. It is essentially a Diode with the energy released in the form of photons due to electron transitions falling in the visible region. Hence normal diode properties apply to it. It glows only in fwd bias mode i.e. with p junction connected to +ve voltage and n junction to negative. Diodes are essentially low power devices. The current through the LED should be less than 20mA.Hence always put a 220 ohm resistor in series with the LED. Never forget that LEDs consume a significant amount of power of the outputs of the ICs (CMOS based).Hence it is advisable to only use them for checking the voltage level (high or low) and then remove them. Figure 8: LEDs 12 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 14. Chapter 2 Some Integrated Circuits and Implementation 2.1 555 555 is an IC used to generate a clock .The two attributes of a clock are Frequency Duty cycle. Both of these can be changed using this IC, however the duty cycle is always <50%. There are two modes in which 555 can run. Figure 9: Pin Configuration of 555 2.1.1 Monostable mode As the name suggests; in this mode the output is stable in only one (mono) state i.e. ‘off’ state. Thus it can stay only for a finite time, if triggered, to the other state i.e. ‘on’ state. This time can be set choosing appropriate values of resistances in the formula: T = 1.1 x R1 x C1 Figure 10: 555 in monostable mode 13 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 15. 2.1.2 Astable mode In this mode; the output is stable neither in ‘high’ state nor in ‘low ’ state. Hence it oscillates from one state to another giving us a square wave or clock. We can set the clock frequency and Duty cycle D by the formulae: F= � .𝟒𝟒 𝑹� +� 𝑹� 𝑪� D= (𝑹� +𝑹� ) (𝑹� +� 𝑹� ) Figure 11: 555 in astable mode NOTE: Capacitor C2 is just to filter the noise and its value can be suitably chosen to be 0.01µF. It can also be neglected. 14 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 16. 2.2 4029 counter With the clock made, we are ready to count the number of pulses passed into the circuit. Note that any kind of counting requires a memory (you got to know that you have just counted ‘3’ to go to ‘4’!). Hence 4029 can also be used as a memory element that remembers its immediate previous state. Figure 12: 4029 pin configuration 2.2.1 Pin Description PIN No. 1 Name Parallel load 2 3 4 5 Output Bit 3 Parallel input bit 3 Parallel input bit 0 Clock enable bar 6 7 Output Bit 0 TC bar 8 9 Gnd Binary/Hex bar 10 Up/Down bar count 11 12 13 14 15 16 Output bit 1 Parallel input bit 1 Parallel input bit 2 Output bit 2 Clock pulse Vdd 15 | P a g e Pin function If given high; loads the value of Parallel bit into the o/p bits Most significant bit of o/p Most significant bit of parallel i/p Least significant bit of parallel i/p Low on this pin enables counting as per the clock received Least significant bit of parallel o/p Output bit that gives a low when the count is complete. Can be used to signal the end of counting. Needed for powering To choose b/w binary and hexadecimal modes To choose b/w up counting and down counting modes 2nd bit of o/p 2nd bit of i/p 3rd bit of i/p 3rd bit of o/p Clock pulse is given here Needed for powering Designed by vivekanand goud j| my embedded robotics Connection reqd. Gnd To pin 6 of 7447 Input Input Gnd To pin 7 of 7447 None if you don’t want to use it Gnd low for count 0-15 high for count 0-9 Low for down count High for up count To pin 1 of 7447 Input Input To pin 2 of 7447 Clock from 555 +5 V
  • 17. 2.3 7447: BCD to 7 segment display decoder For displaying the number in the counter output on a seven segment display (i.e. 7 LEDs making up a figure of ‘8’ as in a general calculator. See fig. ) we need to decode the 4 bits and match them to the 7 pins for lighting the LEDs corresponding to the number. This work is done by 7447. Figure 13: 7447 pin configuration 2.3.1 Pin Description PIN no. 1 2 3 4 5 6 7 8 9-15 16 Name Function 2nd bit(O1) of 4029’s o/p 3rd bit(O2) of 4029’s o/p Used to check that all LEDs of 7 seg are working. i/p B i/p C Lamp Test bar BI /RBI RBI i/p D i/p A Gnd a-g as per the fig Vcc Kept high to allow normal function Blanks ‘0’ from being displayed Most significant bit(O3) of 4029’s o/p 3rd bit(O2) of 4029’s o/p For power The o/p pins to 7segment display For power Connection reqd. To O1 of 4029 To O2 of 4029 High for normal fn Low to glow all LEDs Kept high Kept high To O2 of 4029 To O2 of 4029 Connected to gnd To 7 seg display Connected to +5 V NOTE: The COM pins are to be connected to Vcc via 220 ohm resistor. Why resistor is required?? The dot pin is just for display of decimal point and essentially only makes the upper and lower sides distinguishable from each other for a single display. without the asymmetry produced by dot how will we be able to see which side is upper and which is lower? 16 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 18. 2.4 LDR (Light Dependent Resistor) Light Dependent Resistor (LDR) or photo resistor is a device that acts like a resistance and its resistance varies with the intensity of light incident on it. In this device, if photons of sufficient energy fall on it, the resistance drops drastically as the electrons in the semiconductor are able to jump from the valence band to the conduction band and are available for conduction. The LDRs used are mostly responsive to visible light. The resistance might drop from as high as 1MΩ in the dark to 1 k Ω in bright light. Figure 14: LDRs. The coiled portion is responsive to light 2.5 Operational Amplifier (Opamp) Opamp is a very important device used in everyday electronics .It is essentially a differential amplifier with a very high gain of the order of 105!By differential amplifier I mean that it amplifies the difference of 2 signals and gives the output. Opamp equation: Vout= A (V+ - V- ) where A is the gain of the order 105. Ironically, this high gain in open loop makes it impossible to use it as a general purpose differential amplifier directly. GOOGLY: If (V+-V-) = 0.005V; Vss = 12V what will be the output?? 17 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 19. 2.5.1 Opamp as a comparator Simplest use of Opamp is as a comparator. It can be used to convert an analog signal to a digital signal defined by a fixed threshold. Set V- as the threshold voltage say 2.5 V and apply the analog signal to be digitized at V+ .What will be the output? Well if you have worked out the googly; this should be a piece of cake! 2.6 7805 Voltage Regulator 7805 voltage regulator is used to get +5 V output out of a higher voltage supply (7.5V-20V).We use adapter’s supply to generate +5V here. Connect the gnd and +12V of adapter to the pins as shown and get +5V directly as an output out of the 3rd pin. Current up to 0.5 A can be obtained from this regulator without any significant fall in voltage level. NOTE: Use 2 capacitors of value say 0.1µF to filter the noise in the input and output of regulator’s supply as shown. 18 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 20. Section B Embedded Systems 19 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 21. Chapter 3 Introduction to Microcontrollers You must be knowing about Digital Integrated Circuits (ICs) right ? For example: 7404: Hex Inverter 7408: Quad 2-input AND gate 7410: Triple 3-input NAND Gate 7432: Quad 2-input OR Gate 7457: 60:1 Frequency divider There are AND, XOR, NAND, NOR, OR logic gate ICs, Counters, Timers, Seven Segment Display Drivers and much more. Just check out 7400 Series and 4000 Series of Integrated Circuits. Now let’s take Quad 2 input AND gate IC. It has 4 AND gates, each having 2 pins for input and 1 pin for output. The truth table or the function table of each gate is fixed. This is as follows, Input 1 Input 2 Output 0 0 0 0 1 0 1 0 0 1 1 1 Similarly all the Integrated circuits have their function tables and input and output pins fixed. You cannot change the function and no input pin act as output and vice versa. So whenever you want to design some circuit you first have to get the output as a function of inputs and then design it using gates or whatever the requirement is. So once a circuit is built we cannot change its function ! Even if you want to make some changes again you have to consider all the gates and components involved. Now if you are designing any circuit which involves change of the function table every now and then you are in trouble ! For example if I want to design an Autonomous Robot which should perform various tasks and I don’t just want to fix the task. Suppose I make it to move in a path then I want to change the path ! How to do that ? Here comes the use of Microcontrollers ! Now if I give you an Integrated Circuit with 20 pins and tell you that you can make any pin as output or input also you can change the function table by programming the IC using your computer ! Then your reactions will be wow ! that’s nice :-) That’s what the most basic function of a microcontroller is. It has set of pins called as PORT and you can make any pin either as output or input. After configuring pins you can program it to perform according to any function table you want. You can change the configuration or the function table as many times you wants. There are many Semiconductor Companies which manufactures microcontrollers. Some of them are: Intel Atmel Microchip Motorola 20 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 22. We will discuss about Atmel Microcontrollers commonly known as AVR in this section. Question: How a microcontroller works ! Answer: Well I cannot go into lot of details about the working because it is a vast topic in itself. I can just give an overview. Microcontroller consists of an Microprocessor (CPU that is Central processing Unit) which is interfaced to RAM (Random Access Memory) and Flash Memory (one your pen drive has !). You feed your program in the Flash Memory on the microcontroller. Now when you turn on the microcontroller, CPU accesses the instruction from RAM which access your code from Flash. It sets the configuration of pins and start performing according to your program. Question: How to make the code ? Answer: You basically write the program on your computer in any of the high level languages like C, C++, JAVA etc. Then you compile the code to generate the machine file. Now you will ask what this machine file is ? All the machines understand only one language, 0 & 1 that is on and off. Now this 0 & 1 both corresponds to 2 different voltage levels for example 0 volt for 0 logic and +5 volt for 1 logic. Actually the code has to be written in this 0, 1 language and then saved in the memory of the microcontroller. But this will be very difficult for us ! So we write the code in the language we understand (C) and then compile and make the machine file (.hex). After we make this machine file we feed this to the memory of the microcontroller. Question: How to feed the code in the flash of Microcontroller ? Answer: Assuming you have the machine file (.hex) ready and now you want to feed that to the flash of the microcontroller. Basically you want to make communication between your computer and microcontroller. Now computer has many communication ports such as Serial Port, Parallel Port and USB (Universal Serial Bus). Lets take Serial Port, it has its own definition that is voltage level to define 0 & 1 (yeah all the data communication is a just collection of 0 & 1 ) Serial Port's protocol is called as UART (Universal Asynchronous Receiver & Transmitter) Its voltage levels are :-12 volt for 0 logic and +12 volt for 1 logic. Now the voltage levels of our microcontroller are based on CMOS (Complementary Metal Oxide Semiconductor) technology which has 0 volt for 0 logic and +5 volt for 1 logic. Two different machines with 2 different ways to define 0 & 1 and we want to exchange information between them. Consider microcontroller as a French and Computer's Serial Port as an Indian person (obviously no common language in between !) If they want to exchange information they basically need a mediator who knows both the language. He will listen one person and then translate to other person. Similarly we need a circuit which converts CMOS (microcontroller) to UART (serial port) and vice versa. This circuit is called as programmer. Using this circuit we can connect computer to the microcontroller and feed the machine file to the flash. 21 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 23. 3.1 Compiler / IDE (Integrated Development Environment) Atmel Microcontrollers are very famous as they are very easy to use. There are many development tools available for them. First of all we need an easy IDE for developing code. I suggest beginners to use CVAVR (Code Vision AVR) Evaluation version is available for free download from the website. It has limitation of code size. It works on computers with Windows platform that is Windows XP & Vista. Some famous compilers/development tools supporting Windows for Atmel Microcontrollers are: WINAVR (AVRGCC for Windows) Code Vision AVR (CVAVR) AVR Studio (Atmel's free developing tool) AVRGCC is a very nice open source compiler used by most of the people. 3.2 Programmer Programmer basically consists of two parts: Software (to open .hex file on your computer) Hardware (to connect microcontroller) Hardware depends on the communication port you are using on the computer (Serial, Parallel or USB). I suggest beginners to use Serial Programmer as it is very easy to build. Software for that is Pony Prog. Some famous Windows (XP, Vista) programmers are: Pony Prog (Serial, Parallel) AVRdude (supports many hardwares) AVRStudio (supports Atmel's hardware) ATProg (Serial) USB-ASP (USB) 22 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 24. Chapter 4 Code Vision AVR (CVAVR) An IDE has following functions: Preprocessing Compilation Assembly Linking Object Translation Text Editor If we just use compiler and linker independently we still need to get a text editor. So combining everything will actually mess things up. So the best way is to get Software which has it all. That’s called an Integrated Development Environment, in short IDE. I consider Code-Vision-AVR to be the best IDE for getting started with AVR programming on Windows XP, Vista. It has a very good Code Wizard which generate codes automatically ! You need not mess with the assembly words. So in all my tutorials I will be using CVAVR. You can download evaluation version for free which has code size limitation but good enough for our purpose. For all my examples I will be using Atmega-16 as default microcontroller because it very easily available and is powerful enough with sufficient number of pins and peripherals we use. You can have a look on the datasheet of Atmega-16 in the datasheet section. Let’s take a look on the software. The main window looks like following, 23 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 25. Now click on File ---> New --->Project A pop up window will come asking whether you want to use Code Wizard AVR, obviously select yes because that is the reason we are using CVAVR ! Now have a look on this Wizard. It has many tabs where we can configure PORTS, TIMERS, LCD, ADC etc. I am explaining some of them 4.1 CHIP: Select the chip for which you are going to write the program. Then select the frequency at which Chip is running. By default all chips are set on Internal Oscillator of 1 MHz so select 1 MHz if that is the case. If you want to change the running clock frequency of the chip then you have to change its fuse bits (I will talk more about this in fuse bits section). 24 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 26. 4.2 PORT: PORT is usually a collection of 8 pins. From this tab you can select which pin you want to configure as output and which as input. It basically writes the DDR and PORT register through this setting. Registers are basically RAM locations which configure various peripherals of microcontroller and by changing value of these registers we can change the function it is performing. I will talk more about registers later. All the details are provided in the datasheet. So you can configure any pin as output or input by clicking the box. For Atmega-16 which has 4 Ports we can see 4 tabs each corresponding to one Port. You can also set initial value of the Pins you want to assign. or if you are using a pin as input then whether you want to make it as pull-up or tristated, again I will talk in details about these functions later. Similarly using this code wizard you can very easily configure all the peripherals on the Atmega. Now for generating code just go to File ----> Generate, Save and Exit (of the code wizard) Now it will ask you name and location for saving three files. Two being project files and one being the .C file which is your program. try to keep same names of all three files to avoid confusion. By default these files are generated in C:CVAVRbin The generated program will open in the text editor. Have a look it has some declarations like PORT, DDR, TCCR0 and many more. These are all registers which configures various functions of Atmega and by changing these value we make different functions. All the details about the registers are commented just below them. Now go down and find following infinite while loop there. We can start writing our part of program just before the while loop. And as for most of the applications we want microcontroller to perform the same task forever we put our part of code in the infinite while loop provided by the code wizard ! while { // Place your code here (1) }; } See how friendly this code wizard is, all the work (configuring registers) automatically done and we don’t even need to understand and go to the details about registers too ! Now we want to generate the hex file, so first compile the program. Either press F9 or go to Project ---> Compile. It will show compilation errors if any. If program is error free we can proceed to making of hex file. So either press Shift+F9 or go to Project ----> Make. A pop up window will come with information about code size and flash usage etc. So the machine file is ready now ! It is in the same folder where we saved those 3 files. 25 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 27. Chapter 5 Introduction to Atmega 16 Microcontroller 5.1 Features Advanced RISC Architecture Up to 16 MIPS Throughput at 16 MHz 16K Bytes of In-System Self-Programmable Flash 512 Bytes EEPROM 1K Byte Internal SRAM 32 Programmable I/O Lines In-System Programming by On-chip Boot Program 8-channel, 10-bit ADC Two 8-bit Timer/Counters with Separate Prescalers and Compare Modes One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Four PWM Channels Programmable Serial USART Master/Slave SPI Serial Interface Byte-oriented Two-wire Serial Interface Programmable Watchdog Timer with Separate On-chip Oscillator External and Internal Interrupt Sources 5.2 Pin Configuration 26 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 28. 5.3 Block Diagram 27 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 29. 5.4 Pin Descriptions VCC: Digital supply voltage. (+5V) GND: Ground. (0 V) Note there are 2 ground Pins. Port A (PA7 - PA0) Port A serves as the analog inputs to the A/D Converter. Port A also serves as an 8-bit bidirectional I/O port, if the A/D Converter is not used. When pins PA0 to PA7 are used as inputs and are externally pulled low, they will source current if the internal pull-up resistors are activated. The Port A pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port B (PB7 - PB0) Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). Port B also serves the functions of various special features of the ATmega16 as listed on page 58 of datasheet. Port C (PC7 - PC0) Port C is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). Port C also serves the functions of the JTAG interface and other special features of the ATmega16 as listed on page 61 of datasheet. If the JTAG interface is enabled, the pull-up resistors on pins PC5(TDI), PC3(TMS) and PC2(TCK) will be activated even if a reset occurs. Port D (PD7 - PD0) Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). Port D also serves the functions of various special features of the ATmega16 as listed on page 63 of datasheet. RESET: Reset Input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not running. XTAL1: External oscillator pin 1 XTAL2: External oscillator pin 2 AVCC: AVCC is the supply voltage pin for Port A and the A/D Converter. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. AREF: AREF is the analog reference pin for the A/D Converter. 28 | P a g e Designed by vivekanand goud j| my embedded robotics
  • 30. 5.5 Digital Input Output Port So let’s start with understanding the functioning of AVR. We will first discuss about I/O Ports. Again I remind you that I will be using and writing about Atmega-16. Let’s first have a look at the Pin configuration of Atmega-16. Image is attached, click to enlarge. You can see it has 32 I/O (Input/Output) pins grouped as A, B, C & D with 8 pins in each group. This group is called as PORT. PA0 - PA7 (PORTA) PB0 - PB7 (PORTB) PC0 - PC7 (PORTC) PD0 - PD7 (PORTD) Notice that all these pins have some function written in bracket. These are additional function that pin can perform other than I/O. Some of them are. ADC (ADC0 - ADC7 on PORTA) UART (Rx,Tx on PORTD) TIMERS (OC0 - OC2) SPI (MISO, MOSI, SCK on PORTB) External Interrupts (INT0 - INT2) 5.6 Registers All the configurations in microcontroller is set through 8 bit (1 byte) locations in RAM (RAM is a bank of memory bytes) of the microcontroller called as Registers. All the functions are mapped to its locations in RAM and the value we set at that location that is at that Register configures the functioning of microcontroller. There are total 32 x 8bit registers in Atmega-16. As Register size of this microcontroller is 8 bit, it called as 8 bit microcontroller. 5. B 8051 Microcontroller Architecture  5.1 What is 8051 Standard?  5.2 8051 Microcontroller's pins  5.3 Input/Output Ports (I/O Ports)  5.4 8051 Microcontroller Memory Organisation  5.5 SFRs (Special Function Registers)  5.6 Counters and Timers  5.7 UART (Universal Asynchronous Receiver and Transmitter)  5.8 8051 Microcontroller Interrupts  5.9 8051 Microcontroller Power Consumption Control
  • 31. 2.1 What is 8051 Standard? Microcontrollers’ producers have been struggling for a long time for attracting more and more choosy customers. Every couple of days a new chip with a higher operating frequency, more memory and more high-quality A/D converters comes on the market. Nevertheless, by analyzing their structure it is concluded that most of them have the same (or at least very similar) architecture known in the product catalogs as “8051 compatible”. What is all this about? The whole story began in the far 80s when Intel launched its series of the microcontrollers labelled with MCS 051. Although, several circuits belonging to this series had quite modest features in comparison to the new ones, they took over the world very fast and became a standard for what nowadays is ment by a word microcontroller. The reason for success and such a big popularity is a skillfully chosen configuration which satisfies needs of a great number of the users allowing at the same time stable expanding ( refers to the new types of the microcontrollers ). Besides, since a great deal of software has been developed in the meantime, it simply was not profitable to change anything in the microcontroller’s basic core. That is the reason for having a great number of various microcontrollers which actually are solely upgraded versions of the 8051 family. What is it what makes this microcontroller so special and universal so that almost all the world producers manufacture it today under different name ? As shown on the previous picture, the 8051 microcontroller has nothing impressive at first sight:  4 Kb program memory is not much at all.  128Kb RAM (including SFRs as well) satisfies basic needs, but it is not imposing amount.  4 ports having in total of 32 input/output lines are mostly enough to make connection to peripheral environment and are not luxury at all. As it is shown on the previous picture, the 8051 microcontroller have nothing impressive at first sight: The whole configuration is obviously envisaged as such to satisfy the needs of most programmers who work on development of automation devices. One of advantages of this microcontroller is that nothing is missing and nothing is too much. In other words, it is created exactly in accordance to the average user‘s taste and needs. The other advantage is the way RAM is organized, the way Central Processor Unit (CPU) operates and ports which maximally use all recourses and enable further upgrading. 2.2 8051 Microcontroller's pins Pins 1-8: Port 1 Each of these pins can be configured as input or output.
  • 32. Pin 9: RS Logical one on this pin stops microcontroller’s operating and erases the contents of most registers. By applying logical zero to this pin, the program starts execution from the beginning. In other words, a positive voltage pulse on this pin resets the microcontroller. Pins10-17: Port 3 Similar to port 1, each of these pins can serve as universal input or output . Besides, all of them have alternative functions: Pin 10: RXD Serial asynchronous communication input or Serial synchronous communication output. Pin 11: TXD Serial asynchronous communication output or Serial synchronous communication clock output. Pin 12: INT0 Interrupt 0 input Pin 13: INT1 Interrupt 1 input Pin 14: T0 Counter 0 clock input Pin 15: T1 Counter 1 clock input Pin 16: WR Signal for writing to external (additional) RAM Pin 17: RD Signal for reading from external RAM Pin 18, 19: X2, X1 Internal oscillator input and output. A quartz crystal which determines operating frequency is usually connected to these pins. Instead of quartz crystal, the miniature ceramics resonators can be also used for frequency stabilization. Later versions of the microcontrollers operate at a frequency of 0 Hz up to over 50 Hz. Pin 20: GND Ground Pin 21-28: Port 2 If there is no intention to use external memory then these port pins are configured as universal inputs/outputs. In case external memory is used then the higher address byte, i.e. addresses A8-A15 will appear on this port. It is important to know that even memory with capacity of 64Kb is not used ( i.e. note all bits on port are used for memory addressing) the rest of bits are not available as inputs or outputs. Pin 29: PSEN If external ROM is used for storing program then it has a logic-0 value every time the microcontroller reads a byte from memory. Pin 30: ALE Prior to each reading from external memory, the microcontroller will set the lower address byte (A0-A7) on P0 and immediately after that activates the output ALE. Upon receiving signal from the ALE pin, the external register (74HCT373 or 74HCT375 circuit is usually embedded ) memorizes the state of P0 and uses it as an address for memory chip. In the second part of the microcontroller’s machine cycle, a signal on this pin stops being emitted and P0 is used now for data transmission (Data Bus). In this way, by means of only one additional (and cheap) integrated circuit, data multiplexing from the port is performed. This port at the same time used for data and address transmission. Pin 31: EA By applying logic zero to this pin, P2 and P3 are used for data and address transmission with no regard to whether there is internal memory or not. That means that even there is a program written to the microcontroller, it will not be executed, the program written to external ROM will be used instead. Otherwise, by applying logic one to the EA pin, the microcontroller will use both memories, first internal and afterwards external (if it exists), up to end of address space. Pin 32-39: Port 0 Similar to port 2, if external memory is not used, these pins can be used as universal inputs or outputs. Otherwise, P0 is configured as address output (A0-A7) when the ALE pin is at high level (1) and as data output (Data Bus), when logic zero (0) is applied to the ALE pin. Pin 40: VCC Power supply +5V 2.3 Input/Output Ports (I/O Ports)
  • 33. All 8051 microcontrollers have 4 I/O ports, each consisting of 8 bits which can be configured as inputs or outputs. This means that the user has on disposal in total of 32 input/output lines connecting the microcontroller to peripheral devices. A logic state on a pin determines whether it is configured as input or output: 0=output, 1=input. If a pin on the microcontroller needs to be configured as output, then a logic zero (0) should be applied to the appropriate bit on I/O port. In this way, a voltage level on the appropriate pin will be 0. Similar to that, if a pin needs to be configured as input, then a logic one (1) should be applied to the appropriate port. In this way, as a side effect a voltage level on the appropriate pin will be 5V (as it is case with any TTL input). This may sound a bit confusing but everything becomes clear after studying a simplified electronic circuit connected to one I/O pin.
  • 34. Input/Output (I/O) pin This is a simplified overview of what is connected to a pin inside the microcontroller. It concerns all pins except those included in P0 which do not have embedded pullup resistor. Output pin A logic zero (0) is applied to a bit in the P register. By turning output FE transistor on, the appropriate pin is directly connected to ground. Input pin A logic one (1) is applied to a bit in the P register. Output FE transistor is turned off. The appropriate pin remains connected to voltage power supply through a pull-up resistor of high resistance. A logic state (voltage) on any pin can be changed or read at any moment. A logic zero (0) and logic one (1) are not equal. A logic one (0) represents almost short circuit to ground. Such a pin is configured as output. A logic one (1) is “loosely” connected to voltage power supply through resistors of high resistance. Since this voltage can be easily “pulled down” by an external signal, such a pin is configured as input. Port 0
  • 35. It is specific to this port to have a double purpose. If external memory is used then the lower address byte (addresses A0-A7) is applied on it. Otherwise, all bits on this port are configured as inputs or outputs. Another characteristic is expressed when it is configured as output. Namely, unlike other ports consisting of pins with embedded pull-up resistor ( connected by its end to 5 V power supply ), this resistor is left out here. This, apparently little change has its consequences: If any pin on this port is configured as input then it performs as if it “floats”. Such input has unlimited input resistance and has no voltage coming from “inside”. When the pin is configured as output, it performs as “open drain”, meaning that by writing 0 to some port’s bit, the appropriate pin will be connected to ground (0V). By writing 1, the external output will keep on “floating”. In order to apply 1 (5V) on this output, an external pull-up resistor must be embedded. Only in case P0 is used for addressing external memory ( only in that case), the microcontroller will provide internal power supply source in order to establish logical ones on pins. There is no need to add external pullup resistors. Port 1 This is a true I/O port, because there are no role assigning as it is the case with P0. Since it has embedded pull-up resistors it is completely compatible with TTL circuits. Port 2 Similar to P0, when using external memory, lines on this port occupy addresses intended for external memory chip. This time it is the higher address byte with addresses A8-A15. When there is no additional memory, this port can be used as universal input-output port similar by its features to the port 1. Port 3 Even though all pins on this port can be used as universal I/O port, they also have an alternative function. Since each of these functions use inputs, then the appropriate pins have to be configured like that. In other words, prior to using some of reserve port functions, a logical one (1) must be written to the appropriate bit in the P3 register. From hardware’s perspective , this port is also similar to P0, with the difference that its outputs have a pull-up resistor embedded.
  • 36. Current limitations on pins When configured as outputs ( logic zero (0) ), single port pins can "receive" current of 10mA. If all 8 bits on a port are active, total current must be limited to 15mA (port P0: 26mA). If all ports (32 bits) are active, total maximal current must be limited to 71mA. When configured as inputs (logic 1), embedded pull-up resistor provides very weak current, but strong enough to activate up to 4 TTL inputs from LS series. It may be seen from description of some ports, that even though all pins have more or less similar internal structure, it is necessary to pay attention to which of them will be used for what and how. For example: If they are used as outputs with high voltage level (5V), then port 0 should be avoided because its pins do not have added resistor for connection to +5V. Only low logic level can be obtained therefore, if another port is used for the same purpose, one should have in mind that pull-up resistors have a relatively high resistance. Consequentaly it can be counted on only several hundreds microamperes of current coming out of a pin. 2.4 8051 Microcontroller Memory Organisation The microcontroller memory is divided into Program Memory and Data Memory. Program Memory (ROM) is used for permanent saving program being executed, while Data Memory (RAM) is used for temporarily storing and keeping intermediate results and variables. Depending on the model in use ( still referring to the whole 8051 microcontroller family) at most a few Kb of ROM and 128 or 256 bytes of RAM can be used. However… All 8051 microcontrollers have 16-bit addressing bus and can address 64 kb memory. It is neither a mistake nor a big ambition of engineers who were working on basic core development. It is a matter of very clever memory organization which makes these controllers a real “ programmers’ tidbit“ . Program Memory The oldest models of the 8051 microcontroller family did not have internal program memory . It was added from outside as a separate chip. These models are recognizable by their label beginning with 803 ( for ex. 8031 or 8032). All later models have a few Kbytes ROM embedded, Even though it is enough for writing most of the programs, there are situations when additional memory is necessary. A typical example of it is the use of so called lookup tables. They are used in cases when something is too complicated or when there is no time for solving equations describing some process. The example of it can be totally exotic (an estimate of self-guided rockets’ meeting point) or totally common( measuring of temperature using non-linear thermo element or asynchronous motor speed control). In those cases all needed estimates and approximates are executed in advance and the final results are put in the tables ( similar to logarithmic tables ). How does the microcontroller handle external memory depends on the pin EA logic state:
  • 37. EA=0 In this case, internal program memory is completely ignored, only a program stored in external memory is to be executed. EA=1 In this case, a program from builtin ROM is to be executed first ( to the last location). Afterwards, the execution is continued by reading additional memory. in both cases, P0 and P2 are not available to the user because they are used for data nd address transmission. Besides, the pins ALE and PSEN are used too. Data Memory As already mentioned, Data Memory is used for temporarily storing and keeping data and intermediate results created and used during microcontroller’s operating. Besides, this microcontroller family includes many other registers such as: hardware counters and timers, input/output ports, serial data buffers etc. The previous versions have the total memory size of 256 locations, while for later models this number is incremented by additional 128 available registers. In both cases, these first 256 memory locations (addresses 0-FFh) are the base of the memory. Common to all types of the 8051 microcontrollers. Locations available to the user occupy memory space with addresses from 0 to 7Fh. First 128 registers and this part of RAM is divided in several blocks. The first block consists of 4 banks each including 8 registers designated as R0 to R7. Prior to access them, a bank containing that register must be selected. Next memory block ( in the range of 20h to 2Fh) is bitaddressable, which means that each bit being there has its own address from 0 to 7Fh. Since there are 16 such registers, this block contains in total of 128 bits with separate addresses (The 0th bit of the 20h byte has the bit address 0 and the 7th bit of th 2Fh byte has the bit address 7Fh). The third group of registers occupy addresses 2Fh-7Fh ( in total of 80 locations) and does not have any special purpose or feature. Additional Memory Block of Data Memory
  • 38. In order to satisfy the programmers’ permanent hunger for Data Memory, producers have embedded an additional memory block of 128 locations into the latest versions of the 8051 microcontrollers. Naturally, it’s not so simple…The problem is that electronics performing addressing has 1 byte (8 bits) on disposal and due to that it can reach only the first 256 locations. In order to keep already existing 8-bit architecture and compatibility with other existing models a little trick has been used. Using trick in this case means that additional memory block shares the same addresses with existing locations intended for the SFRs (80h- FFh). In order to differentiate between these two physically separated memory spaces, different ways of addressing are used. A direct addressing is used for all locations in the SFRs, while the locations from additional RAM are accessible using indirect addressing.
  • 39. How to extend memory? In case on-chip memory is not enough, it is possible to add two external memory chips with capacity of 64Kb each. I/O ports P2 and P3 are used for their addressing and data transmission.
  • 40. From the users’ perspective, everything functions quite simple if properly connected because the most operations are performed by the microcontroller itself. The 8051 microcontroller has two separate reading signals RD#(P3.7) and PSEN#. The first one is activated byte from external data memory (RAM) should be read, while another one is activated to read byte from external program memory (ROM). These both signals are active at logical zero (0) level. A typical example of such memory extension using special chips for RAM and ROM, is shown on the previous picture. It is called Hardward architecture. Even though the additional memory is rarely used with the latest versions of the microcontrollers, it will be described here in short what happens when memory chips are connected according to the previous schematic. It is important to know that the whole process is performed automatically, i.e. with no intervention in the program.  When the program during execution encounters the instruction which resides in exter nal memory (ROM), the microcontroller will activate its control output ALE and set the first 8 bits of address (A0-A7) on P0. In this way, IC circuit 74HCT573 which "lets in" the first 8 bits to memory address pins is activated.  A signal on the pin ALE closes the IC circuit 74HCT573 and immediately afterwards 8 higher bits of address (A8-A15) appear on the port. In this way, a desired location in addtional program memory is completely addressed. The only thing left over is to read its content.  Pins on P0 are configured as inputs, the pin PSEN is activated and the microcon troller reads content from memory chip. The same connections are used both for data and lower address byte.
  • 41. Similar occurs when it is a needed to read some location from external Data Memory. Now, addressing is performed in the same way, while reading or writing is performed via signals which appear on the control outputs RD or WR . Addressing While operating, processor processes data according to the program instructions. Each instruction consists of two parts. One part describes what should be done and another part indicates what to use to do it. This later part can be data (binary number) or address where the data is stored. All 8051 microcontrollers use two ways of addressing depending on which part of memory should be accessed: Direct Addressing On direct addressing, a value is obtained from a memory location while the address of that location is specified in instruction. Only after that, the instruction can process data (howdepends on the type of instruction: addition, subtraction, copy…). Obviously, a number being changed during operating a variable can reside at that specified address. For example: Since the address is only one byte in size ( the greatest number is 255), this is how only the first 255 locations in RAM can be accessed in this case the first half of the basic RAM is intended to be used freely, while another half is reserved for the SFRs. MOV A,33h; Means: move a number from address 33 hex. to accumulator Indirect Addressing On indirect addressing, a register which contains address of another register is specified in the instruction. A value used in operating process resides in that another register. For example: Only RAM locations available for use are accessed by indirect addressing (never in the SFRs). For all latest versions of the microcontrollers with additional memory block ( those 128 locations in Data Memory), this is the only way of accessing them. Simply, when during operating, the instruction including “@” sign is encountered and if the specified address is higher than 128 ( 7F hex.), the processor knows that indirect addressing is used and jumps over memory space reserved for the SFRs. MOV A,@R0; Means: Store the value from the register whose address is in the R0 register into accumulator On indirect addressing, the registers R0, R1 or Stack Pointer are used for specifying 8-bit addresses. Since only 8 bits are avilable, it is possible to access only registers of internal RAM in this way (128 locations in former or 256 locations in latest versions of the microcontrollers). If memory extension in form of additional memory chip is used then the 16-bit DPTR Register (consisting of the registers DPTRL and DPTRH) is used for specifying addresses. In this way it is possible to access any location in the range of 64K. 2.5 SFRs (Special Function Registers) SFRs are a kind of control table used for running and monitoring microcontroller’s operating. Each of these registers, even each bit they include, has its name, address in the scope of RAM and clearly defined purpose ( for example: timer control, interrupt, serial connection etc.). Even though there are 128 free memory locations intended for their storage, the basic core, shared by all types of 8051 controllers, has only 21 such registers. Rest of locations are intensionally left free in order to enable the producers to further improved models keeping at the same time compatibility with the previous versions. It also enables the use of programs written a long time ago for the microcontrollers which are out of production now.
  • 42. A Register (Accumulator) This is a general-purpose register which serves for storing intermediate results during operating. A number (an operand) should be added to the accumulator prior to execute an instruction upon it. Once an arithmetical operation is preformed by the ALU, the result is placed into the accumulator. If a data should be transferred from one register to another, it must go through accumulator. For such universal purpose, this is the most commonly used register that none microcontroller can be imagined without (more than a half 8051 microcontroller's instructions used use the accumulator in some way). B Register B register is used during multiply and divide operations which can be performed only upon numbers stored in the A and B registers. All other instructions in the program can use this register as a spare accumulator (A). During programming, each of registers is called by name so that their exact address is not so important for the user. During compiling into machine code (series of hexadecimal numbers recognized as instructions by the microcontroller), PC will automatically, instead of registers’ name, write necessary addresses into the microcontroller. R Registers (R0-R7)
  • 43. This is a common name for the total 8 generalpurpose registers (R0, R1, R2 ...R7). Even they are not true SFRs, they deserve to be discussed here because of their purpose. The bank is active when the R registers it includes are in use. Similar to the accumulator, they are used for temporary storing variables and intermediate results. Which of the banks will be active depends on two bits included in the PSW Register. These registers are stored in four banks in the scope of RAM. The following example best illustrates the useful purpose of these registers. Suppose that mathematical operations on numbers previously stored in the R registers should be performed: (R1+R2) - (R3+R4). Obviously, a register for temporary storing results of addition is needed. Everything is quite simple and the program is as follows : MOV A,R3; Means: move number from R3 into accumulator ADD A,R4; Means: add number from R4 to accumulator (result remains in accumulator) MOV R5,A; Means: temporarily move the result from accumulator into R5 MOV A,R1; Means: move number from R1 into accumulator ADD A,R2; Means: add number from R2 to accumulator SUBB A,R5; Means: subtract number from R5 ( there are R3+R4 ) PSW Register (Program Status Word) This is one of the most important SFRs. The Program Status Word (PSW) contains several status bits that reflect the current state of the CPU. This register contains: Carry bit, Auxiliary Carry, two register bank select bits, Overflow flag, parity bit, and user-definable status flag. The ALU automatically changes some of register’s bits, which is usually used in regulation of the program performing. P - Parity bit. If a number in accumulator is even then this bit will be automatically set (1), otherwise it will be cleared (0). It is mainly used during data transmission and receiving via serial communication. - Bit 1. This bit is intended for the future versions of the microcontrollers, so it is not supposed to be here. OV Overflow occurs when the result of arithmetical operation is greater than 255 (deci mal), so that it can not be stored in one register. In that case, this bit will be set (1). If there is no overflow, this bit will be cleared (0). RS0, RS1 - Register bank select bits. These two bits are used to select one of the four register banks in RAM. By writing zeroes and ones to these bits, a group of registers R0-R7 is stored in one of four banks in RAM.
  • 44. RS1 RS2 Space in RAM 0 0 Bank0 00h-07h 0 1 Bank1 08h-0Fh 1 0 Bank2 10h-17h 1 1 Bank3 18h-1Fh F0 - Flag 0. This is a general-purpose bit available to the user. AC - Auxiliary Carry Flag is used for BCD operations only. CY - Carry Flag is the (ninth) auxiliary bit used for all arithmetical operations and shift instructions. DPTR Register (Data Pointer) These registers are not true ones because they do not physically exist. They consist of two separate registers: DPH (Data Pointer High) and (Data Pointer Low). Their 16 bits are used for external memory addressing. They may be handled as a 16-bit register or as two independet 8-bit registers.Besides, the DPTR Register is usually used for storing data and intermediate results which have nothing to do with memory locations. SP Register (Stack Pointer) A value of the Stack Pointer ensures that the Stack Pointer will point to valid RAM and permits Stack availability. By starting each subprogram, the value in the Stack Pointer is incremented by 1. In the same manner, by ending subprogram, this value is decremented by 1. After any reset, the value 7 is written to the Stack Pointer, which means that the space of RAM reserved for the Stack starts from this location. If another value is written to this register then the entire Stack is moved to a new location in the memory.
  • 45. P0, P1, P2, P3 - Input/Output Registers In case that external memory and serial communication system are not in use then, 4 ports with in total of 32 input-output lines are available to the user for connection to peripheral environment. Each bit inside these ports coresponds to the appropriate pin on the microcontroller. This means that logic state written to these ports appears as a voltage on the pin ( 0 or 5 V). Naturally, while reading, the opposite occurs – voltage on some input pins is reflected in the appropriate port bit. The state of a port bit, besides being reflected in the pin, determines at the same time whether it will be configured as input or output. If a bit is cleared (0), the pin will be configured as output. In the same manner, if a bit is set to 1 the pin will be configured as input. After reset, as well as when turning the microcontroller on , all bits on these ports are set to one (1). This means that the appropriate pins will be configured as inputs. Conditionally said, I/O ports are directly connected to the microcontroller’s pins. This means that a logic state of these registers can be checked by voltmeter and vice versa-voltage on the pins can be checked by testing their bits! 2.6 Counters and Timers As explained in the previous chapter, the main oscillator of the microcontroller uses quartz crystal for its operating. As the frequency of this oscillator is precisely defined and very stable, these pulses are the most suitable for time measuring (such oscillators are used in quartz clocks as well). In order to measure time between two events it is only needed to count up pulses from this oscillator. That is exactly what the timer is doing. Namely, if the timer is properly programmed, the value written to the timer register will be incremented or decremented after each coming pulse, i.e. once per each machine cycle cycle. Taking into account that one instruction lasts 12 quartz oscillator periods (one machine cycle), by embedding quartz with oscillator frequency of 12MHz, a number in the timer register will be changed million times per second, i.e. each microsecond. The 8051 microcontrollers have 2 timer counters called T0 and T1. As their names tell, their main purpose is to measure time and count external events. Besides, they can be used for generating clock pulses used in serial communication, i.e. Baud Rate. Timer T0 As it is shown in the picture below, this timer consists of two registers – TH0 and TL0. The numbers these registers include represent a lower and a higher byte of one 16-digit binary number.
  • 46. This means that if the content of the timer 0 is equal to 0 (T0=0) then both registers it includes will include 0. If the same timer contains for example number 1000 (decimal) then the register TH0 (higher byte) will contain number 3, while TL0 (lower byte) will contain decimal number 232. Formula used to calculate values in registers is very simple: TH0 × 256 + TL0 = T Matching the previous example it would be as follows : 3 × 256 + 232 = 1000 Since the timers are virtually 16-bit registers, the greatest value that could be written to them is 65 535. In case of exceeding this value, the timer will be automatically reset and afterwords that counting starts from 0. It is called overflow. Two registers TMOD and TCON are closely connected to this timer and control how it operates. TMOD Register (Timer Mode) This register selects mode of the timers T0 and T1. As illustrated in the following picture, the lower 4 bits (bit0 - bit3) refer to the timer 0, while the higher 4 bits (bit4 - bit7) refer to the timer 1. There are in total of 4 modes and each of them is described here in this book. Bits of this register have the following purpose:  GATE1 starts and stops Timer 1 by means of a signal provided to the pin INT1 (P3.3): o o  1 - Timer 1 operates only if the bit INT1 is set 0 - Timer 1 operates regardless of the state of the bit INT 1 C/T1 selects which pulses are to be counted up by the timer/counter 1: o o  1 - Timer counts pulses provided to the pin T1 (P3.5) 0 - Timer counts pulses from internal oscillator T1M1,T1M0 These two bits selects the Timer 1 operating mode.
  • 47. T1M1 T1M0 Mode Description 0 0 0 13-bit timer 0 1 1 16-bit timer 1 0 2 8-bit autoreload 1 1 3 Split mode  GATE0 starts and stops Timer 1, using a signal provided to the pin INT0 (P3.2): o o  1 - Timer 0 operates only if the bit INT0 is set 0 - Timer 0 operates regardless of the state of the bit INT0 C/T0 selects which pulses are to be counted up by the timer/counter 0: o o  1 - Timer counts pulses provided to the pin T0(P3.4) 0 - Timer counts pulses from internal oscillator T0M1,T0M0 These two bits select the Timer 0 operating mode. T0M1 T0M0 Mode Description 0 0 0 13-bit timer 0 1 1 16-bit timer 1 0 2 8-bit autoreload 1 1 3 Split mode Timer 0 in mode 0 (13-bit timer) This is one of the rarities being kept only for compatibility with the previuos versions of the microcontrollers. When using this mode, the higher byte TH0 and only the first 5 bits of the lower byte TL0 are in use. Being configured in this way, the Timer 0 uses only 13 of all 16 bits. How does it operate? With each new pulse coming, the state of the lower register (that one with 5 bits) is changed. After 32 pulses received it becomes full and automatically is reset, while the higher byte TH0 is incremented by 1. This action will be repeated until registers count up 8192 pulses. After that, both registers are reset and counting starts from 0.
  • 48. Timer 0 in mode 1 (16-bit timer) All bits from the registers TH0 and TL0 are used in this mode. That is why for this mode is being more commonly used. Counting is performed in the same way as in mode 0, with difference that the timer counts up to 65 536, i.e. as far as the use of 16 bits allows. Timer 0 in mode 2 (Auto-Reload Timer) What does auto-reload mean? Simply, it means that such timer uses only one 8-bit register for counting, but it never counts from 0 but from an arbitrary chosen value (0- 255) saved in another register. The advantages of this way of counting are described in the following example: suppose that for any reason it is continuously needed to count up 55 pulses at a time from the clock generator.
  • 49. When using mode 1 or mode 0, It is needed to write number 200 to the timer registers and check constantly afterwards whether overflow occured, i.e. whether the value 255 is reached by counting . When it has occurred, it is needed to rewrite number 200 and repeat the whole procedure. The microcontroller performs the same procedure in mode 2 automatically. Namely, in this mode it is only register TL0 operating as a timer ( normally 8-bit), while the value from which counting should start is saved in the TH0 register. Referring to the previous example, in order to register each 55th pulse, it is needed to write the number 200 to the register and configure the timer to operate in mode 2. Timer 0 in Mode 3 (Split Timer) By configuring Timer 0 to operate in Mode 3, the 16-bit counter consisting of two registers TH0 and TL0 is split into two independent 8-bit timers. In addition, all control bits which belonged to the initial Timer 1 (consisting of the registers TH1 and TL1), now control newly created Timer 1. This means that even though the initial Timer 1 still can be configured to operate in any mode ( mode 1, 2 or 3 ), it is no longer able to stop, simply because there is no bit to do that. Therefore, in this mode, it will uninterruptedly “operate in the background “.
  • 50. The only application of this mode is in case two independent 'quick' timers are used and the initial Timer 1 whose operating is out of control is used as baud rate generator. TCON - Timer Control Register This is also one of the registers whose bits directly control timer operating. Only 4 of all 8 bits this register has are used for timer control, while others are used for interrupt control which will be discussed later.  TF1 This bit is automatically set with the Timer 1 overflow  TR1 This bit turns the Timer 1 on o 1 - Timer 1 is turned on o 0 - Timer 1 is turned off  TF0 This bit is automatically set with the Timer 0 overflow.  TR0 This bit turns the timer 0 on o 1 - Timer 0 is turned on o 0 - Timer 0 is turned off How to start Timer 0 ? Normally, first this timer and afterwards its mode should be selected. Bits which control that are resided in the register TMOD:
  • 51. This means that timer 0 operates in mode 1 and counts pulses from internal source whose frequency is equal to 1/12 the quartz frequency. In order to enable the timer, turn it on: Immediately upon the bit TR0 is set, the timer starts operating. Assuming that a quartz crystal with frequency of 12MHz is embedded, a number it contains will be incremented every microsecond. By counting up to 65.536 microseconds, the both registers that timer consists of will be set. The microcontroller automatically reset them and the timer keeps on repeating counting from the beginning as far as the bit’s value is logic one (1). How to 'read' a timer ? Depending on the timer’s application, it is needed to read a number in the timer registers or to register a moment they have been reset. - Everything is extremely simple when it is needed to read a value of the timer which uses only one register for counting (mode 2 or Mode 3) . It is sufficient to read its state at any moment and it is it! - It is a bit complicated to read a timer’s value when it operates in mode 2. Assuming that the state of the lower byte is read first (TL0) and the state of the higher byte (TH0) afterwards, the result is: TH0 = 15 TL0 = 255
  • 52. Everything seems to be in order at first sight, but the current state of register at the moment of reading was: TH0 = 14 TL0 = 255 In case of negligence, this error in counting ( 255 pulses ) may occur for not so obvious but quite logical reason. Reading the lower byte is correct ( 255 ), but at the same time the program counter “ was taking “ a new instruction for the TH0 state reading, an overflow occurred and both registers have changed their contents ( TH0: 14→15, TL0: 255→0). The problem has simple solution: the state of the higher byte should be read first, then the state of the lower byte and once again the state of the higher byte. If the number stored in the higher byte is not the same both times it has been read then this sequence should be repeated ( this is a mini- loop consisting of only 3 instructions in a program). There is another solution too. It is sufficient to simply turn timer off while reading ( the bit TR0 in the register TCON should be 0), and turn it on after that. Detecting Timer 0 Overflow Usually, there is no need to continuously read timer registers’ contents. It is sufficient to register the moment they are reset, i.e. when counting starts from 0. It is called overflow. When this has occurred, the bit TF0 from the register TCON will be automatically set. The microcontroller is waiting for that moment in a way that program will constantly check the state of this bit. Furthermore, an interrupt to stop the main program execution can be enabled. Assuming that it is needed to provide a program pause ( time the program appeared to be stopped) in duration of for example 0.05 seconds ( 50 000 machine cycles ): First, it is needed to calculate a number that should be written to the timer registers: This number should be written to the timer registers TH0 and TL0: Once the timer is started it will continue counting from the written number. Program instruction checks if the bit TF0 is set, which happens at the moment of overflow, i.e. after exactly 50.000 machine cycles and 0.05 seconds respectively. How to measure pulses?
  • 53. Suppose it is needed to measure the duration of an event, for example how long some device has been turned on? Look at the picture of the timer and pay attention to the purpose of the bit GATE0 ( which resides in the TMOD register ). If this bit is cleared then the state on the pin P3.2 does not affect the timer operating. If GATE0 = 1 the timer will operate as far as the pin P3.2 has logic one (1) value. If this pin is supplied with 5V through some external switch at the moment the device is being turned on, the timer will measure duration of its operating, which actually was the aim. How to count up pulses? This time, the answer lies in the register TCON, and bit C/T0 respectively. Similar to the previous example, this bit brings into an external signal. If the bit is cleared everything occurs in the same way as in the previous examples and the timer counts pulses from oscillator of defined frequency, i.e. measures the time that went by. If the bit is set, the timer input is provided with pulses from the pin P3.4 (T0). Since these pulses do not have some definite time or order, it is not possible to measure time by counting them. For that reason, this timer is turned into the counter. The highest frequency that could be measured by such a counter is 1/24 frequency of used quartz-crystal. Timer 1 Referring to its characteristics, this timer is “ a twin brother “ to the Timer 0. This means that they have the same purpose, their operating is controlled by the same registers TMOD and TCON and both of them can operate in one of 4 different modes.
  • 54. 2.7 UART (Universal Asynchronous Receiver and Transmitter) One of the features that makes this microcontroller so powerful is an integrated UART, better known as a serial port. It is a duplex port, which means that it can transmit and receive data simultaneously. Without it, serial data sending and receiving would be endlessly complicated part of the program where the pin state continuously is being changed and checked according to strictly determined rhythm. Naturally, it does not happen here because the UART resolves it in a very elegant manner. All the programmer needs to do is to simply select serial port mode and baud rate. When the programmer is such configured, serial data sending is done by writing to the register SBUF while data receiving is done by reading the same register. The microcontroller takes care of all issues necessary for not making any error during data exchange. Serial port should be configured prior to being used. That determines how many bits one serial “word” contains, what the baud rate is and what the pulse source for synchronization is. All bits controlling this are stored in the SFR Register SCON (Serial Control). SCON Register (Serial Port Control Register)  SM0 - bit selects mode  SM1 - bit selects mode  SM2 - bit is used in case that several microcontrollers share the same interface. In normal circumstances this bit must be cleared in order to enable connection to function normally.  REN - bit enables data receiving via serial communication and must be set in order to enable it.  TB8 - Since all registers in microcontroller are 8-bit registers, this bit solves the problem of sending the 9th bit in modes 2 and 3. Simply, bits content is sent as the 9th bit.
  • 55.  RB8 - bit has the same purpose as the bit TB8 but this time on the receiver side. This means that on receiving data in 9-bit format , the value of the last ( ninth) appears on its location.  TI - bit is automatically set at the moment the last bit of one byte is sent when the USART operates as a transmitter. In that way processor “knows” that the line is available for sending a new byte. Bit must be clear from within the program!  RI - bit is automatically set once one byte has been received. Everything functions in the similar way as in the previous case but on the receive side. This is line a “doorbell” which announces that a byte has been received via serial communication. It should be read quickly prior to a new data takes its place. This bit must also be also cleared from within the program! As seen, serial port mode is selected by combining the bits SM0 and SM2 : SM0 SM1 Mode Description Baud Rate 0 0 0 8-bit Shift Register 1/12 the quartz frequency 0 1 1 8-bit UART Determined by the timer 1 1 0 2 9-bit UART 1/32 the quartz frequency (1/64 the quartz frequency) 1 1 3 9-bit UART Determined by the timer 1 In mode 0, the data are transferred through the RXD pin, while clock pulses appear on the TXD pin. The bout rate is fixed at 1/12 the quartz oscillator frequency. On transmit, the least significant bit (LSB bit) is being sent/received first. (received). TRANSMIT - Data transmission in form of pulse train automatically starts on the pin RXD at the moment the data has been written to the SBUF register.In fact, this process starts after any instruction being performed on this register. Upon all 8 bits have been sent, the bit TI in the SCON register is automatically set.
  • 56. RECEIVE - Starts data receiving through the pin RXD once two necessary conditions are met: bit REN=1 and RI=0 (both bits reside in the SCON register). Upon 8 bits have been received, the bit RI (register SCON) is automatically set, which indicates that one byte is received. Since, there are no START and STOP bits or any other bit except data from the SBUF register, this mode is mainly used on shorter distance where the noise level is minimal and where operating rate is important. A typical example for this is I/O port extension by adding cheap IC circuit ( shift registers 74HC595, 74HC597 and similar). Mode 1 In Mode1 10 bits are transmitted through TXD or received through RXD in the following manner: a START bit (always 0), 8 data bits (LSB first) and a STOP bit (always 1) last. The START bit is not registered in this pulse train. Its purpose is to start data receiving mechanism. On receive the STOP bit is automatically written to the RB8 bit in the SCON register.
  • 57. TRANSMIT - A sequence for data transmission via serial communication is automatically started upon the data has been written to the SBUF register. End of 1 byte transmission is indicated by setting the TI bit in the SCON register. RECEIVE - Receiving starts as soon as the START bit (logic zero (0)) appears on the pin RXD. The condition is that bit REN=1and bit RI=0. Both of them are stored in the SCON register. The RI bit is automatically set upon receiving has been completed. The Baud rate in this mode is determined by the timer 1 overflow time. Mode 2 In mode 2, 11 bits are sent through TXD or received through RXD: a START bit (always 0), 8 data bits (LSB first), additional 9th data bit and a STOP bit (always 1) last. On transmit, the 9th data bit is actually the TB8 bit from the SCON register. This bit commonly has the purpose of parity bit. Upon transmission, the 9th data bit is copied to the RB8 bit in the same register ( SCON).The baud rate is either 1/32 or 1/64 the quartz oscillator frequency.
  • 58. TRANSMIT - A sequence for data transmission via serial communication is automatically started upon the data has been written to the SBUF register. End of 1 byte transmission is indicated by setting the TI bit in the SCON register. RECEIVE - Receiving starts as soon as the START bit (logic zero (0)) appears on the pin RXD. The condition is that bit REN=1and bit RI=0. Both of them are stored in the SCON register. The RI bit is automatically set upon receiving has been completed. Mode 3 Mode 3 is the same as Mode 2 except the baud rate. In Mode 3 is variable and can be selected. The parity bit is the bit P in the PSW register. The simplest way to check correctness of the received byte is to add this parity bit to the transmit side as additional bit. Simply, immediately before transmit, the message is stored in the accumulator and the bit P goes into the TB8 bit in order to be “a part of the message”. On the receive side is the opposite : received byte is stored in the accumulator and the bit P is compared with the bit RB8 ( additional bit in the message). If they are the same- everything is OK! Baud Rate Baud Rate is defined as a number of send/received bits per second. In case the UART is used, baud rate depends on: selected mode, oscillator frequency and in some cases on the state of the bit SMOD stored in the SCON register. All necessary formulas are specified in the table : Baud Rate Mode 0 Mode 1 Mode 2 Mode 3 BitSMOD Fosc. / 12 1 Fosc. 16 12 (256TH1) Fosc. / 32 Fosc. / 64 1 Fosc. 16 12 (256TH1) BitSMOD 1 0
  • 59. Timer 1 as a baud rate generator Timer 1 is usually used as a baud rate generator because it is easy to adjust various baud rate by the means of this timer. The whole procedure is simple:  First, Timer 1 overflow interrupt should be disabled  Timer T1 should be set in auto-reload mode  Depending on necessary baud rate, in order to obtain some of the standard values one of the numbers from the table should be selected. That number should be written to the TH1 register. That's all. Fosc. (MHz) Baud Rate Bit SMOD 11.0592 12 14.7456 150 40 h 30 h 00 h 300 A0 h 98 h 80 h 75 h 52 h 0 600 D0 h CC h C0 h BB h A9 h 0 1200 E8 h E6 h E0 h DE h D5 h 0 2400 F4 h F3 h F0 h EF h EA h 0 F3 h EF h EF h 4800 4800 FA h F8 h 9600 FD h 16 20 0 1 FC h 9600 19200 F5 h 0 F5 h FD h 0 1 FC h 1 38400 FE h 1 76800 FF h 1 Multiprocessor Communication As described in the previous text, modes 2 and 3 enable the additional 9th data bit to be part of message. It can be used for checking data via parity bit. Another useful application of this bit is in communication between two microcontrollers, i.e. multiprocessor communication. This feature is enabled by setting the SM2 bit in the SCON register. The consequence is the following: when the STOP bit is ready, indicating end of message, the serial port interrupt will be requested only in case the bit RB8 = 1 (the 9th bit). The whole procedure will be performed as follows: Suppose that there are several connected microcontrollers having to exchange data. That means that each of them must have its address. The point is that each address sent via serial communication has the 9th bit set (1), while data has it cleared (0). If the microcontroller A should send data to the microcontroller C then it at will place first send address of C and the 9th bit set to 1. That will generate interrupt and all microcontrollers will check whether they are called.
  • 60. Of course, only one of them will recognize this address and immediately clear the bit SM2 in the SCON register. All following data will be normally received by that microcontroller and ignored by other microcontrollers. 2.8 8051 Microcontroller Interrupts There are five interrupt sources for the 8051, which means that they can recognize 5 different event that can interrupt regular program execution. Each interrupt can be enabled or disabled by setting bits in the IE register. Also, as seen from the picture below the whole interrupt system can be disabled by clearing bit EA from the same register. Now, one detail should be explained which is not completely obvious but refers to external interrupts- INT0 and INT1. Namely, if the bits IT0 and IT1 stored in the TCON register are set, program interrupt will occur on changing logic state from 1 to 0, (only at the moment). If these bits are cleared, the same signal will generate interrupt request and it will be continuously executed as far as the pins are held low.
  • 61. IE Register (Interrupt Enable)  EA - bit enables or disables all other interrupt sources (globally) o o  0 - (when cleared) any interrupt request is ignored (even if it is enabled) 1 - (when set to 1) enables all interrupts requests which are individually enabled ES - bit enables or disables serial communication interrupt (UART) o o  0 - UART System can not generate interrupt 1 - UART System enables interrupt ET1 - bit enables or disables Timer 1 interrupt o o  0 - Timer 1 can not generate interrupt 1 - Timer 1 enables interrupt EX1 - bit enables or disables INT 0 pin external interrupt o o  0 - change of the pin INT0 logic state can not generate interrupt 1 - enables external interrupt at the moment of changing the pin INT0 state ET0 - bit enables or disables timer 0 interrupt o o  0 - Timer 0 can not generate interrupt 1 - enables timer 0 interrupt EX0 - bit enables or disables INT1 pin external interrupt
  • 62. o 0 - change of the INT1 pin logic state can not cause interrupt o 1 - enables external interrupt at the moment of changing the pin INT1 state Interrupt Priorities It is not possible to predict when an interrupt will be required. For that reason, if several interrupts are enabled. It can easily occur that while one of them is in progress, another one is requested. In such situation, there is a priority list making the microcontroller know whether to continue operating or meet a new interrupt request. The priority list cosists of 3 levels: 1. Reset! The apsolute master of the situation. If an request for Reset omits, everything is stopped and the microcontroller starts operating from the beginning. 2. Interrupt priority 1 can be stopped by Reset only. 3. Interrupt priority 0 can be stopped by both Reset and interrupt priority 1. Which one of these existing interrupt sources have higher and which one has lower priority is defined in the IP Register ( Interrupt Priority Register). It is usually done at the beginning of the program. According to that, there are several possibilities:  Once an interrupt service begins. It cannot be interrupted by another inter rupt at the same or lower priority level, but only by a higher priority interrupt.  If two interrupt requests, at different priority levels, arrive at the same time then the higher priority interrupt is serviced first.  If the both interrupt requests, at the same priority level, occur one after another , the one who came later has to wait until routine being in progress ends.  If two interrupts of equal priority requests arrive at the same time then the interrupt to be serviced is selected according to the following priority list : 1. External interrupt INT0 2. Timer 0 interrupt 3. External Interrupt INT1 4. Timer 1 interrupt 5. Serial Communication Interrupt IP Register (Interrupt Priority) The IP register bits specify the priority level of each interrupt (high or low priority).  PS - Serial Port Interrupt priority bit o o  Priority 0 Priority 1 PT1 - Timer 1 interrupt priority o Priority 0 o Priority 1
  • 63.  PX1 - External Interrupt INT1 priority o o  Priority 0 Priority 1 PT0 - Timer 0 Interrupt Priority o o  Priority 0 Priority 1 PX0 - External Interrupt INT0 Priority o Priority 0 o Priority 1 Handling Interrupt Once some of interrupt requests arrives, everything occurs according to the following order: 1. Instruction in progress is ended 2. The address of the next instruction to execute is pushed on the stack 3. Depending on which interrupt is requested, one of 5 vectors (addresses) is written to the program counter in accordance to the following table: 4. Interrupt Source Vector (address) IE0 3h TF0 Bh TF1 1B h RI, TI 23 h All addresses are in hexadecimal format 5. The appropriate subroutines processing interrupts should be located at these addresses. Instead of them, there are usually jump instructions indicating the location where the subroutines reside. 6. When interrupt routine is executed, the address of the next instruction to execute is poped from the stack to the program counter and interrupted program continues operating from where it left off. From the moment an interrupt is enabled, the microcontroller is on alert all the time. When interrupt request arrives, the program execution is interrupted, electronics recognizes the cause and the program “jumps” to the appropriate address (see the table above ). Usually, there is a jump instruction already prepared subroutine prepared in advance. The subroutine is executed which exactly the aim- to do something when something else has happened. After that, the program continues operating from where it left off… Reset Reset occurs when the RS pin is supplied with a positive pulse in duration of at least 2 machine cycles ( 24 clock cycles of crystal oscillator). After that, the microcontroller generates internal reset signal during which all SFRs, excluding SBUF registers, Stack Pointer and ports are reset ( the state of the first two ports is indefinite while FF value is being written to the ports configuring all pins as inputs). Depending on device
  • 64. purpose and environment it is in, on power-on reset it is usually push button or circuit or both connected to the RS pin. One of the most simple circuit providing secure reset at the moment of turning power on is shown on the picture. Everything functions rather simply: upon the power is on, electrical condenser is being charged for several milliseconds through resistor connected to the ground and during this process the pin voltage supply is on. When the condenser is charged, power supply voltage is stable and the pin keeps being connected to the ground providing normal operating in that way. If later on, during the operation, manual reset button is pushed, the condenser is being temporarily discharged and the microcontroller is being reset. Upon the button release, the whole process is repeated… Through the program- step by step... The microcontrollers normally operate at very high speed. The use of 12 Mhz quartz crystal enables 1.000.000 instructions per second to be executed! In principle, there is no need for higher operating rate. In case it is needed, it is easy to built-in crystal for high frequency. The problem comes up when it is necessary to slow down. For example, when during testing in real operating environment, several instructions should be executed step by step in order to check for logic state of I/O pins. Interrupt system applied on the 8051 microcontrollers practically stops operating and enables instructions to be executed one at a time by pushing button. Two interrupt features enable that:  Interrupt request is ignored if an interrupt of the same priority level is being in progress.   Upon interrupt routine has been executed, a new interrupt is not executed until at least one instruction from the main program is executed.  In order to apply this in practice, the following steps should be done: 1. External interrupt sensitive to the signal level should be enabled (for example INT0). 2. Three following instructions should be entered into the program (start from address 03hex.):
  • 65. What is going on? Once the pin P3.2 is set to “0” (for example, by pushing button), the microcontroller will interrupt program execution jump to the address 03hex, will be executed a mini-interrupt routine consisting of 3 instructions is located at that address. The first instruction is being executed until the push button is pressed ( logic one (1) on the pin P3.2). The second instruction is being executed until the push button is released. Immediately after that, the instruction RETI is executed and processor continues executing the main program. After each executed instruction, the interrupt INT0 is generated and the whole procedure is repeated ( push button is still pressed). Button Press = One Instruction. 2.9 8051 Microcontroller Power Consumption Control Conditionally said microcontroller is the most part of its “lifetime” is inactive for some external signal in order to takes its role in a show. It can make a great problem in case batteries are used for power supply. In extremely cases, the only solution is to put the whole electronics to sleep in order to reduce consumption to the minimum. A typical example of this is remote TV controller: it can be out of use for months but when used again it takes less than a second to send a command to TV receiver. While normally operating, the AT89S53 uses current of approximately 25mA, which shows that it is not too sparing microcontroller. Anyway, it doesn’t have to be always like this, it can easily switch the operation mode in order to reduce its total consumption to approximately 40uA. Actually, there are two power-saving modes of operation: Idle and Power Down.