Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
EmbeddedSystems
&Robotics
Basic
http://www.hpesindia.com
Contents
Chapter1 Basics...............................................................................................6
1.1 WhatisaDigitalsystem?....................................................................................................6
1.2 AssigningStates..................................................................................................................6
1.3 NumberSystemsindigitalelectronics...............................................................................6
1.4 TypesofDigitalCircuits.......................................................................................................6
1.5 Clock:Buildingblockofasequentialcircuit.......................................................................7
1.6 LogicGates:Buildingblockofacombinatorialcircuitry.....................................................7
1.7 PracticalCircuitingElements..............................................................................................8
1.7.1
Resistor:......................................................................................................................8
1.7.2
Capacitor:....................................................................................................................8
1.7.3
Breadboard:................................................................................................................9
1.7.4
IntegratedCircuits(IC)................................................................................................9
1.7.5
LED............................................................................................................................10
Chapter2 SomeIntegratedCircuitsandImplementation............................11
2.1 555....................................................................................................................................11
2.1.1
Monostablemode.....................................................................................................11
2.1.2
Astablemode............................................................................................................12
2.2 4029counter.....................................................................................................................13
2.2.1
PinDescription..........................................................................................................13
2.3 7447:BCDto7segmentdisplaydecoder.........................................................................14
2.3.1
PinDescription..........................................................................................................14
2.4 LDR(LightDependentResistor)........................................................................................14
2.5 OperationalAmplifier(Opamp)........................................................................................15
2.5.1
Opampasacomparator...........................................................................................16
2.6 7805VoltageRegulator....................................................................................................16
Chapter3 IntroductiontoEmbeddedSystems.............................................18
3.1 Applications......................................................................................................................19
3.2 EmbeddedSystemTypes..................................................................................................19
Chapter4 IntroductiontoMicrocontrollers..................................................20
4.1 WhatisMicrocontroller?..................................................................................................20
4.2 BasicArchitecturesofMicrocontrollers...........................................................................22
4.3 DigitalIntegratedCircuits(ICs).........................................................................................25
4.4 ProcessorType&MemoryStructures..............................................................................27
1|P a g e
4.5 OrganizationofDataMemory..........................................................................................30
4.6 Compiler/IDE(IntegratedDevelopmentEnvironment)..................................................33
4.7 Programmer......................................................................................................................33
4.8 HowtouseSerialProgrammer'sCircuit(Hardware)........................................................34
4.9 USBProgrammer..............................................................................................................38
Chapter5 CodeVisionAVR(CVAVR).............................................................38
5.1 CHIP:..................................................................................................................................40
5.2 PORT:................................................................................................................................40
Chapter6 IntroductiontoAtmega16Microcontroller.................................43
6.1 Features............................................................................................................................43
6.2 PinConfiguration..............................................................................................................43
6.3 BlockDiagram...................................................................................................................44
6.4 PinDescriptions................................................................................................................45
6.5 DigitalInputOutputPort..................................................................................................46
6.6 Registers............................................................................................................................46
Chapter7 I/OPorts:.......................................................................................47
7.1 DDRX(DataDirectionRegister)........................................................................................47
7.2 PORTX(PORTXDataRegister)...........................................................................................48
7.3 PINX(DataReadRegister)................................................................................................48
7.4 ASMALLNOTEABOUTDELAY.......................................................................................49
Chapter8 LCDInterfacing..............................................................................50
8.1 OverviewofLCDDisplay...................................................................................................50
8.2 CircuitConnection............................................................................................................52
8.3 SettingupinMicrocontroller............................................................................................52
8.4 PrintingFunctions.............................................................................................................54
8.4.1
lcd_clear().................................................................................................................54
8.4.2
lcd_gotoxy(x,y)..........................................................................................................54
8.4.3
lcd_putchar(charc)...................................................................................................54
8.4.4
lcd_putsf(constantstring).........................................................................................54
8.4.5
lcd_puts(chararr).....................................................................................................54
8.4.6
itoa(intval,chararr[])...............................................................................................55
8.4.7
ftoa(floatval,chardecimal_places,chararr[]).........................................................55
Chapter9 ADC:AnalogtoDigitalConverter.................................................56
9.1 Theoryofoperation..........................................................................................................57
9.2 SettingupMicrocontroller................................................................................................57
9.3 FunctionforgettingADC..................................................................................................58
Chapter10
2|P a g e
Timers.....................................................................................59
10.1
WhatisaTimer?...........................................................................................................59
10.2
HowtoUseTimer.........................................................................................................59
10.3
Prescalar.......................................................................................................................59
10.4
TimerMode..................................................................................................................60
10.5
NormalMode................................................................................................................60
10.6CTCMode.........................................................................................................................60
10.7PulseWidthModulation(PWM)Mode...........................................................................61
(A)PWM:PulseWidthModulation...........................................................................................61
(B)PWMSignalGenerationUsingAvrTimers..........................................................................62
(C)PhaseCorrectPWMMode..................................................................................................64
10.8SETTINGUPTIMERSINCODEVISIONAVR.......................................................................66
10.9
FastPWMMode...........................................................................................................70
10.10 CTCMode......................................................................................................................71
Chapter11
11.1
Data Transfer................................................................................................................72
11.2
Classification.................................................................................................................72
11.3
BaudRate......................................................................................................................73
11.4
DifferentCommunicationTechniques..........................................................................74
Chapter12
TheoryofOperation.....................................................................................................75
12.2
SettingupSPIinMicrocontroller..................................................................................80
12.2.1
MasterMicrocontroller........................................................................................80
12.2.2
SlaveMicrocontroller............................................................................................80
DataFunctions..............................................................................................................80
12.3.1
TransmitData.......................................................................................................81
12.3.2
ReceiveData.........................................................................................................81
12.4
ConnectingMCUToAnotherMCU...............................................................................81
Chapter13
USARTCommunication..........................................................82
13.1
USART...........................................................................................................................82
13.2
HardwareAspectofUSART...........................................................................................82
13.3
BaudRate......................................................................................................................82
13.4
DataTransmission.........................................................................................................82
13.5
UART:TheoryofOperation..........................................................................................83
13.6
SerialPortofComputer................................................................................................84
13.7
SettingupUARTinmicrocontroller..............................................................................86
13.8
DockLight......................................................................................................................88
13.9
ImplementingUSARTinYourCode..............................................................................89
13.9.1
putchar()...............................................................................................................89
13.9.2
getchar()................................................................................................................89
13.9.3
putsf()....................................................................................................................89
Chapter14
SPI:SerialPeripheralInterface..............................................74
12.1
12.3
3|P a g e
Communication......................................................................72
Interrupt.................................................................................91
Example..................................................................................................................................92
14.1
Polling...........................................................................................................................92
14.2
Hardwareinterrupt.......................................................................................................92
14.3
HardwareInterruptorpolling?.....................................................................................93
14.4
SettingupHardwareInterruptinMicrocontroller.......................................................93
14.5
FunctionsofInterruptServiceRoutine.........................................................................93
14.6
TimerInterrupt.............................................................................................................94
14.7
OverflowInterrupt........................................................................................................94
14.8
CompareMatchInterrupt.............................................................................................95
Chapter15
EEPROM.................................................................................97
Chapter16
IntroductiontoRobots.........................................................100
16.1
WhatIsARobot?........................................................................................................102
16.2
RobotChassisDesigning.............................................................................................103
16.2.1
Robotwithsteeringwheel:.................................................................................104
16.2.2
Robotwithdifferentialdrive:.............................................................................104
Chapter17
MotorsandMotorDrivers...................................................105
17.1
IntroductiontoMotors...............................................................................................105
17.2
HBridge:....................................................................................................................106
17.3
MotorDriverICs:L293/L293DandL298....................................................................107
17.3.1
DifferencebetweenL293andL298:...................................................................109
17.3.2
SpeedControl:....................................................................................................109
Chapter18
Sensors.................................................................................109
18.1
AnalogSensor.............................................................................................................116
18.2
DigitalIRSensorTSOPSensor...................................................................................117
Chapter19
19.1
ProjectWork........................................................................118
LinefollowingRobot...................................................................................................118
Chapter20DefinitionsofEmbeddedsystem............................................119
Chapter21GLOSSARY................................................................................121
Chapter22References..............................................................................126
4|P a g e
SectionA
DigitalElectronics
5|P a g e
Chapter1 Basics
1.1 WhatisaDigitalsystem?
Inmostgeneralterms,thissystemsbehaviorissufficientlyexplainedbyusingonlytwoofits
statescanbeVoltage(morethanxvoltsorless?),distancecovered(morethan2.5kmorless?],true
falseorweightofanelephant(willmyweighingmachinewithstandit?))
Notethatalthoughineverycase,thealltheintermediatestatesAREPOSSIBLEANDDOEXIST,
ourpointofinterestaresuchthatwedontrequiretheirexplicitdescription.Inelectronicsystems
wemostlydealwithVoltagelevelsasdigitalentities.
1.2 AssigningStates
Thereisnospecificfixeddefinitionoflogiclevelsinelectronics.Mostcommonlyusedlevel
designationistheoneusedinCMOSandTTL(transistortransistorlogic)families:
Logichigh>designatedas1
Logiclow>designatedas0
Where high and low are actually higher and lower with respect to a reference voltage
level (ideally taken as 2.5V)
GOOGLY:Whyassign0and1andnotaandb,xandy,catanddog?
ANS:Computationalease!
1.3 NumberSystemsindigitalelectronics
1.4 TypesofDigitalCircuits
CombinatorialCircuits:Inthesecircuits,thepaststatesareimmaterial
andtheoutputdependsonlyuponthepresentstate.Examplelogicgates
Sequentialcircuits:Inthesecircuits,thenextstateiscompletely
determinedbythepaststates.Hencethesefollowapredictablestructure
andessentiallyrequireatimingdevice.Ex.counters,flipflops.
6|P a g e
1.5 Clock:Buildingblockofasequentialcircuit
Aclockissimplyalternatehighandlowstatesofvoltagewithtimei.e.essentiallyasquarewave.
Importanttermsrelatedtoclockareitsdutycycleanditsfrequency:
Dutycycle:ItistheratioofThandTh+Tl
TheseareessentiallycombinatorialcircuitsusedtoimplementlogicalBooleanoperationslikeAND,
NAND,OR,XORandNOT.NOTandNANDarecalleduniversalgatesasanyothergatecanbeformed
usingeitherofthem!
Figure1:TableofLogicGates
7|P a g e
1.7 PracticalCircuitingElements
1.7.1 Resistor:
Acolorschemeisfollowedtogivethespecificationsofaresistor.Thetableforcolorcodeisshown
below:
The1sttwobandsspecifythe2digitsoftheresistorvaluewhereasthe
3rdbandspecifiesthemultiplierintermsofthepowertowhich10is
raisedandmultipliedtothe2digits.
Thetolerancetellsthepossible%variationoftheresistorvalueabout
thevalueindicatedbybands.
Figure2:TableofResistance
1.7.2 Capacitor:
The2typesofcapacitorswefrequentlyuseincircuitsareceramicandelectrolyticcapacitors.While
ceramiccapacitorsdonothaveafixedpolarity;electrolyticcapacitorsshouldbeconnectedintheir
specifiedpolaritiesonlyelsetheymightblowoff!Thispolarityisusuallyprovidedonthesideofthe
capacitorscorrespondingleg.
Figure4:Electrolyticcapwithvepolaritylegseen
8|P a g e
Figure3:Ceramiccapwithvalue15x104pF
1.7.3 Breadboard:
Thisisthebaseusedforsettingupthecircuit.Thishasembeddedmetalstripsinitthatformagrid
ofconnectionsinsideitsbody.Thisallowsustotakemultipleconnectionsfromasinglepoint
withoutanyneedofsoldering/disorderingasinPCBs.Itisalwaysagoodhabittotestthecircuiton
breadboardbeforemakingitonaPCB.
1.7.4 IntegratedCircuits(IC)
ICsorIntegratedCircuitsarepackagedcircuitsdesignedforsome
fixedpurpose.AnIChasitsfixedICname/numberthatcanbeused
togetcatalogofitsfunctionsandpinconfiguration.ICscomein
varioussizesandpackagesdependinguponthepurpose.
NOTE:NumberingschemeofICpinswillbeexplainedinthelab
session.DifferentICsmayhavedifferentnumberofpins.
Figure6:IC
9|P a g e
Figure5:Topviewshowingtheconnectingholes.Bottomviewshowsthecontactmetalstrips
1.7.5 LED
LED(LightEmittingDiode)isfrequentlyusedtodisplaytheoutputsatvariousstagesofthecircuit.It
is essentially a Diode with the energy released in the form of photons due to electron transitions
fallinginthevisibleregion.Hencenormaldiodepropertiesapplytoit.
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.Hencealwaysputa220ohmresistorinserieswiththeLED.
Never forget that LEDs consume a significant amount of power of the outputs of the ICs (CMOS
based).Henceitisadvisabletoonlyusethemforcheckingthevoltagelevel(highorlow)andthen
removethem.
Figure7:LEDs
10|P a g e
Chapter2 SomeIntegratedCircuitsandImplementation
2.1 555
555isanICusedtogenerateaclock.The
twoattributesofaclockare
Frequency
Dutycycle.
BothofthesecanbechangedusingthisIC,
howeverthedutycycleisalways<50%.
Therearetwomodesinwhich555canrun.
Figure8:PinConfigurationof555
2.1.1 Monostablemode
Asthenamesuggests;inthismodetheoutputisstableinonlyone(mono)statei.e.offstate.Thus
itcanstayonlyforafinitetime,iftriggered,totheotherstatei.e.onstate.Thistimecanbeset
choosingappropriatevaluesofresistancesintheformula:
T=1.1xR1xC1
Figure9:555inmonostablemode
11|P a g e
2.1.2 Astablemode
Inthismode;theoutputisstableneitherinhighstatenorinlowstate.Henceitoscillatesfrom
onestatetoanothergivingusasquarewaveorclock.WecansettheclockfrequencyandDutycycle
Dbytheformulae:
.
F=
D=
Figure10:555inastablemode
NOTE:CapacitorC2isjusttofilterthenoiseanditsvaluecanbesuitablychosentobe0.01F.Itcan
alsobeneglected.
12|P a g e
2.2 4029counter
Withtheclockmade,wearereadytocountthenumberofpulsespassedintothecircuit.Notethat
anykindofcountingrequiresamemory(yougottoknowthatyouhavejustcounted3togoto
4!).Hence4029canalsobeusedasamemoryelementthatremembersitsimmediateprevious
state.
Figure11:4029pinconfiguration
2.2.1 PinDescription
PINNo.
1
13|P a g e
Name
Parallelload
2
3
4
5
OutputBit3
Parallelinputbit3
Parallelinputbit0
Clockenablebar
6
7
OutputBit0
TCbar
8
9
Gnd
Binary/Hexbar
10
Up/Downbarcount
11
12
13
14
15
16
Outputbit1
Parallelinputbit1
Parallelinputbit2
Outputbit2
Clockpulse
Vdd
Pinfunction
Ifgivenhigh;loadsthevalueof
Parallelbitintotheo/pbits
Mostsignificantbitofo/p
Mostsignificantbitofparalleli/p
Leastsignificantbitofparalleli/p
Lowonthispinenablescountingas
pertheclockreceived
Leastsignificantbitofparallelo/p
Outputbitthatgivesalowwhenthe
countiscomplete.Canbeusedtosignal
theendofcounting.
Neededforpowering
Tochooseb/wbinaryand
hexadecimalmodes
Tochooseb/wupcountingand
downcountingmodes
2ndbitofo/p
2nd bitofi/p
3rdbitofi/p
3rdbitofo/p
Clockpulseisgivenhere
Neededforpowering
Connectionreqd.
Gnd
Topin6of7447
Input
Input
Gnd
Topin7of7447
Noneifyoudont
wanttouseit
Gnd
lowforcount015
highforcount09
Lowfordowncount
Highforupcount
Topin1of7447
Input
Input
Topin2of7447
Clockfrom555
+5V
Figure12:7447pinconfiguration
2.3.1 PinDescription
PIN
no.
1
2
3
Name
Function
Connectionreqd.
i/pB
i/pC
LampTest
bar
2ndbit(O1)of4029so/p
3rdbit(O2)of4029so/p
UsedtocheckthatallLEDsof7seg
areworking.
4
5
6
BI/RBI
RBI
i/pD
7
8
915
i/pA
Gnd
agasperthe
fig
Vcc
Kepthightoallownormalfunction
Blanks0frombeingdisplayed
Mostsignificantbit(O3)of4029s
o/p
3rdbit(O2)of4029so/p
Forpower
Theo/ppinsto7segmentdisplay
ToO1of4029
ToO2of4029
Highfornormalfn
Lowtoglowall
LEDs
Kepthigh
Kepthigh
ToO2of4029
16
Forpower
ToO2of4029
Connectedtognd
To7segdisplay
Connectedto+5V
NOTE:
TheCOMpinsaretobeconnectedtoVccvia220ohmresistor.Whyresistorisrequired??
Thedotpinisjustfordisplayofdecimalpointandessentiallyonlymakestheupperand
lowersidesdistinguishablefromeachotherforasingledisplay.withouttheasymmetry
producedbydothowwillwebeabletoseewhichsideisupperandwhichislower?
2.4 LDR(LightDependentResistor)
14|P a g e
LightDependentResistor(LDR)orphotoresistorisadevicethatactslikearesistanceandits
resistancevarieswiththeintensityoflightincidentonit.Inthisdevice,ifphotonsofsufficient
energyfallonit,theresistancedropsdrasticallyastheelectronsinthesemiconductorareableto
jumpfromthevalencebandtotheconductionbandandareavailableforconduction.TheLDRsused
aremostlyresponsivetovisiblelight.Theresistancemightdropfromashighas1Minthedarkto1
kinbrightlight.
Figure13:LDRs.Thecoiledportionisresponsivetolight
2.5 OperationalAmplifier(Opamp)
Opampisaveryimportantdeviceusedineverydayelectronics.Itisessentiallyadifferential
amplifierwithaveryhighgainoftheorderof105!BydifferentialamplifierImeanthatitamplifies
thedifferenceof2signalsandgivestheoutput.
Opampequation:
Vout=A(V+V)
whereAisthegainoftheorder105.
Ironically,thishighgaininopenloopmakesitimpossibletouseitasageneralpurpose
differentialamplifierdirectly.
GOOGLY:If(V+V)=0.005V;Vss=12Vwhatwillbetheoutput??
15|P a g e
2.5.1 Opampasacomparator
SimplestuseofOpampisasacomparator.Itcanbeusedtoconvertananalogsignaltoadigital
signaldefinedbyafixedthreshold.SetVasthethresholdvoltagesay2.5Vandapplytheanalog
signaltobedigitizedatV+.Whatwillbetheoutput?Wellifyouhaveworkedoutthegoogly;this
shouldbeapieceofcake!
2.6 7805VoltageRegulator
7805voltageregulatorisusedtoget+5Voutputoutofahighervoltagesupply(7.5V20V).Weuse
adapterssupplytogenerate+5Vhere.Connectthegndand+12Vofadaptertothepinsasshown
andget+5Vdirectlyasanoutputoutofthe3rdpin.Currentupto0.5Acanbeobtainedfromthis
regulatorwithoutanysignificantfallinvoltagelevel.
NOTE:Use2capacitorsofvaluesay0.1Ftofilterthenoiseintheinputandoutputofregulators
supplyasshown.
16|P a g e
SectionB
EmbeddedSystems
17|P a g e
Chap
pter3 Introductio
ontoEmb
beddedSy
ystems
Embed
dded system is a scaled down comp
puter system which is deesigned to perform a specific
task/operation. Unlike a gen
neral purposse computerr
system
m which is ussed for a varriety of tasks, like playingg
music,, games, surffing internet etc. The term
m embedded
d
tellsth
hatwholesysstemisembeddedintoanappliance.A
A
single chip contaains both hardware
h
an
nd softwaree
(technically, firmw
ware). It iss designed to perform
m
operattions which minimize (orr even comp
pletely avoid))
needo
ofhumancon
ntrol.
BasicFFlowdiagram
mforembeddedcomputerrsystemscan
n
besho
ownas:
y VariouswayswecanDeefine
s
is a sspecialpurpo
ose computerr system dessigned to perrform
An Embedded system
eorafewdedicatedfuncttions,oftenw
withrealtimecomputingcconstraints.
one
or
An EmbeddedssystemisaSoftwareproggramonaH//Wchipdesiggnedforaspecific
purrposeandcan
nalsocontain
nsomemechanicalmovinggparts.
Asfeatu
uresgetonad
ddeddailydefinitionitselfisevolving.
or
y AnEmbedd
dedsystemisaspecialpu
urposecomp
putersystem designedto performoneeora
fewdedicattedfunctionss,oftenwithrrealtimecom
mputing.
or
y AnEmbedd
dedsystemisssomecombiinationofcom
mputerhardw
wareandsofttware,eitherfixed
in capability or prograammable, th
hat is speciffically design
ned for a particular
p
kin
nd of
applicationdevice.
18|P a g e
Someimportantthingstonoteaboutembeddedsystems:
1. Once an embedded hardware is programmed for a certain task, it is used forever for the
sametask.Changingthefirmwareafterwardsisnotpossible.
2. Such systems are limited in computational resources like memory, CPU processing speed,
I/Ofacilitiesbutarestillcapableofperformingthetaskgiventothemveryefficiently.
3. Embeddedsystemscanalsobehavingareducedfunctionalityversionofoperatingsystem
calledRTOS(RealTimeOperatingSystem)forhighlyspecializedapplications.
4. Is a system built to perform its duty, completely or partially independent of human
intervention?
5. Is specially designed to perform a few tasks in the most efficient way.
6. Interacts with physical elements in our environment, viz. controlling and driving a
motor, sensing temperature, etc.
3.1 Applications
An embedded system can be defined as a control system or computer system designed to
perform a specific task. Examples:
1. Pen drives (for controlling the communication between P.C. and Flash Chip and also the
small LED!)
2. Hard disks( again for the same purpose)
3. Mouse(Reads and Interprets the Sensors and send final result to P.C.),Keyboards
4. Printers: Ever opened a printer for installing ink cartridge? Then you must have seen the
printed head. There are motors to control the print head and the paper movement. Your
P.C. is not directly connected to them but there is built in MCU of printer to control all
these. Your P.C. just sends the data (pixels) through the communication line (USB or
parallel).But the MCU used here is fairly fast and has lots of RAM.
5. Automobiles
6. Calculators, Electronic wending machines, Electronic weighing scales, Phones(digital
with LCD and phonebook)
7. Cell phones
8. SecuritySystem
9. Alarmsystem
10. Automobilesystem
11. DigitalCamera
12. Environmentmonitoringsystems(usingsensorsandactuators)
Embeddedsystemsareoftenrequiredtoperformrealtimeoperations.ByRealtimeoperations,we
meanthat,operationswheredelayofevenafewmillisecondscouldbedangerous.Somerealtime
systemsmaybe:
1. SensorsysteminNuclearPlants
2. Flightcontrolsystems
3. AutomobileBrakingsystemandenginecontrollingsystems
Thesearesituationswhereweneedveryaccuratetimingandcontrol.Failureinsuchsituationsmay
causegreatloss.
3.2 EmbeddedSystemTypes
19|P a g e
y RealtimeEmbeddedSystems:Wheredeadlineistobemet.
Softrealtimeembeddedsystems.
Hardrealtimeembeddedsystems.
y FollowingaresomeapplicationsofEmbeddedSys.butnotrealtime.
SecuritySystems.
MobileandPDA.
AlarmSystem.
Automobilesystem.
DigitalCamera.
y ExamplesofRealtimeEmbeddedsystems.
SensorsysteminNuclearplants.
Missiledefencesystem.
Flightcontrolsystem.
AnticollisionsysteminAutomobiles.
Chapter4 IntroductiontoMicrocontrollers
4.1 WhatisMicrocontroller?
20|P a g e
WhatisaMicrocontroller?
A Microcontroller is a programmable digital processor with necessary peripherals. Both
microcontrollersandmicroprocessorsarecomplexsequentialdigitalcircuitsmeanttocarryout
job according to the program / instructions. Sometimes analog input/output interface makes a
part of microcontroller circuit of mixed mode(both analog and digital nature).
AmicrocontrollercanbecomparedtoaSwissknifewithmultiplefunctionsincorporatedinthe
sameIC.
Fig.4.1AMicrocontrollercomparedwithaSwissknife
MicrocontrollersVsMicroprocessors
Development/Classificationofmicrocontrollers(Invisible)
Microcontrollers have gone through a silent evolution (invisible). The evolution can be rightly
termedassilentastheimpactorapplicationofamicrocontrollerisnotwellknowntoacommon
user,althoughmicrocontrollertechnologyhasundergonesignificantchangesinceearly1970's.
Developmentofsomepopularmicrocontrollersisgivenasfollows.
21|P a g e
Intel4004
4bit(2300PMOStrans,108kHz)
Intel8048
8bit
Intel8031
8bit(ROMless)
Intel8051
8bit(MaskROM)
MicrochipPIC16C64
8bit
Motorola68HC11
8bit(onchipADC)
Intel80C196
16bit
AtmelAT89C51
MicrochipPIC16F877
8bit(Flashmemory)
8bit(Flashmemory+ADC)
197
1
197
6
.
198
0
198
5
.
198
2
.
.
Developmentofmicroprocessors(Visible)
Microprocessors have undergone significant evolution over the past four decades. This
developmentisclearlyperceptibletoacommonuser,especially,intermsofphenomenalgrowth
incapabilitiesofpersonalcomputers.Developmentofsomeofthemicroprocessorscanbegiven
asfollows.
Intel4004
4bit(2300PMOStransistors)
1971
Intel8080
8bit(NMOS)
1974
8085
8bit
Intel8088
16bit
1978
8086
16bit
Intel80186
16bit
1982
80286
16bit
Intel80386
32bit(275000transistors)
1985
Intel80486SX
32bit
1989
DX
32bit(builtinfloatingpointunit)
Intel80586I
1993
MMX
1997
CeleronII
64bit
1999
III
2000
IV
Z80(Zilog)
8bit
1976
MotorolaPowerPC
32bit
1993
601
602
1995
603
4.2 BasicArchitecturesofMicrocontrollers
We use more number of microcontrollers compared to microprocessors. Microprocessors are
primarilyusedforcomputationalpurpose,whereasmicrocontrollersfindwideapplicationindevices
needingrealtimeprocessing/control.
22|P a g e
Applicationofmicrrocontrollers isnumerous..Startingfrom
mdomesticaapplicationsssuchasinwasshing
machin
nes,TVs,aircconditioners,microcontrollersareused
dinautomobiles,processccontrolindusstries,
cellph
hones,electriccaldrives,androb+oticsandinspaceaapplications.
MicrocontrollerChips
BroadClassification
nofdifferentmicrocontrolllerchipscouldbeasfollows:
Embedded(SelfContain
ned)8bitM
Microcontrolle
er
16to32Microcontrollerrs
DigitalSignalProcessorss
Fe
eaturesofM
ModernMicrocontrollerss
BuiltinMo
onitorProgram
m
BuiltinPro
ogramMemorry
Interrupts
AnalogI/O
SerialI/O
FacilitytoInterfaceExteernalMemoryy
Timers
IntternalStrucctureofaMiicrocontrolleer
Fiig.4.2InternaalStructureoffaMicrocontroller
Harrvardvs.PriincetonArch
hitecture
At times,
t
a microcontroller can have extternal memo
ory also (if th
here is no intternal memory or
extramemoryin
nterfaceisreequired).Earllymicrocontrrollerswerem
manufactured
dusingbipolaror
NM
MOS technolo
ogies. Most modern
m
micro
ocontrollers are manufactured with CMOS
C
techno
ology,
whiich leads to reduction in
n size and p
power loss. Current
C
draw
wn by the IC
C is also red
duced
23|P a g e
con
nsiderably fro
om 10mA to a few micro Amperes in sleep mode(for a microccontroller run
nning
typicallyataclockspeedof2
20MHz).
Manyyearsago,inthelate1
1940's,theUSGovernmen
ntaskedHarvvardandPrin
ncetonuniverrsitys
to come
c
up with a compute
er architecturre to be used
d in computing distances of Naval arttillery
sheellfordefenseeapplications.Princeton suggestedco
omputerarchitecturewith
hasinglememory
inteerface.ItisalsoknownassVonNeumaannarchitectu
ureafterthe nameofthe
echiefscientistof
theprojectinPrrincetonUniversityJohnVo
onNeumann(19031957
7BorninBudaapest,Hungary).
differentmem
moryinterfaces,oneforth
hedata/variables
Harrvardsuggesttedacomputerwithtwod
and
d the other for
f program / instruction
ns. Although Princeton architecture
a
w accepted
was
d for
sim
mplicity and ease
e
of impleementation, H
Harvard architecture becaame popular later, due to
o the
parrallelismofinstructionexeecution.
Prin
ncetonArch
hitecture(Siinglememo
oryinterface
e)
Fig.4.3 PrincetonArrchitecture
Examp
ple:Aninstrucction"Readaadatabytefro
ommemoryaandstoreitin
ntheaccumu
ulator"isexeccuted
asfollo
ows:
Cycle1
1ReadInstruction
Cycle2
2ReadDataoutofRAMandputintoA
Accumulator
HarrvardArchittecture(SeparateProggramandDaataMemoryinterfaces)
24|P a g e
Fig.4.44HarvardArrcitecture
Thesameinstructio
on(asshownunderPrinceetonArchitectture)wouldb
beexecutedaasfollows:
Cycle1
1
Completepreviousinstruction
DatatoAccum
mulator"instrruction
Readthe"MoveD
2
Cycle2
Execute"MoveDattatoAccumu
ulator"instrucction
Readnextinstructtion
Hence each instrucction is effecctively executed in one instruction cyycle, except for
f the ones that
modifyy thecontenttof the proggramcounterr. For examplle,the "jump
p" (or call)insstructionstakkes2
cycles.. Thus, due to
t parallelism
m, Harvard arrchitecture executes more instruction
ns in a given time
compaaredtoPrinceetonArchitecture.
4.3 DigitalInttegratedC
Circuits(IC
Cs)
YoumustbeknowingaboutDigitalIntegratedCircuits(ICss)right?Foreexample:
7404:HexInverter
7408:Quad
d2inputAND
Dgate
7410:Triplee3inputNAN
NDGate
7432:Quad
d2inputORG
Gate
7457:60:1Frequencydiivider
ThereareAND,XOR
R,NAND,NOR,ORlogicgaateICs,Countters,Timers,SevenSegmeentDisplayDrrivers
andmuchmore.Justcheckout7
7400Seriesaand4000SeriesofIntegrattedCircuits.
etstakeQuaad2inputAN
NDgateIC.It has4ANDgaates,eachhaaving2pinsfo
orinputand 1pin
Nowle
forouttput.Thetrutthtableorthefunctiontableofeachgaateisfixed.TThisisasfollows,
Input1
0
0
1
1
25|P a g e
Input2
0
1
0
1
Output
0
0
0
1
Similarly all the Integrated circuits havetheir functiontables and inputand outputpinsfixed. You
cannotchangethefunctionandnoinputpinactasoutputandviceversa.Sowheneveryouwantto
designsomecircuityoufirsthavetogettheoutputasafunctionofinputsandthendesignitusing
gatesorwhatevertherequirementis.
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 designingany
circuit which involves change of the function table every now and then you are in trouble ! For
exampleifIwanttodesignanAutonomousRobotwhichshouldperformvarioustasksandIdont
justwanttofixthetask.SupposeImakeittomoveinapaththenIwanttochangethepath!How
todothat?
HerecomestheuseofMicrocontrollers!NowifIgiveyouanIntegratedCircuitwith20pinsandtell
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! Thats nice :) Thats
whatthemostbasicfunctionofamicrocontrolleris.IthassetofpinscalledasPORTandyoucan
make any pin either as output or input. After configuring pins you can program it to perform
accordingtoanyfunctiontableyouwant.Youcanchangetheconfigurationorthefunctiontableas
manytimesyouwants.
There are many Semiconductor Companies which manufactures
microcontrollers.Someofthemare:
Intel
Atmel
Microchip
Motorola
WewilldiscussaboutAtmelMicrocontrollerscommonlyknownasAVRinthissection.
Question:Howamicrocontrollerworks?
Answer:WellIcannotgointolotofdetailsabouttheworkingbecauseitisavasttopicinitself.Ican
justgiveanoverview.
Microcontroller consists of an Microprocessor (CPU that is Central processing Unit) which is
interfacedtoRAM(RandomAccessMemory)andFlashMemory(oneyourpendrivehas!).Youfeed
your program in the Flash Memory on the microcontroller. Now when you turn on the
microcontroller,CPUaccessestheinstructionfromRAMwhichaccessyourcodefromFlash.Itsets
theconfigurationofpinsandstartperformingaccordingtoyourprogram.
Question:Howtomakethecode?
Answer:YoubasicallywritetheprogramonyourcomputerinanyofthehighlevellanguageslikeC,
C++,andJAVAetc.Thenyoucompilethecodetogeneratethemachinefile.Nowyouwillaskwhat
thismachinefileis.Allthemachinesunderstandonlyonelanguage,0&1thatisonandoff.Now
this0&1bothcorrespondsto2differentvoltagelevelsforexample0voltfor0logicand+5voltfor
1logic.Actuallythecodehastobewritteninthis0,1languageandthensavedinthememoryofthe
microcontroller. But this will be very difficult for us ! So we write the code in the language we
understand(C)andthencompileandmakethemachinefile(.hex).Afterwemakethismachinefile
wefeedthistothememoryofthemicrocontroller.
26|P a g e
Question:HowtofeedthecodeintheflashofMicrocontroller?
Answer:Assumingyouhavethemachinefile(.hex)readyandnowyouwanttofeedthattotheflash
of the microcontroller. Basically you want to make communication between your computer and
microcontroller.NowcomputerhasmanycommunicationportssuchasSerialPort,ParallelPortand
USB(UniversalSerialBus).
LetstakeSerialPort,ithasitsowndefinitionthatisvoltageleveltodefine0&1(yeahallthedata
communication is a just collection of 0 &1 ) Serial Port's protocol is called as UART (Universal
AsynchronousReceiver& Transmitter)Itsvoltagelevelsare:12voltfor0logicand +12voltfor1
logic.
Now the voltage levels of our microcontroller are based on CMOS (Complementary Metal Oxide
Semiconductor)technologywhichhas0voltfor0logicand+5voltfor1logic.
Twodifferentmachineswith2differentwaystodefine0&1andwewanttoexchangeinformation
betweenthem.ConsidermicrocontrollerasFrenchandComputer'sSerialPortasanIndianperson
(obviously no common language in between!) If they want to exchange information they basically
needamediatorwhoknowsboththelanguage.Hewilllistenonepersonandthentranslatetoother
person.SimilarlyweneedacircuitwhichconvertsCMOS(microcontroller)toUART(serialport)and
viceversa.This circuitis calledasprogrammer. Usingthis circuit wecanconnectcomputertothe
microcontrollerandfeedthemachinefiletotheflash.
TheAVR(AdvancedVirtualRisc)isaModifiedHarvardarchitecture8bitRISCsinglechip
microcontroller(C)whichwasdevelopedbyAtmelin1996.TheAVRwasoneofthefirst
microcontrollerfamiliestouseonchipflashmemoryforprogramstorage.
4.4 ProcessorType&MemoryStructures
Microcodedandhardcodedprocessors:
Theimplementationofcomputerarchitecturecanbebroadlyachievedintwoways.Acomputerisa
complexsequential digital circuitwith both combinational and sequentialcircuit components.In a
microcodedprocessor,eachinstructionisrealizedbyanumberofstepsthatareimplementedusing
small subroutines. These subroutines are called microcodes stored within the instruction decode
unit.Hence,amicrocodedprocessorcanbecalledaprocessorwithinaprocessor.
Microcodedprocessor:
27|P a g e
Fig.4
4.5Architectu
ureofaMicroCodedProcesssor
Letustakeanexam
mple.Theinsttruction"MovveAcc,Reg"ccanbeexecuttedinthefolllowingsteps.
1. Outputadd
dresstothedatamemory
2. Configurettheinternalbusfordatam
memoryvalueetobestoredinaccumulattor.
3. Enablebusread.
4. Storethedataintotheaaccumulator.
5. Compared
datareadwithzerooranyyotherimpo
ortantconditionandsetb
bitsintheSTA
ATUS
register.
6. Disabledattabus.
Eachsstepoftheinstructionisrrealizedbya subroutine(m
microcode). Asetofbits intheinstruction
pointstothememo
orywheretheemicrocodefortheinstru
uctionislocatted.
Advan
ntages:
1. Easeoffabrrication.
bug.
2. Easytodeb
Disadvvantage:
1.P
Programexeccutiontakeslo
ongertime.
Hardcoded
dprocessor:
Eachin
nstructionisrrealizedbyco
ombinationaland/orsequeentialdigitalcircuits.Thed
designiscom
mplex,
hardto
odebug.How
wever,thepro
ogramexecuttionisfaster.
28|P a g e
Fig4
4.6Architectu
ureofaHardCodedProcesssor
Me
emoryType
In a
a microcontrroller, two tyypes of mem
mory are found. They aree, program memory
m
and data
memoryrespecttively.Programmemoryissalsoknown as'controlsttore'and'firm
mware'.Itis non
volaatilei.e,them
memoryconttentisnotlosstwhenthep
powergoesofff.Nonvolatiilememoryissalso
calledReadOnlyyMemory(RO
OM).Therearrevarioustyp
pesofROM.
1. Mask ROM
M: Some micrrocontrollers with ROM are
a programm
med while they are still in
n the
factory.ThisROMiscalledMaskROM.Sincethe microcontro
ollerswithMaaskROMare used
for specificc application,, there is no
o need to reeprogram theem. Some tim
mes, this typ
pe of
manufacturringreducestthecostforb
bulkproductio
on.
2. Reprogram
mmable progrram memoryy (or) Erasab
ble PROM (EEPROM):Micrrocontrollers with
EPROMwe
ereintroduced
dinlate1970
0's.Thesedevvicesareelecctricallyprogrrammablebu
utare
erased with UV radiatio
on. The consstruction of a
a EPROM meemory cell is somewhat like a
MOSFETbu
utwithaconttrolandfloatsemiconducttorasshowninthefigure.
Fig4.7StructureofanEPROM
Intheunprrogrammedsstate,the'flo
oat'doesnot haveanychaargeandthe MOSFETisin
nthe
OFF state. To program the cell, thee 'control' ab
bove the 'floaat' is raised to
t a high enough
potentialsu
uchthatachargeleakstothefloatthrroughSiO2inssulatinglayerr.Henceachaannel
is formed between
b
'Sou
urce' and 'Drain' in the silicon substrate and the MOSFET
M
beco
omes
'ON'.Thecchargeinthe 'float'remaiinsforalonggtime(typicaallyover30yyears).Thech
harge
can be rem
moved by exposing the float to UV
V radiation. FFor UV erasaable version,, the
packagingisdoneinace
eramicenclossurewithagllasswindow.
29|P a g e
F
Fig4.8UVeras
sableversiono
ofanEPROM
Usually,theeseversionso
ofmicroconttrollersareexxpensive.
3. OTPEPROM
M:Onetimep
programmable(OTP)EPRO
OMbasedmicrocontrollerrsdonothaveeany
glasswindo
owforUVeraasing.Theseccanbeprograammedonlyo
once.Thistyp
peofpackaging
resultsinm
microcontrolleerthathavethecost10%o
ofthemicroccontrollerswithUVerase
facility(i.e.,1/10thcost).
4. EEPROM:(ElectricallyErrasableProgrrammableRO
OM):Thisissim
milartoEPRO
OMbuttheflo
oat
chargecanberemovedelectrically.
5. FLASH(EEP
PROMMemory):FLASHmemorywasin
ntroducedbyINTELinlate1980's.
Thismemoryissimilarto
oEEPROMbu
utthecellsinaFLASHmem
moryarebussedsothatth
hey
canbeerassedinafewcclockcycles.H
Hencetherep
programmingisfaster.
4.5 OrganizattionofDattaMemory
y
DA
ATAMemorry
Datam
memorycanb
beclassifiedin
ntothefollow
wingcategories
Bits
Registers
VariableRA
AM
Programco
ounterstack
Microccontroller can
n have abilityy to perform
m manipulatio
on of individu
ual bits in ce
ertain registers(bit
manipulation).Thissisauniqueffeatureofam
microcontrolle
er,notavailab
bleinamicro
oprocessor.
Eightb
bitsmakeabyyte.Memorybytesarekno
ownasfilere
egisters.
RegisteersaresomespecialRAMlocationsthaatcanbeacceessedbythep
processorverryeasily.
30|P a g e
Fig4.9StaticRAM(SRAM)m
memorycell
Mmemorycellequivalent
Fig4.10SRAM
ThefiggureofasingleSRAMcellisshownabo
ove.ThisconssistsoftwoCMOSinverterrsconnectedback
tofron
nt,soastoformalatch.
Processsorstacksstore/savethe datainasim
mplewayduringprogram execution.Prrocessorstackisa
partoffRAMareaw
wherethedataissavedinaaLastInFirsttOut(LIFO)faashionjustlikkeastackofp
paper
on a table.
t
Data is stored by executing a 'push' instru
uction and data is read out
o using a 'pop'
instrucction.
I/ORe
egisters:Inad
dditiontothe
eDatamemory,somespecialpurpose registersare requiredthaatare
used in input/outp
put and conttrol operation
ns. These reggisters are ccalled I/O reggisters. Thesee are
importtantformicro
ocontrollerpe
eripheralinteerfaceandcontrolapplicattions.
Hardwareiinterfaceregisters(I/OSppace)
31|P a g e
Aswealreaadyknowam
microcontrolleerhassomeeembeddedpeeripheralsand
dI/Odevicess.The
datatransffertothesed
devicestakesplacethrougghI/Oregisteers.Inamicrroprocessor, input
/output (I/O) devices arre externally interfaced and are mapp
ped either to memory add
dress
(memorym
mappedI/O)o
oraseparateI/Oaddresssspace(I/OmaappedI/O).
In a microccontroller, tw
wo possible architectures can be used i.e., Princeto
on(Von Neum
mann)
architectureandHarvardarchitecturre.
I/ORegisteerspaceinPrincetonarchitecture
InPrincetonarchitecturrewehaveo
onlyonemem
moryinterfaceforprogram
mmemory(R
ROM)
anddatam
memory(RAM
M).Oneoption
nistomapth
heI/ORegisteerasaparto
ofdatamemo
oryor
variable RA
AM area. Thiss architecturee is simple and straight fo
orward. This is called memory
mappedI/O
O.AlternativeelyaseparateeI/Oregisterspacecanbeeassigned.
Fig4.11I/OReggistersinPrinccetonArchiteccture
The drawb
back of mem
mory mapped I/O is that a program which
w
wronggly executed may
overwriteI//Oregisters.
I/ORegiste
erspaceinHaarvardarchiteecture
ThesearetthefollowingoptionsavailableforI/OrregisterspaceeinHarvardA
Architecture.
1. I/OregistersinproggramROM.
2. I/Oregistersinregissterspace(DaataMemoryaarea).
3. I/Oregistersinsepaaratespace.
32|P a g e
Fig4.12O
Organizationo
ofI/OregisterssinHarvardA
Architecture
Thefirstop
ptionissomew
whatdifficultttoimplemen
ntasthereisnomeansto
owritetoprogram
ROM area. It is also complicated to have a sepaarate I/O spacce as shown in (3). Hencee the
secondopttionwhereI/O
Oregistersarreplacedinth
heregistersp
paceiswidelyyused.
4.6 Compiler/IDE(InttegratedD
Developme
entEnvironment)
Atmel Microcontro
ollersareveryyfamousasttheyareveryeasytouse.Therearem
manydevelopment
toolsaavailablefortthem.Firstoffallweneed aneasyIDE fordevelopin
ngcode.Isugggestbeginneersto
useCV
VAVR(CodeV
VisionAVR)Evaluationverrsionisavailaableforfreed
downloadfro
omthewebsiite.It
has lim
mitation of co
ode size. It works
w
on com
mputers with Windows pllatform that is Windows XP &
Vista.
pilers/develop
pmenttoolsssupportingW
WindowsforA
AtmelMicroco
ontrollersaree:
Someffamouscomp
WINAVR(A
AVRGCCforW
Windows)
CodeVision
nAVR(CVAVR
R)
AVRStudio(Atmel'sfreeedevelopingtool)
AVRGC
CCisaveryniiceopensourrcecompilerusedbymosttofthepeoplle.
4.7 Programm
mer
33|P a g e
Programmerbasicallyconsistsoftwoparts:
Software(toopen.hexfileonyourcomputer)
Hardware(toconnectmicrocontroller)
Hardware depends on the communication port you are using on the computer (Serial, Parallel or
USB).Isuggestbeginners touseSerial Programmer asitisvery easytobuild. Software forthatis
PonyProg.SomefamousWindows(XP,Vista)programmersare:
PonyProg(Serial,Parallel)
AVRdude(supportsmanyhardwares)
AVRStudio(supportsAtmel'shardware)
ATProg(Serial)
USBASP(USB)
4.8 HowtouseSerialProgrammer'sCircuit(Hardware)
Thisistheeasiestprogrammercircuittomake.YoujusthavetogetSerialPortconnectorandthree
1Kresistorsandyouaredone!CircuitDiagramisattached.
34|P a g e
NowopenthedatasheetofAtmegayouareusing(IamusingAtmega16).Gotothepin
configurationandfindthefollowingpinsandconnecttheprogrammer.Programmingisdone
throughSPI(SerialPeripheralInterface)whichinvolvesMISO,MOSIandSCKpins.RESETisusedto
resetthechip.0voltonthispinwillresetthechipandfornormalrunningitshouldbepulledupto
+5V.
MOSI(MasterOutSlaveIn)
MISO(MasterInSlaveOut)
SCK(SerialClock)
RESET
GND(Ground)
NowconnectthepowersuppliesthatareVccandGNDtothemicrocontroller.
Vcc=+5VandGND=0V
DonotforgettoconnectResettoVccwitha1K/10Kresistorforpullingup.
Thatisitwearereadywiththehardware.
Note:TheTrainerBoardhasOnBoardSerialProgrammer.
Software
AsItoldyoutherearetwopartsofaprogrammer,hardwareandsoftware.Wecanbuildthis
hardwareasitisveryeasywithjust34components.Nowweneedsoftwarewhichsupportthis
hardwareandcancommunicatewithmicrocontrollerusingthiscircuit.Thereare2goodsoftwares
forWindows.Theyare,
PonyProg
AtProg
BothofthemsupportSerialaswellasParallelport,butIhavealwayspreferredserialportbecauseit
hasonly9pins,henceasmallerconnectorisrequired.
35|P a g e
Nowletusdiscussaboutthem.
AtProg
I consider it as simplest programmer ever. The circuit we discussed is actually based on this
programmer.Downloadthefolderfromthewebsite,unzipit.Ithasanexecutablefilenamedat
prog.exedoubleclicktoexecuteit.
GotoPORTandselecttheaddressofserialport
(bydefaultCOM1).OnceyouclickthatSercon2
detectedshouldappearintheActivitytab.Thatis
thenameoftheprogrammercircuit.
Turnonthepowersupplyandconnectthecircuit
tothemicrocontroller.
ClickonCheck,itshouldshowOKintheActivity
tabanddevicename(ATMEGA16)will
automaticallycomeinthetabbelowcheck
option.Thisistheautodetectoptionofthis
programmerwhichautodetectsthedevicename
connectedbyitssignature.
Nowjustopenthedevicefilefrom File>Open andclickonWrite.Itwillwriteandverifythe
program.Done!Sosimpleisntit?:)
PonyProg
OneofthemostcommonlyusedprogrammersonWindows.Downloaditfromthewebsiteand
installit.Nowletssetitupforourhardware.
FirstselectAVRmicroandAVRAuto(youcanalsospecifydevicename,Atmega16)inthechip
options(lasttwodropdowntabs)
36|P a g e
GototheSetup>InterfaceSetup.Thendothesettingsasshowninthepicturebelow.Then
connectthecircuittothemicrocontroller,turnonthepowersupply. NowclickonProbe.You
shouldgetTestOKmessage.Ifnot,checkyourconnectionsagain.
Now lets read the Microcontroller. Go to Command>Read All. It should start reading the
signatureandtheflashmemory.YoushouldgetReadSuccessfulmessageafterthat.
Sowearedonewiththesettingsandtestings.Everythingisworkingfine:)Nowjustopenthe
hexfilefromFile>OpenDeviceFile
37|P a g e
Go to Command>WriteProgram (Flash). It will start writing and then verifying the code.
Congratulations:)youdidit!
4.9 USBProgrammer
USBaspisaUSBincircuitprogrammerforAtmelAVRcontrollers.ItsimplyconsistsofanATMega48
or an ATMega8 and a couple of passive components. The programmer uses a firmwareonly USB
driver;nospecialUSBcontrollerisneeded.
Chapter5 CodeVisionAVR(CVAVR)
38|P a g e
AnIDEhasfollowingfunctions:
Preprocessing
Compilation
Assembly
Linking
ObjectTranslation
TextEditor
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. Thats
calledanIntegratedDevelopmentEnvironment,inshortIDE.
I consider CodeVisionAVR to be the best IDE for getting started with AVR programming on
WindowsXP,Vista.IthasaverygoodCodeWizardwhichgeneratecodesautomatically!Youneed
notmesswiththeassemblywords.SoinallmytutorialsIwillbeusingCVAVR.Youcandownload
evaluationversionforfreewhichhascodesizelimitationbutgoodenoughforourpurpose.
For all my examples I will be using Atmega16 as default microcontroller because it very easily
available and is powerful enough with sufficient number of pins and peripherals we use. You can
havealookonthedatasheetofAtmega16inthedatasheetsection.
Letstakealookonthesoftware.Themainwindowlookslikefollowing,
NowclickonFile>New>Project
39|P a g e
ApopupwindowwillcomeaskingwhetheryouwanttouseCodeWizardAVR,obviouslyselectyes
becausethatisthereasonweareusingCVAVR!
NowhavealookonthisWizard.IthasmanytabswherewecanconfigurePORTS,TIMERS,LCD,ADC
etc.Iamexplainingsomeofthem
5.1 CHIP:
Select the chip for which you are going to write the program. Then select the frequency at which
Chipisrunning.BydefaultallchipsaresetonInternalOscillatorof1MHzsoselect1MHzifthatis
thecase.Ifyouwanttochangetherunningclockfrequencyofthechipthenyouhavetochangeits
fusebits(Iwilltalkmoreaboutthisinfusebitssection).
5.2
40|P a g e
PORT:
PORTisusuallyacollectionof8pins.
From this tab you can select which pin you want to configure as output and which as input. It
basicallywritestheDDRandPORTregisterthroughthissetting.RegistersarebasicallyRAMlocations
whichconfigurevariousperipheralsofmicrocontrollerandbychangingvalueoftheseregisterswe
can change the function it is performing. I will talk more about registers later. All the details are
providedinthedatasheet.
Soyoucanconfigureanypinasoutputorinputbyclickingthebox.
ForAtmega16whichhas4Portswecansee4tabseachcorrespondingtoonePort.Youcanalsoset
initialvalueofthePinsyouwanttoassign.orifyouareusingapinasinputthenwhetheryouwant
tomakeitaspulluportristated,againIwilltalkindetailsaboutthesefunctionslater.
SimilarlyusingthiscodewizardyoucanveryeasilyconfigurealltheperipheralsontheAtmega.
NowforgeneratingcodejustgotoFile>Generate,SaveandExit(ofthecodewizard)
41|P a g e
Nowitwillaskyounameandlocationforsavingthreefiles.Twobeingprojectfilesandonebeing
the .C filewhich isyour program.try to keep same names ofallthreefiles to avoidconfusion. By
defaultthesefilesaregeneratedinC:\CVAVR\bin
Thegeneratedprogramwillopeninthetexteditor.HavealookithassomedeclarationslikePORT,
DDR,TCCR0 and many more.These are allregisterswhich configuresvariousfunctions ofAtmega
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
startwritingourpartofprogramjustbeforethewhileloop.Andasformostoftheapplicationswe
wantmicrocontrollertoperformthesametaskforeverweputourpartofcodeintheinfinitewhile
loopprovidedbythecodewizard!
While
{
//Placeyourcodehere
(1)
};
}
Seehowfriendlythiscodewizardis,allthework(configuringregisters)automaticallydoneandwe
dontevenneedtounderstandandgotothedetailsaboutregisterstoo!
Nowwewanttogeneratethehexfile,sofirstcompiletheprogram.EitherpressF9orgotoProject
>Compile.
Itwillshowcompilationerrorsifany.Ifprogramiserrorfreewecanproceedtomakingofhexfile.
SoeitherpressShift+F9orgotoProject> Make.Apopupwindowwillcomewithinformation
aboutcodesizeandflashusageetc.
Sothemachinefileisreadynow!Itisinthesamefolderwherewesavedthose3files.
42|P a g e
Chap
pter6 Introductio
ontoAtm
mega16Microcontrroller
6.1 Features
AdvancedR
RISCArchitectture
Upto16M
MIPSThroughp
putat16MHzz
16KByteso
ofInSystemSSelfProgrammableFlash
512BytesEEEPROM
1KByteInte
ernalSRAM
32Program
mmableI/OLines
InSystemP
ProgramminggbyOnchipB
BootProgram
m
8channel,10bitADC
Two8bitTTimer/CounteerswithSeparratePrescalersandCompaareModes
One16bitTimer/CountterwithSeparatePrescaler,CompareM
Mode,andCapture
FourPWMChannels
ProgrammaableSerialUSSART
Master/SlaveSPISerialIInterface
ByteorienttedTwowireSerialInterfaace
ProgrammaableWatchdo
ogTimerwith
hSeparateOn
nchipOscillattor
Externalan
ndInternalIntterruptSourcces
6.2 PinConfig
guration
43|P a g e
6.3 BlockDia
agram
44|P a g e
6.4 PinDescriptions
VCC:Digitalsupplyvoltage.(+5V)
GND:Ground.(0V)Notethereare2groundPins.
PortA(PA7PA0)
PortAservesastheanaloginputstotheA/DConverter.PortAalsoservesasan8bitbidirectional
I/O port, if the A/D Converter is not used. When pins PA0 to PA7 are used as inputs and are
externallypulledlow,theywillsourcecurrentiftheinternalpullupresistorsareactivated.ThePort
Apinsaretristatedwhenaresetconditionbecomesactive,eveniftheclockisnotrunning.
PortB(PB7PB0)
PortBisan8bitbidirectionalI/Oportwithinternalpullupresistors(selectedforeachbit).PortB
also serves the functions of various special features of the ATmega16 as listed on page 58 of
datasheet.
PortC(PC7PC0)
PortCisan8bitbidirectionalI/Oportwithinternalpullupresistors(selectedforeachbit).PortC
alsoservesthefunctionsoftheJTAGinterfaceandotherspecialfeaturesoftheATmega16aslisted
on page 61 of datasheet. If the JTAG interface is enabled, the pullup resistors on pins PC5(TDI),
PC3(TMS)andPC2(TCK)willbeactivatedevenifaresetoccurs.
PortD(PD7PD0)
PortDisan8bitbidirectionalI/Oportwithinternalpullupresistors(selectedforeachbit).PortD
also serves the functions of various special features of the ATmega16 as listed on page 63 of
datasheet.
RESET:ResetInput.Alowlevelonthispinforlongerthantheminimumpulselengthwillgeneratea
reset,eveniftheclockisnotrunning.
XTAL1:Externaloscillatorpin1
XTAL2:Externaloscillatorpin2
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
throughalowpassfilter.
AREF:AREFistheanalogreferencepinfortheA/DConverter.
45|P a g e
6.5 DigitalInputOutputPort
SoletsstartwithunderstandingthefunctioningofAVR.WewillfirstdiscussaboutI/OPorts.AgainI
remind you that I will be using and writing about Atmega16. Lets first have a look at the Pin
configurationofAtmega16.Imageisattached,clicktoenlarge.
Youcanseeithas32I/O(Input/Output)pinsgroupedasA,B,C&Dwith8pinsineachgroup.This
groupiscalledasPORT.
PA0PA7(PORTA)
PB0PB7(PORTB)
PC0PC7(PORTC)
PD0PD7(PORTD)
Noticethatallthesepinshavesomefunctionwritteninbracket.Theseareadditionalfunctionthat
pincanperformotherthanI/O.Someofthemare.
ADC(ADC0ADC7onPORTA)
UART(Rx,TxonPORTD)
TIMERS(OC0OC2)
SPI(MISO,MOSI,SCKonPORTB)
ExternalInterrupts(INT0INT2)
6.6 Registers
Alltheconfigurationsinmicrocontrollerissetthrough8bit(1byte)locationsinRAM(RAMisabank
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
functioningofmicrocontroller.Therearetotal32x8bitregistersinAtmega16.AsRegistersizeof
thismicrocontrolleris8bit,itcalledas8bitmicrocontroller.
46|P a g e
Chapter7 I/OPorts:
InputOutputfunctionsaresetbyThreeRegistersforeachPORT.
DDRX>SetswhetherapinisInputorOutputofPORTX.
PORTX>SetstheOutputValueofPORTX.
PINX>ReadstheValueofPORTX.
Gotothepage50inthedatasheetoryoucanalsoseetheI/OPortstabintheBookmarks.
7.1 DDRX(DataDirectionRegister)
Firstofallweneedtosetwhetherwewantapintoactasoutputorinput.DDRXregistersetsthis.
EverybitcorrespondstoonepinofPORTX.LetshavealookonDDRAregister.
Bit
PIN
PA7
PA6
PA5
PA4
PA3
PA2
PA1
PA0
NowtomakeapinactasI/OwesetitscorrespondingbitinitsDDRregister.
TomakeInputsetbit0
TomakeOutputsetbit1
IfIwriteDDRA=0xFF(0xforHexadecimalnumbersystem)thatissettingallthebitsofDDRAtobe
1,willmakeallthepinsofPORTAasOutput.
SimilarlybywritingDDRD=0x00thatissettingallthebitsofDDRDtobe0,willmakeallthepinsof
PORTDasInput.
Nowletstakeanotherexample.ConsiderIwanttosetthepinsofPORTBasshownintable,
PORTB
PB7
PB6
PB5
PB4
PB3
PB2
PB1
PB0
Function
Output
Output
Input
Output
Input
Input
Input
Output
DDRB
ForthisconfigurationwehavetosetDDRBas11010001whichinhexadecimalisD1.Sowewillwrite
DDRB=0xD1
Summary
DDRX>tosetPORTXasinput/outputwithabyte.
DDRX.y>tosetythpinofPORTXasinput/outputwithabit(worksonlywithCVAVR).
47|P a g e
7.2 PORTX(PORTXDataRegister)
ThisregistersetsthevaluetothecorrespondingPORT.NowapincanbeOutputorInput.Solets
discussboththecases.
OutputPin
Ifapinissettobeoutput,thenbysettingbit1wemakeoutputHighthatis+5Vandbysettingbit0
wemakeoutputLowthatis0V.
Letstakeanexample.ConsiderIhavesetDDRA=0xFF,thatisallthepinstobeOutput.NowIwant
tosetOutputsasshownintable,
PORTA
Value
PA7
PA6
PA5
PORTA
PA4
Low(0V)
0
PA3
PA2
PA1
PA0
For this configuration we have to set PORTA as 11000110 which in hexadecimal isC6. So we will
writePORTA=0xC6;
InputPin
If a pin is set to be input, then by setting its corresponding bit in PORTX register will make it as
follows,Setbit0>TriStatedSetbit1>PullUp
Tristatedmeanstheinputwillhang(nospecificvalue)ifnoinputvoltageisspecifiedonthatpin.
PullUpmeansinputwillgoto+5Vifnoinputvoltageisgivenonthatpin.Itisbasicallyconnecting
PINto+5Vthrougha10KOhmresistance.
Summary
PORTX>tosetvalueofPORTXwithabyte.
PORTX.y>tosetvalueofythpinofPORTXwithabit(worksonlywithCVAVR)
7.3 PINX(DataReadRegister)
ThisregisterisusedtoreadthevalueofaPORT.IfapinissetasinputthencorrespondingbitonPIN
registeris,
0forLowInputthatisV<2.5V
1forHighInputthatisV>2.5V(Ideally,butactually0.8V2.8Viserrorzone!)
ForanexampleconsiderIhaveconnectedasensoronPC4andconfigureditasaninputpinthrough
DDRregister.NowIwanttoreadthevalueofPC4whetheritisLoworHigh.SoIwilljustcheck4th
bitofPINCregister.
We can only read bits of the PINX register; can never write on that as it is meant for reading the
valueofPORT.
Summary
48|P a g e
PINX>ReadcompletevalueofPORTXasabyte.
PINX.y>ReadythpinofPORTXasabit(worksonlywithCVAVR).
7.4 ASMALLNOTEABOUTDELAY
Chasinbuiltlibrarieswhichcontainmanyprebuiltfunctions.OnesuchfunctionisDelay,which
introducesatimedelayataparticularstep.Toinvokeitinyourprogram,youneedtoaddthe
followinglineatthebeginningofyourcode:
#include<delay.h>;
Thereafter,itcanbeusedintheprogrambyaddingthefollowingline:
delay_ms(X);
WhereXisthetimedelayyouwishtointroduceatthatparticularstepinmilliseconds.
IhopeyoumusthavegotbasicideaaboutthefunctioningofI/OPorts.Fordetailedreadingyoucan
alwaysrefertodatasheetofAtmega.
49|P a g e
Chapter8 LCDInterfacing
NowweneedtointerfaceanLCDtoourmicrocontrollersothatwecandisplaymessages,outputs,
etc.SometimesusinganLCDbecomesalmostinevitablefordebuggingandcalibratingthesensors
(discussed later). We will use the 16x2 LCD, which means it has two rows of 16 characters each.
Henceintotalwecandisplay32characters.
8.1 OverviewofLCDDisplay
LCD displays are widely used in many applications like mobile phones, robotics, DVD players,
Measurement instruments etc. Intelligent LCD displays are very capable because they can display
complete ASCII character set and even graphics. These displays are easily connected with micro
controller and microprocessors. LCD displays are complete embedded system in them, because it
includemicrocontroller,RAMandROM.
16X2LCDDISPLAY
LCDModulescanpresenttextualinformationtouser.Itslikeacheapmonitorthatyoucanhook
inallofyourgadgets.
Theycomeinvarioustypes.Themostpopularoneis16x2LCDmodule.Ithas2rows&16columns.
Theintelligentdisplaysaretwotypes:
a)TextDisplay
b)GraphicsDisplay
Text display can display all character set and graphics display can show anyGraphics because they
areinterfacedpixelwise.
In recent year the LCD is finding widespread use replacing LEDs (seven segment LEDs or
multisegmentLEDs).
Thisisduetothefollowingreasons:
a)ThedecliningpricesofLCDs.
b)Theabilitytodisplaythenumbers,charactersandgraphics.ThisisnotpossibleinLEDs,whichcan
displaythenumbersandfewcharacters.
c)Incorporation of a refreshing controller into the LCD, Thereby reliving the CPU of the task of
refreshingtheLCD.Incontrast,theLEDmustberefreshedbytheCPU(orinsomeotherway)tokeep
displayingthedata.
TheinterfacingofLCDisquitedifficult.Butwewilltrytomakeitsimpleandletusexplainitforyou.
We will learn how to interface the text intelligent LCD display. These displays are available in the
marketof16columnandoneRowandmorethanonerowdisplays.
BlockDiagramofLCDDisplay
50|P a g e
Micro
DataRAM
Code
controller
RAM
MICROCONTROLLER:
ItisthebrainofLCDdisplay.ThisishandlingtheallworkingoftheLCD.
Data
Command
Busy
Register
Register
DATARAM:
ROM
ThisRAMisstoringtheASCIIvaluesofcorrespondingcharacterswhichwillbedisplayedontheLCD.
For each column there is one location in the RAM. When we will store the ASCII value at that
locationthanitscorrespondingcharacterwillbedisplayedonthescreen.
CODERAM:
ThisRAMstoresthebinarypatternaccordingtothecharacter.
ROM:
ThisROMstoresthebinarypatternwhichisaccordingtothePixelsofLCDandtherearepatternsof
everycharacter.
COMMANDREGISTER:
Itstoresvariouscommandsforproperfunctioning.
DATAREGISTER:
This register work as buffer for data lines and the internal buses of LCD. The ASCII values of
characterswillbegiventothedataregister.
BF(BUSYFLAG):
ItindicatestheinternalworkingoftheLCD.ItshowwhetherLCDisbusyinanyoperationornot.
IfBF=0(LCDisidlewecanproceedfornextoperation)
If BF=1 (LCD is busy we cannot proceed for next operation and we have to wait unless operation
completes).
DESCRIPTIONOFPINSISGIVENBELOW:
VCC,VSSandVO:
WhileVCCandVSSprovide+5Voltsandground,respectivelyVEEisusedforcontrollingLCDcontrast
RS(REGISTERSELECT):
TheRSpinisusedtoselectDataRegisterorCommandRegister.
51|P a g e
IfRS=0
0,CRRegisterrisselected,allowingthe usertosend
dacommandsuchascleardisplay,cursserat
theho
omeetc.
IfRS=1
1,DRRegisterrisselected,allowingtheusertosenddatatobedissplayontheLCD.
R/W(R
READ/WRITEE):
WhenR/W=0,Writeoperation..
WhenR/W=1ReadOperation
EN(EN
NABLE):
The En
nable pin is used by the LCD to latch binary bitss available on
n its data pins. When daata is
supplieed to data pins,
p
a negatiive edge is applied
a
to thiis pin So thaat the LCD latches in the data
presen
ntatthedatapins.Thispu
ulsemustbeaaminimumoff450nswidee.
Thereshouldbepo
ositiveedgeattENpinwhen
nreadoperattionisrequireed.
0:
D7D0
Thisis8bitdatapins.D7D0arreusedtoseendinformatiiontotheLC
CDorreadth
hecontentso
ofthe
LCDsiinternalregisters.
BKLED
D(LEDA,LEDK
K):
These pinsareusedtogivetheesupplytoth
hebacklight oftheLCDd
display.So,th
hatcontento
ofthe
LCDdisplaycanbeviewedintheedark.
8.2 CircuitCo
onnection
Thereare16pinsin
nanLCD;SeeereversesideoftheLCDfo
orthePINcon
nfiguration.
Theco
onnectionshaavetobemad
deasshownb
below:
Figu
ure14:LCDconn
nections
8.3 Settingup
pinMicroccontrollerr
andselectthePORTatwhichyou wanttoconnecttheLCD.WewillselectPORTC.Alsoselectthe
numberofcharactersperlineinyourLCD.Thisis16inourcase.CodeWizardnowshowsyouthe
completelistofconnectionswhichyouwillhavetomakeinordertointerfacetheLCD.Theseare
nothingbutthesameasintheabovefigureforgeneralPORTX.
Figure15:LCDsettingsonCVAVRwizardwindow.
Asyoucansee,therearesomespecialconnectionsotherthanthosetouC,Vccandgnd.Theseare
general LCD settings. Pin 3 (VO) is for the LCD contrast, ground it through a <1k resistance/
potentiometerforoptimumcontrast.Pin15&16(LEDAandLEDK)areforLCDbacklight,givethem
permanent+5VandGNDrespectivelyasweneedtoglowitcontinuously.
53|P a g e
8.4 PrintingFunctions
Now once the connections have been made, we are ready to display something on our screen.
Displayingournamewouldbegreattostartwith.SomeofthegeneralLCDfunctionswhichyoumust
knoware:
8.4.1 lcd_clear()
Clearsthelcd.Remember!Callthisfunctionbeforethewhile(1)loop,otherwiseyouwontbeable
toseeanything!
8.4.2 lcd_gotoxy(x,y)
Place the cursor at coordinates (x,y) and start writing from there. The first coordinate is (0,0).
Hence,xrangesfrom0to15andyfrom0to1inourLCD.Supposeyouwanttodisplaysomething
startingfromthe5thcharacterinsecondline,thenthefunctionwouldbe
lcd_gotoxy(5,1);
8.4.3 lcd_putchar(charc)
Todisplayasinglecharacter.E.g.,
lcd_putchar(H);
8.4.4 lcd_putsf(constantstring)
Todisplayaconstantstring.Eg,
lcd_putsf(IITKanpur);
8.4.5 lcd_puts(chararr)
To display a variable string, which is nothing but an array of characters (data type char) in C
language . e.g., You have an array char c[10] which keeps on changing. Then to display it, the
functionwouldbecalledas
lcd_puts(c);
Nowwehaveseenthatonlycharactersorstrings(constantorvariable)canbedisplayedontheLCD.
Butquiteoftenwehavetodisplayvaluesofnumericvariables,whichisnotpossibledirectly.Hence
we need to first convert that numeric value to a string and then display it. For e.g., if we have a
variableoftypeinteger,sayintk,andweneedtodisplaythevalueofk(whichchangeseverynow
andthen,200nowand250afterasecond...andsoon).Forthis,weusetheCfunctionsitoa()and
ftoa(),butremembertoincludetheheaderfilestdlib.htousetheseCfunctions.
54|P a g e
8.4.6 itoa(intval,chararr[])
Itstoresthevalueofintegervalinthecharacterarrayarr.E.g.,wehavealreadydefinedintiand
charc[20],then
itoa(i,c);
lcd_puts(c);
Similarlywehave
8.4.7 ftoa(floatval,chardecimal_places,chararr[])
Itstoresthevalueoffloatingvariablefinthecharacterarrayarrwiththenumberofdecimalplaces
asspecifiedbysecondparameter.E.g.,wehavealreadydefinedfloatfandcharc[20],then
ftoa(f,4,c);
//till4decimalplaces
lcd_puts(c);
NowwearereadytodisplayanythingwewantonourLCD.Justtryoutsomethingwhichyouwould
liketoseeglowingonit!
55|P a g e
Most of the physical quantities around us are continuous. By continuous, we mean that the
quantitycantakeanyvaluebetweentwoextremes.Forexample,theatmospherictemperaturecan
take any value within a certain range. If an electrical quantity is made to vary directly in
proportiontothisvaluethenwhatwehaveisanAnalogueSignal.Nowwehavebroughtaphysical
quantityintotheelectricaldomain.Theelectricalquantityinmostcasesisvoltage.Tobringthis
quantityintodigitaldomainwehavetoconvertthisintodigitalform.ForthisanADCoranalogue
todigitalconverterisneeded.MostmodernMCUincludingAVRshaveanADConchip.
AnADCconvertsaninputvoltageintoanumber.AnADChasaresolution.A8bitADChasarange
of0255.(28=256)TheADCalsohasaReferenceVoltage(ARef).WhentheinputvoltageisGNDthe
outputis0andwhentheinputvoltageisequaltoAReftheoutputis255.Sotheinputrangeis0to
ARefandtheoutputrangeis0to255.
InputVoltage
DigitalOutput
0V0
2.5V127
5V255
Youcanseethatanyanaloguesignalisnotperfectlyconvertedafactorthataffectsthe
outputqualityisthesamplingrate.TheADCcannotcontinuouslyreadtheinputsignaland
changeitsoutputitdoessoincertaintimeintervals.Thefrequencyatwhichitsamplesthe
inputiscalleditssamplingrate.
Also,thevalueoftheanaloguesignalreadisnotstoredperfectlyforexample,avoltage
of2.501wouldbereadas2.5Vi.e.127indigitalformat.Thus,thesignalisquantized,or,
inotherterms,thereiscertaingraininesstothedigitalsignalthatyouobtain.Howaccurateyour
digital signal isdepends on your resolution higher resolution will make your digital signal more
accurate.
56|P a g e
9.1 Theoryoffoperation
n
What we have seen till nowthat theinput given to uC wasdigital, i.e., either +5
5 V(logic 1)o
or0V
(logic0
0).Butwhatiifwehavean
nanaloginputt,i.e.,valuevvariesoverarange,say0V
Vto+5V?Theenwe
require
eatoolthat convertsthissanalogvoltaagetodiscrettevalues.AnaalogtoDigitaalConverter((ADC)
issuch
hatool.
uswehave8
8pinsavailab
blewherewecanapplyan
nalog
ADCissavailableat PORTAofAttmega16.Thu
voltage
e and get co
orresponding digital values. The ADC register
r
is a 10
1 bit registe
er, i.e., the digital
d
valuerrangesfrom0
0to1023.Bu
utwecanalso
ouseonly8b
bitoutofit(0
0to255)asto
oomuchpreccision
isnotrrequired.
Refereencevoltage isthevoltageetowhichth
heADCassign
nsthemaxim
mumvalue(25
55incaseof 8bit
and 10
023 for 10 bit). Hence, th
he ADC of Attmega16 divides the inpu
ut analog volttage range (0
0V to
Refereence Voltage)) into 1024 or
o 256 equal parts, depen
nding upon w
whether 10 bit
b or 8 bit ADC is
used. Forexample,iftherefere
encevoltageiis5Vandwe use10bitAD
DC,0Vhasdiggitalequivaleent0,
+5Visdigitally1023
3and2.5Visapproximatelyequalto51
12.
ADC=Vinnx255/Vreff
(8bit)
ADC=Vinnx1023/Vrref(10bit)
9.2 Settingup
pMicrocon
ntroller
57|P a g e
ToenableADCinAtmega16,clickontheADCtabinCodeWizardandenablethecheckbox.Youcan
alsocheckuse8bitsasthatissufficientforourpurposeand10bitaccuracyisnotrequired.Ifthe
inputvoltagerangesfrom0tolessthan+5V,thenapplythatvoltageatAREF(pin32)andselectthe
Volt.Ref.asAREFpin.Butifitrangesfrom0to+5V,youcanselecttheVolt.Ref.asAVCCpinitself.
Keeptheclockatitsdefaultvalueof125kHzandselecttheAutoTriggerSourceasFreeRunning.
Youcanalsoenableaninterruptfunctionifyourequire.
9.3 FunctionforgettingADC
Nowwhenyougenerateandsavethecode,alltheregistervaluesaresetautomaticallyalongwitha
function:
unsignedcharread_adc(unsignedcharadc_input).
ThisfunctionreturnsthedigitalvalueofanaloginputatthatpinofPORTAwhosenumberispassed
asparameter,e.g.,ifyouwanttoknowthedigitalvalueofvoltageappliedatPA3,andthenjustcall
thefunctionas,
read_adc(3);
IftheADCis8bit,itwillreturnavaluefrom0to255.MostprobablyyouwillneedtoprintitonLCD.
So,thecodewouldbesomewhatlike
inta;charc[10];
//declareinthesectionofglobalvariables
a=read_adc(3);
itoa(a,c);
lcd_puts(c);
58|P a g e
Chapter10 Timers
10.1 WhatisaTimer?
Weusetimerseverydaythesimplestonecanbefoundonyourwrist.Asimpleclockwilltimethe
seconds,minutesandhourselapsedinagivendayorinthecaseofatwelvehourclock,sincethe
lasthalfday.AVRtimersdoasimilarjob,measuringagiventimeinterval.
AnAVRtimerinsimplesttermisaregister.Timersgenerallyhavearesolutionof8or16bits.Soan8
bittimeris8bitswide,andiscapableofholdingvaluewithin0255.Butthisregisterhasamagical
propertyitsvalueincreases/decreasesautomaticallyatapredefinedrate(suppliedbyuser).Thisis
thetimerclock.AndthisoperationdoesnotneedCPUsintervention.
TheAVRtimersareveryusefulastheyrunasynchronoustothemainAVRcore.Thisisafancywayof
sayingthatthetimersareseparatecircuitsontheAVRchipwhichcanrunindependentofthemain
program,interactingviathecontrolandcountregisters,andsomethingcalledtimerinterrupts.
10.2 HowtoUseTimer
SinceTimerworksindependentlyofCPUitcanbeusedtomeasuretimeaccurately.Timer
uponcertainconditionstakessomeactionautomaticallyorinformsCPU.Asweknowatimerisan
8bitregisterthatkeepsonincreasingitsvalue,sooneofthebasicconditionsisthesituationwhen
timerregisterOVERFLOWSi.e.ithascounteduptoitsmaximumvalue(255for8BITtimers)and
rolledbackto0.InthissituationtimercanissueaninterruptandyoumustwriteanInterrupt
ServiceRoutine(ISR)tohandletheevent.TherearethreedifferenttimersavailableinAtmega16
andallthetimersworkinalmostsameway.TheyareTIMER0,TIMER1andTIMER2.
10.3 Prescalar
The Prescalar is a mechanism for generating clock for timer by CPU clock. Every CPU has a clock
sourceandthefrequencyofthissourcedecidestherateatwhichinstructionsareexecutedbythe
processor.Atmegahasclocksofseveralfrequenciessuchas1MHz,8MHz,12MHz,16MHz(max).
The Prescalar is used to divide this clock frequency and produce a clock for TIMER. The
Prescalarcanbesettoproducethefollowingtypesofclocks:
NoClock(Timerstop)
Noprescaling(clockfrequency=CPUfrequency)
FCPU/8
FCPU/64
FCPU/256
FCPU/1024
Externalclock,however,itwillrarelybeused.
59|P a g e
10.4 TimerMode
Timersareusuallyusedinoneofthefollowingmodes:
Normal
CTC
FastPWM
PhasecorrectPWM
10.5 NormalMode
Atimerrunninginnormalmodewillcountuptoitsmaximumvalue.Whenitreachesthis
maximumvalue,itissuesanOverflowinterruptandresetsthevalueofthetimertoits
originalvalue.
Intheabovecase,youcanseethatthetimeperiodis256timesthetimeperiodoftheclock.255
clockcyclesarerequiredtoattainthemaximumvalueandoneclockcycletoclearthetimervalue.
So,ftimer=fclock/256
10.6CTCMode
Hereweshallseehowtouseatimerincomparemode.Inthenormalmode,wesettheclockofthe
timer using a prescalar and the let the timer run. When it overflowed, we set up an interrupt to
handletheoverflow.Whilesimple,thismodehasitslimitations.Weareconfinedtoaverysmallset
ofvaluesoffrequencyforthetimer.Thislimitationisovercomebythecomparemode.
ComparemodemakesuseofaregisterknownastheOutputCompareRegisterwhichstoresavalue
ofourchoice.Thetimercontinuouslycomparesitscurrentvaluewiththevalueontheregisterand
whenthetwovaluesmatch,thefollowingeventscanbeconfiguredtohappen:
1. ArelatedOutputComparepincanbemadeset(puttohigh),cleared(puttolow)ortoggled
automatically.Thismodeisidealforgeneratingsquarewavesofdifferentfrequency.
2. ItcanbeusedtogeneratePWMsignalsusedtoimplementaDACdigitaltoanalogconverter
whichcanbeusedtocontrolthespeedofDCmotors.
3. Simplygenerateandinterruptandcallahandler.
Onacomparematch,thetimerresetsitselfto0.ThisiscalledCTCClearTimeronCompareMatch.
In this case, suppose we set our event to toggle the output pin. In that case, the output pin will
remainhighforonetimeperiodofthetimerandwillremainlowforanothertimeperiod.
So,tout=2*ttimer
Fromthenormalcase,wecandrawananalogytofindoutttimer.
ttimer=tclock*(OCR+1)
60|P a g e
So,finally,wehavethefrequencyas,
fout=fclock/(2*(OCR+1))
10.7PulseWidthModulation(PWM)Mode
A digital device like a microcontroller can easily work with inputs and outputs that have only two
statesonoroff.SoyoucaneasilyuseittocontrolaLED'sstatei.e.onoroff.Inthesamewayyou
canuseittoturnonoroffanyelectricaldevicebyusingproperdrivers(transistor,triac,relays
etc).Butsometimesyouneedmorethanjust"on"&"off"controloverthedevice.Forexample,if
youwanttocontrolthebrightnessofanLED(oranylamp),orthespeedofDCmotor,thendigital
on/offsignalswillnotsuffice.Thissituationisverysmartlyhandledbyatechniquecalledas PWM
orPulseWidthModulation.
PWMisthetechniqueusedtogenerateanalogsignalsfromadigitaldevicelikeaMCU.
(A)PWM:PulseWidthModulation
Amicrocontrollercanonlygeneratetwolevelsonitsoutputlines,HIGH=5VandLOW=0V.Butwhat
if we want to generate 2.5V or 3.1V or any voltage between 05 volt as output? For these
requirements,insteadofgeneratingaconstantDCvoltageoutputwegenerateasquarewave,which
hashigh=5VandLow=0V.
AtermcalledasDutyCycleisdefinedas
d=ton/ttotal*100%
So you can see that the duty cycle in the above case is 50%. If the frequency of such a wave is
sufficientlyhigh (say500Hz)thentheoutputyou getishalfof5Vi.e.2.5V.Thusif thisoutputis
connected to a motor (by means of suitable drivers) it will run at 50% of its full speed at 5V. The
PWM technique utilizes this fact to generate any voltage between two extremes (for example
between012volts).Thetrickistovarythedutycyclebetween0to100%andgetsamepercentage
ofinputvoltagetooutput.
Considerthefollowingexamples:
61|P a g e
Herethedutycycleis75%.Sotheequivalentanalogvoltageoutputis3.75V.
Herethedutycycleis12.5%.Sotheanalogvoltageoutputis0.625V.
(B)PWMSignalGenerationUsingAvrTimers
InAVRmicrocontrollers,PWMsignalsaregeneratedbytimers.Therearetwomethodsbywhichyou
cangeneratePWMfromtimers:
1.FastPWM
2.PhaseCorrectPWM
Thesewillbeclearasweproceed.
Wewillusethesimplesttimer,TIMER0forPWMgeneration.Sowehavean8bitcountercounting
from0to255andthenresettingto0andsoon.Thiscanbeshownongraphas:
62|P a g e
The period depends upon the PRESCALAR settings. Now for PWM generation from this count
sequenceOCR0(OutputCompareRegisterZero)isused(ZerobecauseitisforTIMER0andthereare
moreoftheseforTIMER1&TIMER2).Wecanstoreanyvaluebetween0255inOCR0,saywestore
64inOCR0thenitwouldappearinthegraphasfollows(theREDline).
WhentheTIMER0isconfiguredforfastPWMmode,then,whilethetimeriscountingup,whenever
thevalueofTIMER0countermatchesthevalueintheOCR0register,anoutputPINispulledlow(0)
andwhencountingsequencebeginagainfrom0itisSETagain(pulledhigh=VCC).Thisisshownin
thefigure3.ThisPINisnamedOC0andyoucanfinditinthePINconfigurationofATmega32.
63|P a g e
Fromthefigure,youcanseethatawaveofdutycycleof64/256=25%isproducedbysettingOCR0
to64.YoucansetOCR0toanyvalueandgetaPWMofdutycycleof(OCR0/256).Whenyousetit
to0yougeta0%dutycyclewhilesettingitto255willgiveyoua100%dutycycleoutput.Thusby
varyingdutycycleyoucangetananalogvoltageoutputfromtheOC0PIN.
In the inverting mode the value of the OC0 pin is just the reverse of that in the above figure. So
wheneverthevalueoftheTIMER0counterislessthanOCR0valuethentheOC0pinisLOWelseitis
HIGH.Youcanselect the invertingor noninverting mode in the Outputfieldin theCodeWizard
AVR.Theinvertingandnoninvertingmodeswillhavedifferentdutycycleswhicharerelatedas
dinv+dnoninv=100%
Youcanseethat
tout=ttimer=256*tclock
Hence,
fout=fclock/256
(C)PhaseCorrectPWMMode
This mode is very similar to the Fast PWM mode except that whenever the value of the timer
reachesitsmaximumvaluetheninsteadofclearingthevalueofthetimeritsimplystartscounting
down.
ThevalueofthepintogglesonlywhenthevalueoftheOCR0matcheswiththeTIMER0counter.
64|P a g e
Here,
tout=ttimer=256*tclock*OCR
Hence,
fout=fclock/(2*OCR)
TimerscanbeconfiguredintheCodeWizardAVRwindowwhilesettingupanewproject.Tosetupa
timer,followtheseinstructions:
65|P a g e
OpenCodeVisionAVRandclickonFile>New.
Thewindowshownintheabovefigurewillappear.ClickonYes.
OntheCodeWizardAVRwindow,selectyourchipandfrequency.
ClickontheTimerstabonthetop.
10.8SETTINGUPTIMERSINCODEVISIONAVR
The window will allow you to configure TIMER0, TIMER1, TIMER2. For now, you can ignore the
Watchdogtimer.
66|P a g e
TheClockSourcemenuwillallowyoutoselecttheclocksourceforthecurrenttimeryou
can either select the system clock or an external clock. For most purposes, you can select
SystemClock.
TheClockValuemenuwillallowyoutosetthefrequencyoftheclockofthetimer.Select
theappropriatevalue:
SelectthetimermodeintheModemenu:
IntheOutputmenu,selecttheappropriateoptionforyourtimer.Thismenuwillhavedifferent
optionsdependinguponyourtimermode,eg.Toggle,Set,ResetandInverting,NonInverting,etc.:
67|P a g e
YoucanselecttoenableOverflowInterruptandCompareMatchInterruptbyselectingthe
appropriatecheckboxes.
TheTimerValueoptionwillallowyoutoselectthestartingvalueofthetimer.Thedefault
valueis0.
TheCompareValueoptionwillallowyoutoselectthevalueforOCR.Thisvalueisrequired
for CTC and PWM modes as well as Compare Match Interrupt. Enter the value in
hexadecimalnumbers.
Essentially,youredoneconfiguringyourtimer.Youcannowconfiguretheremainingsettingsofthe
timer and click on File > Generate, Save and Exit. After saving the files, you can configure your
Interrupthandlersinthecodewindow,ifyouactivatedany.
68|P a g e
Atmega16hasfollowingtimers,
Timer0,8bit
Timer1,16bitconsistingoftwo8bitparts,AandB
Timer2,8bit
Nowtherearetwoclocks,
1. SystemClock(fs):ThisistheclockfrequencyatwhichAtmegaisrunning.Bydefaultitis1MHz
whichcanbechangedbysettingfusebits.
Therearetotal4settingsforTimers,
1. ClockSource:Sourcefortimerclock,keep
it as system clock. You can also provide
external clock. Read datasheet for more
informationaboutexternalclocksource.
2. Clockvalue:Thisisvalueofft.Dropdown
for available options of ft. Chose
whicheverisrequired
a. FastPWMtop=FFh
b. CTCtop=OCRx(x=0,1A,2)
BasicallyeachTimerhasacounterunitwithsize8bitforTimer0,2and16bitforTimer1.Iwillbe
talkingaboutTimer0andsamewillfollowforotherTimers.
Each counter has a register which increments by one on every rising edge of timer clock. After
countingtoitsfullcapacity,255for8bit,itagainstartsfrom0.Byusingthisregisterwecanhave
differentmodes.
Timer/Counter(TCNT0)andOutputCompareRegister(OCR0)are8bitregisters.
69|P a g e
TOP: The counter reaches the TOP when it becomes equal to the highest value in the count
sequence.TheTOPvaluecanbeassignedtobethefixedvalue0xFF(MAX)orthevaluestoredin
theOCR0Register.Theassignmentisdependentonthemodeofoperation.
10.9 FastPWMMode
PWM=PulseWidthModulation.
Thismodeisusedtogeneratepulsewith
FixedFrequency(F)
VariableDutyCycle(D)
F=Ft/256
D=OCR0/255
(noninverted)
D=(255OCR0)/255 (inverted)
AsOCR0isan8bitregisteritcanvaryfrom0o255.
0OCR0255
PinsforOutputpulse,
Timer0:OC0,pin4
Timer1A:OC1A,pin19
Timer1B:OC1B,pin18
Timer2:OC2,pin21
Figure16:FastPWMmodeTimingDiagram
70|P a g e
10.10 CTCMode
CTC=ClearTimeronCompareMatch.
Thismodeistogeneratepulsewith,
FixedDutyCycle(D=0.5)
VariableFrequency(F)
F=
D=0.5
0OCR0255
Figure17:CTCModetimingdiagram
71|P a g e
Chapter11 Communication
SimpleparalleltransferUsedtotransfer8,16,and32...bitsofdatainthesametime.
Asynchronous Serial Transfer (USART) It is an old but still in use mode of serial
communicationusesonly2lines(+1additionallineforGND).
SPISerialPeripheralInterfaceItisastandardmodeofcommunicationbetweendifferent
ICs.
USBAveryadvance,highspeedandcomplicatedserialBususedinPCstoconnectalmost
anythingtoit.
11.2 Classification
ModesofDataTransfercanbebroadlydividedintotwotypes:
1. PARALLEL TRANSFER In this mode a number of bits (say 8,16 or 32) are transferred at a
time. Thus they require as many electrical line as the number of bits to be transferred at
once.Thismethodisfastbutitsdisadvantageisthatitusesmorenumberoflines.Sothey
arebasically usedwhenthe unitsinvolvedin data transferarephysicallycloseandalmost
fixed with each other for a long time. For eg. CPU and RAM, the PCI Cards inside the PC.
These are close to each other and packed inside the CPU box and are disconnected from
eachotherlessfrequently.
2. SERIALTRANSFERInthismodeonlyonebitistransferatonce.Sototransfer8bits,8cycles
are required. So these require less number of physical lines (like SPI use 3 lines). The
advantage is that due to less number ICs using these technologies are small with low PIN
count.
ModesofDataTransfercanalsobedividedinto
1. SYNCHRONOUSTRANSMISSION.InthistypetheactualdataistransferredBITbyBITonthe
DATAline.Theclocklinesignalstheendof1bitandthestartofanotherbit.Whentheclock
linechangesitslevel,thatiswhenitgoesHIGHfromaLOWlevelorviceversathedatais
transferred.WhentheCLOCKlinegoesHIGHitsignalsthatanewbitisavailablefortransfer.
The"other"devicewhichisreceivingthedatareadsthedatalineattherisingedgeorthe
fallingedgeoftheclockdependinguponoursettings.
72|P a g e
Thediagramcorrespondsto
thetransferofthedata
10010111.Itcorrespondsto
thevalueofthedataatevery
risingedgeoftheclock.
2. ASYNCHRONOUSTRANSMISSIONAsynchronoustransmissionallowsdatatobetransmitted
without the sender having to send a clock signal to the receiver. Instead, the sender and
receiver must agree on timing parameters in advance and special bits are added to each
wordwhichareusedtosynchronizethesendingandreceivingunits.Whenawordisgiven
forAsynchronoustransmissions,abitcalledthe"StartBit"isaddedtothebeginningofeach
wordthatistobetransmitted.TheStartBitisusedtoalertthereceiverthatawordofdata
isabouttobesent,andtoforcetheclockinthereceiverintosynchronizationwiththeclock
inthetransmitter.Onesolutionistohavebothdevicessharethesameclocksource.
11.3 BaudRate
Baud Rate is a measurement of transmission speed in asynchronous communication. The devices
thatallowcommunicationmustallagreeonasinglespeedofinformation'bitspersecond'.
Whentheentiredatawordhasbeensent,thetransmittermayaddaParityBitthatthetransmitter
generates.TheParityBitmaybeusedbythereceivertoperformsimpleerrorchecking.Thenatleast
oneStopBitissentbythetransmitter.
73|P a g e
Whenthereceiverhasreceivedallofthebitsinthedataword,itmaycheckfortheParityBits(both
senderandreceivermustagreeonwhetheraParityBitistobeused),andthenthereceiverlooks
foraStopBit.
Inshort,asynchronousdatais'selfsynchronizing'.
Transmission
Asynchronous
Synchronous
Advantages
Simple
Inexpensive
Efficient
Disadvantages
& High Overhead
Complex
Expensive
and
11.4 DifferentCommunicationTechniques
74|P a g e
12.1 TheoryofOperation
TheSerialPeripheralInterfaceBusorSPIbusisasynchronousserialdatalinkusedtocommunicate
between two or more microcontroller and devices supporting SPI mode data transfer. Devices
communicateinmaster/slavemodewherethemasterdeviceinitiatesthedataframe.Multipleslave
devicesareallowedwithindividualslaveselect(chipselect)lines.
Thiscommunicationprotocolconsistsoffolliwnglinesorpins,
1. MOSI:MasterOutSlaveIn(TxforMasterandRxforSlave)
2. MISO:MasterInSlaveOut(RxforMasterTxforSlave)
3. SCK:SerialClock(Clockline)
4. SS:SlaveSelect(ToselectSlavechip)(ifgiven0deviceactsasslave)
Master:Thisdeviceprovidestheserialclocktotheotherdevicefordatatransfer.Asaclockisused
forthedatatransfer,thisprotocolisSynchronousinnature.SSforMasterwillbedisconnected.
Slave:Thisdeviceacceptstheclockfrommasterdevice.SSforthishastobemade0externally.
MOSI
MOSI
MISO
MISO
Master
Slave
SCK
SCK
SS
PinconnectionsforSPIprotocol
Figure18:SPIDataCommunication
75|P a g e
InSPI,dataistransmittedserially,i.e.bitbybitasopposedtoparallelcommunicationwhereallthe
dataissentmultiplebitsatatime.WewillstudysynchronousSPI,wherethereisaclockgenerated
andthedataistransferredattherateoftheclockpulse.Whatisclockpulse?
Clockpulseisbasicallyasequenceof alternating0sand1sthatisusedtoindicatethatoneBitof
datahasbeensent.Forexample,ifyouweretosendthedata10011000,thesignalyousentwould
looklike:
Nowasitmightbeclearthereshouldbesomewaytotellthissignalfrom1010of100010ofsome
other.Forthis,wecandoeitheroftwothings,setastandardthatataparticularrate,thedatawill
betransferredandwekeepcheckingforvoltageattimemomentsT,2T,3Tsoon,orwealsosenda
clockpulseatthesametime.Likewedecidethatwheneverwesendanewsignal,wewillmakethe
clock1.Thentheclocksignalwouldlooklike:
Nowifthereceivingmachinereadstheincomingdataatnegativeedges,itwillalwaysreadwhatthe
senderactuallymeant.Thistheconceptofsynchronousdatatransfers.Thesenderandthereceiver
aresynchronizedbyaclockpulse.
Now, in SPI set up when we have to set up communication between two systems, first we have
makeonesystemasmasterandtheotherasslave.Thedifferencebetweenmasterandtheslaveis
thattheclockpulseisgeneratedbythemasterandbothmasterandtheslaveagreetoworkonthe
clockfrequencythatissetupbythemaster.
76|P a g e
ThebasicconnectionsinanySPIsetupareasfollows:
MOSIisMasterOutSlaveIn,soitisthechannelwherethemastersendsthedatatotheslaveand
theslavereceivesit.
MISO is Master In Slave Out, so it is the channel where the slave sends the data and the master
receivesit.
Clockistheclockthatissendbythemaster.
SSisslaveselectwhenthemasterwantstosenddatatoaparticularslaveitmakesitsSSpinlow,
sends the data and then again makes it high. It is especially useful when multiple slaves are
connectedtothemaster,butthebasicpurposeistoselecttheslaveandtransmittingdatatoit.
In SPI, the data the data is exchanged between the transmitter and the receiver. It happens as
follows:
Firstthe masterand the slavekeep the databits to transferin their respective registers. Suppose
master wants to send bm1,bm2,bm3..bm8 and the slave wants to send bs1, b s2, b s3 ..b s8.
Whathappensisasfollows:
77|P a g e
78|P a g e
The data is transferred one bit at a time between the master and the slave, and at the end of 8
cyclesthedataiscompletelyexchanged.
ThefollowingfiguresshowatypicalsetupusedwithSPI:
Onemasterandoneslave
Onemasterandtwoslaves
HOWTOUSECODEWIZARDTOSETUPSPICONNECTION
79|P a g e
12.2 SettingupSPIinMicrocontroller
12.2.1 MasterMicrocontroller
OpenCodeWizardandgotoSPItab.EnableSPIandchoose
MasterinSPIType.
Selectclockratedependinguponyourdatatransferspeed
requirement.
Keepothersettingsasdefault.
12.2.2 SlaveMicrocontroller
OpenCodeWizardandgotoSPItab.EnableSPIandchoose
SlaveinSPIType.
Selectclockratedependinguponyourdatatransferspeed
requirement.
Keepothersettingsaskeptinthemastermicrocontroller.
12.3 DataFunctions
80|P a g e
Youcantransmitorreceive1byteofdataatatime.
12.3.1 TransmitData
spi(1bytedata);
Example:spi(A);
12.3.2 ReceiveData
c=spi(0);//cis1bytevariable Example:charc=spi(0);
12.4 ConnectingMCUToAnotherMCU
Just connect the MOSI, MISO, SCK, and SS to SS. Use the following function to send data:
spi(character)
Whenyouusethisfunctioninthemaster,itwritesthecharactertotheregisterandsendsthedata
toslave.Incaseoftheslave,thedataiswrittentotheregisterandthecpuwaitsforthemasterto
senddatawhenitalsotransmitsthedatawrittenintotheregister.
SAMPLEPROGRAMME:
MASTER:
char a=spi(0xFF);
lcd_putchar(a);//displays1onthelcd
81|P a g e
SLAVE:
char b=spi(1);
Chapter13 USARTCommunication
13.1 USART
Likemanymicrocontrollers,AVRalsohasadedicatedhardwareforserialcommunication.Thispartis
calledtheUSARTUniversalSynchronousAsynchronousReceiverTransmitter.Thisspecialhardware
makesyourlifeasaprogrammereasier.Youjusthavetosupplythedatayouneedtotransmitandit
willdotherest.TheadvantageofhardwareUSARTisthatyoujustneedtowritethedatatooneof
theregistersofUSARTandyourdone,youarefreetodootherthingswhileUSARTistransmitting
thebyte.
AlsotheUSARTautomaticallysensesthestartoftransmissionofRXlineandtheninputsthewhole
byteandwhenithasthebyteitinformsyou(CPU)toreadthatdatafromoneofitsregisters.
TheUSARTofAVRisveryversatileandcanbesetupforvariousdifferentmodesasrequiredbyyour
application. In this tutorial we will show you how to configure the USART in a most common
configurationandsimplysendandreceivedata.
13.2 HardwareAspectofUSART
USART consists of only three connections Rx, Tx and GND. Rx means Receive and Tx means
Transmit.TheGNDconnectionisforacommonreferencelevel.
Heresasimplediagramexplainingtheconnections:
Device1
Rx
Tx
Tx
Rx
2
Gnd
Device
Gnd
NoticehowTxisconnectedtoRx,andRxisconnectedtoTx.
13.3 BaudRate
Baudisameasurementoftransmissionspeedinasynchronouscommunication.Thecomputer,any
adaptors,andtheUARTmustallagreeonasinglespeedofinformation'bitspersecond'.
13.4 DataTransmission
InAsynchronousmode,dataistransmittedinframes.Eachframehasastartbit,databits,optional
paritybit,andstopbits.
82|P a g e
Astartbitsignalsthebeginningofdatatransmission.Databitsaretheactualdatatobetransmitted.
Stopbitssignaltheendoftransmission.
An optional parity bit can be transmitted before the stop bits. This bit represents the number of
logicalhighsinthetransmission.Ifthereareoddnumbersoflogicalhighsinthetransmission,then
theparitybithasalogicalhighvalue.Ifthereareevennumbers,thentheparitybittakesthevalue
logicallow.Paritybitsaregenerallyusedinerrordetection.
Figure19:BasicUARTpacketformat:1startbit,8databits,1paritybit,1stopbit.
BAUDRate:Thisparameterspecifiesthedesiredbaudrate(bitspersecond)oftheUART.Most
typicalstandardbaudratesare:300,1200,2400,9600,19200,etc.However,anybaudratecanbe
used.Thisparameteraffectsboththereceiverandthetransmitter.Thedefaultis2400(bauds).
IntheUARTprotocol,thetransmitterandthereceiverdonotshareaclocksignal.Thatis,aclock
signaldoesnotemanatefromoneUARTtransmittertotheotherUARTreceiver.Duetothisreason
theprotocolissaidtobeasynchronous.
Sincenocommonclockisshared,aknowndatatransferrate(baudrate)mustbeagreeduponprior
todatatransmission.Thatis,thereceivingUARTneedstoknowthetransmittingUARTsbaudrate
(andconverselythetransmitterneedstoknowthereceiversbaudrate,ifany).Inalmostallcases
thereceivingandtransmittingbaudratesarethesame.Thetransmittershiftsoutthedatastarting
withtheLSBfirst.
Once the baud rate has been established (prior to initial communication), both the transmitter and the
receivers internal clock is set to the same frequency (though not the same phase). The receiver
"synchronizes" its internal clock to that of the transmitters at the beginning of every data packet
received. This allows the receiver to sample the data bit at the bit-cell center.
A key concept in UART design is that UARTs internal clock runs at much faster rate than the baud
rate. For example, the popular 16450 UART controller runs its internal clock at 16 times the baud rate.
This allows the UART receiver to sample the incoming data with granularity of 1/16 the baud-rate
period. This "oversampling" is critical since the receiver adds about 2 clock-ticks in the input data
synchronizer uncertainty. The incoming data is not sampled directly by the receiver, but goes through
83|P a g e
a synchronizer which translates the clock domain from the transmitters to that of the receiver.
Additionally, the greater the granularity, the receiver has greater immunity with the baud rate error.
The receiver detects the start bit by detecting the transition from logic 1 to logic 0 (note that while the
data line is idle, the logic level is high). In the case of 16450 UART, once the start-bit is detected, the
next data bits "center" can be assured to be 24 ticks minus 2 (worse case synchronizer uncertainty)
later. From then on, every next data bit center is 16 clock ticks later. Figure 2 illustrates this point.
Once the start bit is detected, the subsequent data bits are assembled in a de-serializer. Error
condition maybe generated if the parity/stop bits are incorrect or missing.
13.6 SerialPortofComputer
WewillbeusingSerialPortforcommunicationbetweentheuCandthecomputer.Aserialporthas
9pinsasshown.Ifyouhavealaptop,thenmostprobablytherewontbeaserialport.Thenyoucan
useaUSBtoserialConverter.
84|P a g e
If you have to transmit one
e byte of
data, the
t serial port will transm
mit 8 bits
as onee bit at a tim
me. The advantage is
thata serialportneedsonlyon
newireto
transm
mitthe8bits.
Pin
n3istheTransmit(TX)pin
n,pin2is
theReeceive(RX)pinandpin5iisGround
pin. Other pins are
e used for co
ontrolling
dataco
ommunicatio
onincaseofaamodem.
For th
he purpose of
o data tran
nsmission,
onlyth
hepins3and5arerequire
ed.
Th
he standard
d used fo
or serial
Figgure20:ASerialPort
communicationisR
RS232(Recom
mmended
Standaard 232). Thee RS232 stan
ndard definess the voltagee levels that ccorrespond to
t logical onee and
logical zero levels. Valid signals are plusor minus 3to1
15volts. The rangenear zero
z
volts is not
n a
validR
RS232level; logiconeisd
definedasa negativevolttage,thesign
nalcondition iscalledmarrking,
andhaasthefunctio
onalsignifican
nceofOFF.Logiczeroisp
positive;thessignalconditionisspacingg,and
hasthe
efunctionON
N.
No
owweknow thatthisisn
notthevoltaggelevelatwhichourmicrocontrollerw
works.Hencee,we
needaadevicewhicchcanconverrtthisvoltageleveltothaatofCMOS,i.e.,logic1= +5Vandlogiic0=
0V.Th
histaskiscarriedoutbyaanICMAX23
32,whichisaalwaysusedw
withfour10u
uFcapacitors.The
circuitisshown:
heRxandTxshowninabo
ovefigure(pins11and12
2ofMAX232)aretheRxaandTxofAtm
mega
Th
16(PD
D0andPD1re
espectively).
85|P a g e
USART connection with a computer is accomplished through a protocol called RS232. RS232 is an
asynchronousserialcommunicationprotocolwidelyusedincomputersanddigitalsystems.Asimple
exampleistheserialportusedinoldcomputers.
Onethingtonoteaboutthisprotocolisthat,whileinanMCUcircuit,HIGH=5VandLOW=0,for
RS232thevaluesare+12Vand12Vrespectively.Forthisconversion,anICcalledMAX232isused:
Theschematicsrequiredare:
13.7 SettingupUARTinmicrocontroller
86|P a g e
Once our electronic circuit is complete, we can start with coding. To enable UART mode in
Atmega16,clickontheUSARTtabinCodeWizard.Nowdependinguponyourrequirement,youcan
eithercheckreceiver,transmitterorboth.Yougetalistofoptionstoselectfromforthebaudrate.
Baud Rateistheunitofdatatransfer,definedasbitspersecond.Wewillselect9600asitisfair
enoughforourpurpose,anddefaultsettinginmostoftheapplications(likeMatlab,Docklight,etc.).
Keep the communication parameters as default, i.e., 8 data, 1 stop and no parity and mode
asynchronous.YoualsohaveoptionofenablingRxandTxInterruptfunctions,butwewontdoat
thispoint.
Onceyougenerateandsavethecode,alltheregistervaluesaresetbyCVAVRandyouonlyneed
toknowsomeoftheCfunctionstotransferdata.
87|P a g e
13.8 DockLight
To communicate with the computer, you need a terminal where you can send data through
keyboard and the received data can be displayed on the screen. There are many softwares which
providesuchterminal,butwewillbeusingDocklight.Itsevaluationversionisfreefordownloadon
internet,whichissufficientforourpurpose.
To start with, check the Terminal Settings in Docklight. Go to Tools > Project Settings. Select the
Send/Receive communication channel, i.e., the name by which the serial port is known in your
computer (like COM1). In the COM port settings, select the samevalues as you had set while
codingAtmega16.So,wewillselectBaudRate9600,DataBits8,StopBits1,ParityBitsnone.You
canselectnoneinParityErrorCharacter.ClickOK.
Wearenowreadytosend/receivedata,so,selectRun>StartCommunication,or,pressF5.Ifyour
uCisactingasatransmitter,thenthecharactersitsendswillappearintheCommunicationwindow
ofDocklight.E.g.,
putchar(K);
delay_ms(500);
//SendscharacterKafterevery500ms
HencewhatyougetonthescreenisaKKKKKKKKKKKKKKKKKKKKKKKKK..oneKincreasingevery
500ms.Tostopreceivingcharacters,selectRun>StopCommunication,orpressF6.
IfthereceiveroptionisalsoenabledinAtmega16,thenwhateveryoutypefromkeyboardwill be
receivedbyit.YoucaneitherdisplaythesereceivedcharactersonanLCD,controlmotorsdepending
onwhatcharactersyousend,etc.e.g.,
c=getchar();
//receivecharacter
lcd_putchar(c);
//displayitonLCD
if(c==A)
PORTA=255;
//ifthatcharacterisA,makeallpinsofPORTAhigh.
Whenyouaredonewithsendingdata,selectRun>StopCommunication,orpressF6.
88|P a g e
Rx Interrupt and Tx Interrupt are special interrupts that are called every time data is
received/transmitted.Selectingeitheroptionwillenablemoreoptionsleavethemtotheir
defaultvalues.
Baudratewillletyouselectthetransmissionrateinbps.Thelinebelowtheoptionwilltell
you the error rate do not set the baud rate so high that the error is large and the line
becomesred.
CommunicationParameterswillletyousetotherparametersleavethemtotheirdefaults
formostcases.
IMPORTANT:Thesesettingsshouldbethesameforboththedeviceswhicharecommunicatingwith
eachother.
13.9 ImplementingUSARTinYourCode
ImplementingUSARTiseasyallyouneedaretwofunctions:
1. putchar(char);
ThisfunctionwillallowyoutotransmitdatathroughtheUSARTinterface.Theargumentisa
character; you can transmit the ASCII code of the character in hexadecimal form. The
transmitteddataisstoredinaspecialregisterinthedevicewhichisreceivingthisdata.
2. getchar();
ThisfunctionreadsdatafromthespecialregisterreservedforUSARTcommunication.This
functionwillstalltheprogramwhilewaitingforthedatatobetransmittedandstoredinthe
registerifitdoesnotalreadyexist.
13.9.1 putchar()
Tosendonecharactertothebuffer,whichwillbereceivedbythedevice(uCorcomputer)?E.g.,
putchar(A);//sendscharacterAtothebuffer
putchar(c);//sendsavariablecharacterc
13.9.2 getchar()
To receive one character from the buffer, which might have been sent by the other uC or the
computer.E.g.,ifwehavealreadydefinedavariablecharc,then
c=getchar();
//receivesthecharacterfrombufferandsaveitinvariablec
13.9.3 putsf()
89|P a g e
Tosendaconstantstring.Eg,
putsf(MyNameisXYZ);
SAMPLEPROGRAM
InputMCU
//aisacharvariable
a=getchar();
a=inputFromUser();
//Programwillwaitfordata
putchar(a);
//Datatransmitted,nowprint
LCDMCU
printChar(a);
90|P a g e
Chapter14 Interrupt
Whatisaninterrupt?
AspecialeventthatrequirestheCPUtostopnormalprogramexecutionandperformsomeservice
relatedtotheevent.
ExamplesofinterruptsincludeI/Ocompletion,timertimeout,illegalopcodes,arithmeticoverflow,
divideby0, etc.Functions of InterruptsCoordinating I/O activities and preventing CPU from being
tiedupProvidingagracefulwaytoexitfromerrorsRemindingtheCPUtoperformroutinetasks
Interrupt maskabilityInterrupts that can be ignored by the CPU are called maskable interrupts.A
maskable interrupt must be enabled before it can interrupt the CPU.An interrupt is enabled by
settinganenableflag.InterruptsthatcantbeignoredbytheCPUarecallednonmaskableinterrupts.
Interruptpriority
Allow multiple pending interrupt requestsResolve the order of service for multiple pending
interrupts
InterruptserviceCPUexecutes a program called the interruptservice routine.A complete interrupt
servicecycleincludesSavingtheprogramcountervalueinthestackSavingtheCPUstatus(including
the CPU status register and some other registers)in the stackIdentifying the cause of
interruptResolvingthestartingaddressofthecorrespondinginterruptserviceroutineExecutingthe
interruptserviceroutineRestoringtheCPUstatusandtheprogramcounterfromthestack
RestartingtheinterruptedprogramInterruptvectorStartingaddressoftheinterruptserviceroutine
/Interrupt vector tableA table where all interrupt vectors are storedMethods of determining
interrupt vectorsPredefined locations (Microchip PIC18, 8051 variants)Fetching the vector from a
predefined memory location (HCS12)Executing an interrupt acknowledge cycle to fetch a vector
numberinordertolocatetheinterruptvector(68000andx86families)
Stepsofinterruptprogramming
Step1.Initializingtheinterruptvectortable
Step2.Writingtheinterruptserviceroutine
Step3.Enablingtheinterrupt
InterruptsEnabling
INT0,INT1,INT2aresetforenablingthecorrespondinginterrupts
InterruptLevels
91|P a g e
InterruptFlag
This register contains the interrupt flags for the interrupts 0, 1, 2You can poll this to check for an
interrupt.Writinga1tobitpositionacknowledgetheinterrupt
An interrupt is a signal that stops the current program forcing it to execute another program
immediately. The interrupt does this without waiting for the current program to finish. It is
unconditionalandimmediatewhichiswhyitiscalledaninterrupt.
The concept of an interrupt in reference to microcontrollers is similar to our daily life concept of
interrupts:supposeyouarereadingthistutorialandsuddenlyyourmobileringswhatyoudoisyou
stopreadingforawhileandattendthephonecall,andthenresumereadingfromwhereyouleftit.
Thewholepointofaninterruptisthatthemainprogramcanperformataskwithoutworryingabout
anexternalevent.
Example
Forexampleifyouwanttoreadapushbuttonconnectedto
onepinofaninputportyoucouldreaditinoneoftwoways
eitherbypollingitorbyusinginterrupts.
14.1 Polling
14.2 Hardwareinterrupt
92|P a g e
By using a hardware interrupt driven button reader the calculation could proceed with all button
presses captured. With the interrupt running in the background you would not have to alter the
calculationfunctiontogiveupprocessingtimeforbuttonreading.
Theinterruptroutineobviouslytakesprocessortimebutyoudonothavetoworryaboutitwhile
constructingthecalculationfunction.
You do have to keep the interrupt routine small compared to the processing time of the other
functions its no good putting tons of operations into the ISR. Interrupt routines should be kept
shortandsweetsothatthemainpartoftheprogramexecutescorrectlye.g.forlotsofinterrupts
youneedtheroutinetofinishquicklyreadyforthenextone.
14.3 HardwareInterruptorpolling?
The benefit of the hardware interrupt is that processor time is used efficiently and not wasted
pollinginputports.Thebenefitofpollingisthatitiseasytodo.
Another benefit of using interrupts is that in some processors you can use a wakefromsleep
interrupt.Thisletstheprocessorgointoalowpowermode,whereonlytheinterrupthardwareis
active,whichisusefulifthesystemisrunningonbatteries.
HardwareinterruptCommonterms
Terms you might hear associated with hardware interrupts are ISR, interrupt mask, non maskable
interrupt,anasynchronousevent,andinterruptvectorandcontextswitching.
14.4 SettingupHardwareInterruptinMicrocontroller
Thereare3externalinterruptsinAtmega16.Theyare
INT0:PD2,Pin16
INT1:PD3,Pin17
INT2:PB2,Pin3
Thereare3modesofexternalInterrupts,
2. FallingEdge:Inthismodeinterruptoccurswheneveritdetectsafallingedgethatis1to0logic
changeatINTpin.
3. RisingEdge:Inthismodeinterruptoccurswheneveritdetectsafallingedgethatis0to1logic
changeatINTpin.
14.5 FunctionsofInterruptServiceRoutine
Aftergeneratingthecode,youcanseethefollowingfunction,
93|P a g e
//ExternalInterrupt0serviceroutine
interrupt[EXT_INT0]voidext_int0_isr(void)
{
//Placeyourcodehere
Youcanplaceyourcodeinthefunction,andthecodewillbeexecutedwheneverinterruptoccurs.
14.6 TimerInterrupt
Prior to learning about timers you need to know the concept of interrupt because timers mainly
interactwithCPUthroughinterrupts.Theconceptofaninterruptinreferencetomicrocontrollersis
similartoourdailylifeconceptofinterrupts:supposeyouarereadingthistutorialandsuddenlyyour
mobile rings what you do is you stop reading for a while and attend the phone call, and then
resumereadingfromwhereyouleftit.ThisisexactlywhataninterruptdoesinMCU.WhiletheMCU
is executing a program, if there is something that needs immediate attention, an interrupt is
generatedbythattaskandtheexecutionofthecurrentprogramisleftatthattimeandinterruptis
handled. After that, the execution of program continues as usual from the point where it was
stopped.The timers runparallel and independent of the CPU at a specificfrequency,and interact
withtheCPUbyissuinginterrupts.
Therearetwotypesofinterrupts:
Overflowinterrupt
ComparematchInterrupt
14.7 OverflowInterrupt
Overflow interrupt is triggered whenever the timer register overflows, i.e. reaches its maximum
value(inthiscase,255,or,inhexadecimal,FFh).
In order to use overflow interrupt, you should first decide what your clock frequency will be (To
learn how to do that, see How to define clock frequency for a timer? below). Then check the
checkboxwrittenoverflowinterruptthatappearsintheTimerstabintheCodeWizardAVR(Note:
TheTimervaluefieldcanbeusedtosettheinitialvalueofthetimer.Bydefault,itissetto0).Now
whenyougenerateyourfile,youwillfindthatafunctionappearsinthecode:
.
.
.
.
#include<mega16.h>
94|P a g e
//Timer0overflowinterruptserviceroutine
interrupt[TIM0_OVF]voidtimer0_ovf_isr(void)
{
//Placeyourcodehere
}
//Declareyourglobalvariableshere
.
.
.
.
Nowyoucanplaceacodeherethatisexecutedeverytimeanoverflowinterruptisgenerated.
Thisinterruptcanbeusedtomeasuretimeintervalslargerthan1cycle.Forexample,letussuppose
that an LED is connected to say pin 0 of Port A and you want to blink it at 0.5 Hz using overflow
interrupts. Since the system frequency is 8 Mhz, you can set an appropriate clock speed say,
FCPU/1024(seePrescalarbelow)andthendoitasfollows:
intcount=0;
interrupt[TIM0_OVF]voidtimer0_ovf_isr(void)
{
//Incrementourvariable
count++;
if(count==61)
{
PORTA.0=~PORTA.0;//InverttheValueofPORTA
count=0;
}
}
This function will increment the count variable every time the overflow interrupt is called and
whentheappropriatetimehaspassed,willtogglethevalueofPORTA.0.
14.8 CompareMatchInterrupt
ACompareMatchInterruptisissuedbyatimerwheneverthevalueofthetimerbecomesequaltoa
certainpredefinedvalue.ThispredefinedvalueisstoredinaregisterknownastheOutputCompare
Register.
ComparematchInterruptsarerequiredbytheCTC,FastPWM,andPhasecorrectPWMmodesofa
timer(seebelow).
95|P a g e
In order to use compare match interrupt, check the checkbox written compare match interrupt
thatappearsintheTimerstabintheCodeVisionWizard.SetthevalueoftheOCRintheCompare
value in hexadecimal numbers. Now when you generate your file, you will find that a function
appearsinthecode:
.
.
.
.
#include<mega16.h>
//Timer0outputcompareinterruptserviceroutine
interrupt[TIM0_COMP]voidtimer0_comp_isr(void)
{
//Placeyourcodehere
}
//Declareyourglobalvariableshere
.
.
.
.
Nowyoucanplaceacodethatisexecutedeverytimeacomparematchinterruptisgenerated,as
shown:
interrupt[TIM0_COMP]voidtimer0_comp_isr(void)
{
//Enteryourhandlercodehere
}
96|P a g e
Chapter15 EEPROM
UnderstandinginternalEEPROM:
WhyEEPROM?
Providesnonvolatilememorystoragespace
AVRhasinternalEEPROMof512bytes
Enduranceofatleast100,000write/erasecycles
Organizedasaseparatedataspaceinwhichsinglebytescanbeerased/written
FusebitconfigurationchangesforEEPROM:
HFUSE(previousvalue=0xC9)
RevisedHFUSEvalue=0xC1
SettingEESAVEto0(programmed)willreservetheEEPROMcontentsthroughthe
chiperase
1
EESAVE
UnderstandinginternalEEPROM(contd...):
ConfiguringinternalEEPROM:
EEPROMAddressRegister:EEAR
ThisEEPROMlocationstobeaddressesstartingfrom0x0000to0x0511
EEPROMDataRegister:EEDR
EEPROMControlRegister:EECR
Bits
97|P a g e
Description
EERIE
EEMWE
EEWE
EERE
EEPROMReadyInterruptEnable
EEPROMMasterWriteEnable
EEPROMWriteEnable
EEPROMReadEnable
NOTE:EEWEshouldbesettologicalonewithinfourclockcyclesaftersetting
EEMWEtologicalone(securityfeature).
voidEEPROM_write(unsignedintuiAddress,unsignedcharucData)
{
/*Waitforcompletionofpreviouswrite*/
while(EECR&(1<<EEWE));
/*Setupaddressanddataregisters*/
EEAR=uiAddress;
EEDR=ucData;
/*WritelogicalonetoEEMWE*/
EECR|=(1<<EEMWE);
/*StarteepromwritebysettingEEWE*/
EECR|=(1<<EEWE);
}
unsignedcharEEPROM_read(unsignedintuiAddress)
{
/*Waitforcompletionofpreviouswrite*/
while(EECR&(1<<EEWE));
/*Setupaddressregister*/
EEAR=uiAddress;
/*StarteepromreadbywritingEERE*/
EECR|=(1<<EERE);
/*Returndatafromdataregister*/
returnEEDR;
}
98|P a g e
SectionC
Robotics
99|P a g e
Chapter16 IntroductiontoRobots
Robotics is the science of designingand building robots suitable for reallife applications in
automated manufacturing and other nonmanufacturing environments. Robots are the means of
performing multifarious activities for mans welfare in most planned and integrated manner,
maintaining their own flexibility to do any work, effecting enhanced productivity, guaranteeing
quality, assuring reliability and assuring safety to workers. The word robot came from the
CzechoslovakinwordRobotawhichmeansaworkeroraslavedoingheavywork.
Over the course of human history the emergence of certain new technologies have globally
transformedlifeasweknowit.Disruptivetechnologieslikefire,theprintingpress,oilandtelevision
have dramatically changed both the planet we live on and mankind itself, most often in
extraordinary and unpredictable ways. In prehistory these disruptions took place in less than a
generation.
Wearecurrentlyattheedgeofonesuchevent.Intenyearsroboticsystemswillflyourplanes,grow
ourfood,explorespace,discoverlifesavingdrugs,fightourwars,sweepourhomesanddeliverour
babies.
In the process, this robotics driven disruptive event will create a new 200 billion dollar global
industryandchangelifeasyounowknowit,forever.Justasthepresentgenerationcannotimagine
worldwithoutelectricity,thefuturegenerationwillneverknowaworldwithoutrobots.
TheThreeLawsofRoboticsare:
Arobotmaynotinjureahumanbeing,or,throughinaction,allowahumanbeingtoharm
them.
Arobotmustobey the ordersgivenit byhumanbeings except wheresuch orderswould
conflictwiththeFirstLaw.
Arobotmustprotectitsownexistenceaslongassuchprotectiondoesnotconflictwiththe
FirstorSecondLaw.
DEFINITIONOFROBOTICS
AmericanHeritageDictionary:robot(rbt,bt)n.
Amechanicaldevicethatsometimesresemblesahumanbeingandiscapableofperforming
avarietyofoftencomplexhumantasksoncommandorbybeingprogrammedinadvance.
Amachineordevicethatoperatesautomaticallyorbyremotecontrol.
A person who works mechanically without original thought, especially one who responds
automaticallytothecommandsofothers.
Webster
100|P a g e
a:amachinethatlookslikeahumanbeingandperformsvariouscomplexacts(aswalking
or talking) of a human being; a similar but fictional machine whose lack of capacity for
human emotions is often emphasized b : an efficient insensitive person who functions
automatically.
Adevicethatautomaticallyperformscomplicatedoftenrepetitivetasks.
Amechanismguidedbyautomaticcontrols.
History
One of the first robots was the clepsydra or water clock, which was made in 250 B.C. It was
createdbyCtesibiusofAlexandria,aGreekphysicistandinventor.Theearliestremotecontrol
vehicles were built by Nikola Tesla in the 1890's. Tesla is best known as the inventor of AC
electric power, radio (before Marconi), induction motors, Tesla coils, and other electrical
devices. Other early robots (1940's 50's) were Grey Walter's "Elsie the tortoise"
("Machinaspeculatrix") and the Johns Hopkins "beast." "Shakey" was a small unstable box on
wheels that used memory and logical reasoning to solve problems and navigate in its
environment.ItwasdevelopedbytheStanfordResearchInstitute(SRI)inPaloAlto,Californiain
the1960s.TheGeneralElectricWalkingTruckwasalarge(3,000pounds)fourleggedrobotthat
could walk up to four miles an hour. The walking truck was the first legged vehicle with a
computerbrain, developed by Ralph Moser at General Electric Corp. in the 1960s. The first
modern industrial robots were probably the "Unimates", created by George Devol and Joe
Engleberger in the 1950's and 60's. Engleberger started the first robotics company, called
"Unimation",andhasbeencalledthe"fatherofrobotics."
IsaacAsimovandJoeEngleberger(imagefromRoboticsSocietyofAmericawebsite)
101|P a g e
Left: Grey
G
Walter'ss tortoise, resstored recenttly by Owen Holland and fully operational (from Arkin,
A
1998).Center:Shakkeytherobot.Shakeywaasthefirstmobilerobotthatcouldthiinkindependently
andinteractwithittssurroundings(fromWickelgren,1996
6).Right:GeeneralElectriccWalkingTru
uck.A
human
n controlled the steppingg of this rob
bot by pushin
ng pedals wiith his feet. The compliccated
coordinationofmo
ovementswitthinalegand
dbetweendiffferentlegsd
duringsteppingwascontrrolled
byaco
omputer(from
mWickelgren
n,1996).
16.1 WhatIsA
ARobot?
102|P a g e
A
rep
programmablee,
multifu
unctional
manipulatorr
designed
d
to
m
move
material, parts, too
ols, or sp
pecialized devices
d
thro
ough variou
us program
mmed
motionsforrtheperform
manceofavarrietyoftasks.
ThewordROBOTisdeerivedfromth
hewordROBOTAwhichm
means'compu
ulsorylabor'.
A Robot is an electronic device whiich can be co
ontrolled digitally and maanually,basicaally it
reducestheehumanefffo
ortineveryaspect.
Itisafieldo
ofEngineerin
ngthatcoverssthemimickin
ngofhumanbehavior.
Roboticsin
ncludestheknowledgeof Mechanical, Electronics, Electrical&C
ComputerSciience
Engineeringg.
Arobotmusthavethefollowingessentialcharacteristics:
Mobility:Itpossessessomeformofmobility.
Programmability:implying computational or symbol manipulative capabilities that a
designer can combine as desired (a robot is a computer). It can be programmed to
accomplishalargevarietyoftasks.Afterbeingprogrammed,itoperatesautomatically.
Sensors:on or around the device that are able to sense the environment and give useful
feedbacktothedevice
Mechanicalcapability:enablingittoactonitsenvironmentratherthanmerelyfunctionasa
dataprocessingorcomputationaldevice(arobotisamachine);
Flexibility: it can operate using a range of programs and manipulates and transport
materialsinavarietyofways.
IsaacAsimov'sThreeLawsofRobotics:
Thetermroboticswascoinedinthe1940sbysciencefictionwriterIsaacAsimov.
LawZeroArobotmaynotinjurehumanity,or,throughinaction,allowhumanitytocometo
harm.
FirstLawArobotmaynotinjureahumanbeing,or,throughinaction,allowahumanbeing
tocometoharm.
SecondLawArobotmustobeyordersgivenitbyhumanbeings,exceptwheresuchorders
wouldconflictwiththeFirstLaw.
Third Law A robot must protect its own existence as long as such protection does not
conflictwiththeFirstorSecondLaw.
IntroductiontoAutonomousRobots:
AnyAutonomousRobotconsistsoffollowingessentialparts.
1. RobotChassisandactuators
Includeswheeledoranytypeofchassiswithallthenecessaryactuatorsfittedonthechassisto
achievedesiredgoal.WemostlyuseDCgearedmotorsasactuators.
2. Electronics
ElectronicsincludesSensors,motioncontrolcircuits,powermanagementsystemetc.
3. PowerSource
Usually battery pack consisting of Lead acid, Nickel cadmium, Nickel metal hydride or Lithium
batteriesisused.
4. Intelligence
Thisisthemostimportantpartoftheautonomousrobots.Usuallyintelligenceisachievedbyusing
Microcontroller.
Firststepinmakinganautonomousrobotistochalkoutwhattasksweareexpectingtherobotto
perform.Aftergaugingthesewegetavagueideaaboutthedesignandappearanceoftherobot.
16.2 RobotChassisDesigning
SelectingtheDriveMechanismforthewheeledmotion:
103|P a g e
16.2.1 Robotwithsteeringwheel:
Powerformotionisprovidedbybackwheelsandturningisachievedusingfrontwheels.
Thisschemeissimilartothatofcars.
Advantages:
1. Whenpathtobefollowedisstraightinnaturewithcurvedturnsthisconfigurationgivesfastest
speedandgracefulpathfollowing.
2. Dontneedtomodifyleftorrightwheelsvelocitytofollowthepath.Thisisveryadvantageous
whenwewantprecisionvelocitycontrol.Inthiscasebackwheelstakecareofvelocitycontrol
andfrontwheelstakecareofdirectioncontrol.
Disadvantages:
1. Itwillnotabletotakeverysharpturns.Henceitisdifficulttomoverobotonthegridoflines.
2. Somewhatdifficultandexpensivetomake.
3. Frontwheelswillneedpositionfeedbacktocontrolturningcontrol.
16.2.2 Robotwithdifferentialdrive:
Amethodofcontrollingarobotwheretheleftandrightwheelsarepoweredindependently.
TheThreeWheelDifferentialdriveusestwomotorsandacasteroranomnidirectionalwheel
easiesttodesignandprogram.
104|P a g e
Figure21:Ballbearingcaster,wheelbasedswivelcasterandomnidirectionalwheel
The radius and centre of rotation can be varied by the varying the relative speed of rotation
betweenthetwomotors.
Rotatingthewheelsindifferentdirectionsprovidesasharpturn.
Forasmoothturn,rotatethewheelsinthesamedirectionbutwithdifferentspeeds. Greater
thedifferenceinspeeds,smallertheradiusofrotation.
Advantages:
1. Zeroturningradiusachievable.
2. Easytomovewhenpathtobefollowediscontouredandzigzaginnature.E.g.,navigatingalong
themazeoflines.
Disadvantages:
1. If we want to move along curved path we have to control left and right motors velocity
independently.Henceprecisionvelocitycontrolbecomesdifficultasactualvelocityoftherobot
willbeaverageofthebothwheels.
Chapter17 MotorsandMotorDrivers
17.1 IntroductiontoMotors
Deviceusedtoconvertelectricalenergyintomechanicalenergyiscalledamotor.Amotorisvery
usefulinroboticsandembeddedsystemstogivemovementanddesigningcontrolsystems.
SomeMotorsusedinembeddedsystemsandroboticsaredescribedasbelow:
i. Steppermotors
ii. Servomotors
iii. GearedDCMotors
105|P a g e
Steppermotors
Amotorwhichdividesitsfullrotationintoalargenumberofstepsiscalledasteppermotor.These
steps help in precise, step by stepmovement of the rotor giving
precisecontrolovermovement.
Theshaftofsteppermotorhaspermanentmagnetsattachedtoit.
The rotor is surrounded by series of coils which can be turned on
andoffandthemagneticfieldchangecausestherotortomove.As
themovementiscontrolledbyturningcoilsonoroff,itiseasierto
programthemovementsofsteppermotorusingmicrocontrollers.
Thesemotorsarealsocalledopenloopsystemsanddonothaveany
feedbackmechanism.Thesehaveverysimpledesignandareoften
lessreliable.Suchmotorsareusedinvarietyofdeviceslikelinearactuators,printersetc.
Servomotors
A servo motor is defined as the motor that allows more precise control of position, velocity, or
torqueusingfeedbackloops.Thesefeedbackloopshelpinstabilityanalysisandgivebettercontrol
overmovement.Thesearealsocalledclosedloopsystems.
Thesemotorscannotrotatecontinuallyandhencecannotbeused
for driving wheels. These motors usually have a 90180 degree
movement.Servomotorsarenormallyusedinmachinetoolsand
automationrobots.
Programming these motors is more complex. Also the design is
morecomplex.ThesearemorereliablethanSteppermotors.
GearedDCmotors
Gearmotorsaremotorswithanintegratedgearbox.Thefunctionofgearboxistoincreasetorque
generating capacity of the motor reducing its output speed. Hence, the
needforspeedreducingarrangementiseliminated.
Geared motors have a variety of applications. Some of its uses are as in
wheelchairs,stairwheelsetc.
17.2 HBridge:
ItallowsacircuitfullcontroloverastandardelectricDCmotor.Thatis,withanHbridge,a
microcontroller,logicchip,orremote controlcanelectronicallycommand themotortogo
forward,reverse,brake,andcoast.
Hbridgesareavailableasintegratedcircuits,orcanbebuiltfromdiscretecomponents.
106|P a g e
A"doublep
poledoublethrow"relayccangenerallyachievethessameelectriccalfunctionalityas
anHbridgee,butan Hb
bridgewould bepreferable whereasm
mallerphysiccal sizeisneeeded,
highspeedswitching,lo
owdrivingvo
oltage,orwherethewearringoutofm
mechanicalpaartsis
undesirablee.
S1
1
1
S2
0
S3
0
0
S4
1
1
1
0
0
0
1
1
0
0
0
1
1
0
Result
R
M
Motor
rotatees in one
d
direction
M
Motor
rotaates in
o
oppositedirec
ction
M
Motor
freee runs
(coasts)
M
Motorbrakes
s
M
Motorbrakes
s
StructureoffanHbridgee(highlighted
dinred)
Topowerrthemotor,yyouturnontw
woswitchestthatarediago
onallyoppose
ed.
Thetwob
basicstateso
ofanHbridgee.
17.3 MotorDriiverICs:L293/L293
3DandL29
98
107|P a g e
AMotorDrriverIClikeL2
293DorL298isusedforth
hispurposew
whichhastwo
oHbridgedriivers.
Hence,eachICcandriveetwomotors.
mplifythecurrrent;itonlyactsasaswittch(AnHbrid
dgeis
Notethataamotordriverdoesnotam
nothingbutt4switches)..
Figgure23:L293D
Figurre22:L298
Driversareenabledinp
pairs,withdrivers1and2
2beingenableedbytheEnaablepin.Wheenan
enableinpu
utishigh(loggic1or+5V),theassociateeddriversareeenabledand
dtheiroutputtsare
activeandiinphasewith
htheirinputs..
Whentheeenablepinis low,theouttputisneitheerhighnorlo
ow(disconneccted),irrespeective
oftheinputt.
Directionofthemotoriscontrolledb
byassertingo
oneoftheinputstomoto
ortobehigh((logic
1)andtheo
othertobelow(logic0).
Tomoveth
hemotorinoppositedirecctionjustinteerchangethelogicappliedtothetwoin
nputs
ofthemoto
ors.
Assertingbothinputsto
ologichighorrlogiclowwilllstopthemo
otor.
ors is about 26 ohms i.ee. its short ccircuit current will be aro
ound.
Resistance of our moto
0.46Ampw
whichisbelowthemaximum
mcurrentlim
mit.
93andL293D
D:Outputcurrrentperchannel=1AforrL293and60
00mA
Difference betweenL29
forL293D.
108|P a g e
17.3.1 DifferencebetweenL293andL298:
L293 is quadruple halfH driver while L298 is dual fullH driver, i.e, in L293 all four input
outputlinesareindependentwhileinL298,ahalfHdrivercannotbeusedindependently,
onlyfullHdriverhastobeused.
Outputcurrentperchannel=1AforL293and2AforL298.Hence,heatsinkisprovidedin
L298.
ProtectiveDiodesagainstbackEMFareprovidedinternallyinL293Dbutmustbeprovided
externallyinL298.
17.3.2 SpeedControl:
Tocontrolmotorspeedwecanusepulsewidthmodulation(PWM),appliedtotheenable
pinsofL293driver.
PWM is the scheme in which the duty cycle of a square wave output from the
microcontrollerisvariedtoprovideavaryingaverageDCoutput.
WhatactuallyhappensbyapplyingaPWMpulseisthatthemotorisswitchedONandOFFat
agivenfrequency.Inthisway,themotorreactstothetimeaverageofthepowersupply.
Figure24:VelocitycontrolofmotorusingPWM
Chapter18 Sensors
A sensor is a device that measures a physical quantity and converts it into a signal which can be
readbyanobserverorbyaninstrument.
Temperaturesensor:
Commonly availabletemperaturesensorsareLM35,DS1621,thermistor.Thermistorgives resistance
proportionaltothetemperature.Butaccuracyisnotgoodinthermistor.DS1621givesdigitaloutput
in I2C format, so you require a microcontroller to interface to see the temperature. Thermistor
requireaccurateresistanceinseriestogetgoodreadingwithaccuracyTheresistanceofthermistors
109|P a g e
are100ohm,1Kohm(theoneihaveheard).Butthermistorcreatessomeheadachesalthoughitcosts
Rs.5.LM35have3terminalVcc,ground,Vout.SoitiseasyandgivesanalogoutputanditcostsRs.50
LM35:
The most commonly available LM35 is LM35DZ measures temperaturefrom 0 to 100 degree.
Normallysensorsbecomeinaccuratewithage.ButLM35willnothavethisproblem.WegetLM35in
TO92 package, just likesmall transistors like BC547. The main problem you will be creating
isinterchanging leads. Vs range from 4V to 30V. Output is 10mV* degree inCelsius. That is if the
temperatureis29degreethenVout=.29V.Let'stryforacircuitwhichwillglowanLEDiftheoutput
voltageisgreaterthansomevoltage.UsecomparatorwithareferencevoltageatoneendandLM35
output at other end, so that comparator become high when thetemperature is above reference.
MoreLinks:
http://www.facstaff.bucknell.edu/mastascu/elessonshtml/Sensors/TempLM35.html
http://www.cjseymour.plus.com/elec/tempsens/tempsens.htm
http://www.national.com/pf/LM/LM35.html
LIGHTSENSORS
Light sensors are used to measure the intensity of light. Mostly availablesensors are Cadmium
SulphideLDRsensor,IRsenorlikephotodiode,phototransistor,TSOP1738.ForbeginnersLDRiseasy
to handle. Soas a beginner better start with LED+LDR combination or IR LED+photodiode . LDR is
economicalthanothersensorsandeasytohandle.
LIGHTDEPENDENTRESISTOR(LDR):
LDR is basically a resistor whose resistance varies withintensity of light. More intensity less its
resistance (i.e, in black it offershigh resistance and in white it offers less resistance). This is the
basicsensorwhichbeginnersshouldstartwith,whichishavingcostlessthanRs.6.Figurebelowshow
someofthepicturesofLDRwhichiobtainedfromsomesite.
110|P a g e
Fig.1showsLDR'swithgreatersurface area;Fig.2showstheLDR'swhichare availableabout Rs.5,
which is commonly used. Greater surface area,better the sensing will be. The sensing material is
madeofCadmiumSulphide.
Resistance:400ohmto400Kohm
Normal resistance variation: 1Kohm to 10Kohm (in the robots which I used for line following for
identifyingblackandwhitestrips)
Sensitivity: about 3msec(Sensitivity is defined as the time taken for output to change when input
changes,igotthisreadingbyverifyingwithADCinterfacedwithparallelport,sensitivityofLDR'sisin
millseconds.Thisisthebestsensitivityobtainedtome).
Voltageratings:Iusediton3V,5Vand12V
PracticalapplicationinLinefollowerRobots:LED'sareusedwithLDRwhichwillactasasourceof
lightforLDRbecauseweareplacingtheLDRbelowtherobotwherelightisnotpresent.Ifwewant
toidentifyBlackandWhitestripsweaddalightsourcewithLDRandthewhitestripreflectslight
whileblackwon'treflectlight.
111|P a g e
Above figure shows how LED is placed with LDR. Here LDR is covered because we want light
reflections from ground only,not from sides of LED.Also cover the LED so that the light will move
pointed,sothatreflectionwilldirectlygotoLDR.WhenyouattachLEDandLDRtothebodyofthe
robot,usetapetopastethesensors.Rememberifyourobotbodyisofaluminum,thensomeshort
circuitorcurrentflowcanoccursthroughthebody.Soapplytapeperfectlysothatnoshortcircuit
problemsoccur.RememberthatLDRisaresistorandhavenopolaritywhileallothersensorshave.
PROBLEMS:LDRismainlyusedwithvisiblelight.SotheproblemofexternallightwillaffecttheLDR.
TheaffectofvisiblelightismoreinLDRthencomesPhotodiode,thenTSOP1738.
http://www.technologystudent.com/elec1/ldr1.htm
http://www.kpsec.freeuk.com/components/other.htm
http://www.mstracey.btinternet.co.uk/technical/Theory/theorysensors.htm
http://www.tpub.com/neets/book7/26g.htm
PHOTODIODE
Hereissomelinkforphotodiode:
http://www.radioelectronics.
com/info/data/semicond/photo_diode/photo_diode.php
http://en.wikipedia.org/wiki/Photodiode
http://www.lasermate.com/PR.htm
http://electron9.phys.utk.edu/optics421/modules/m4/photodiode.htm
Photo diode works in reverse biase region. A photo diode leads can be identified by seeing the
length of the leads. Short lead is the cathodeconnected to greater voltage. The current flowing
throughthephotodiodechangeswithintensityofthelight.Youcanuseitforedgedetection.Itried
todoedgedetectionofatable,igotrangeabout7cm.IRLEDisusedforproducinglight.Whenyou
are using IR LED be sure that it is working properly by measuring the voltage across the IR LED,
shouldbegreater than2V.WhenconnectingIRLEDthevoltageofthecircuit drops,sobecareful
thatvoltagetoothercircuitswon'tfallbelowthelevel.
112|P a g e
PhotodiodeandIRledlookssame.TheonlydifferenceisinitscolorIRLEDissomedarkincolor.If
youstillcan'tidentify.Seethispost
http://nod.phpwebhosting.com/~robotics/modules.php?name=Forums&file=viewtopic&t=435
PHOTOTRANSISTOR
I haven't used photo transistor. But a photo transistor is one in which base is like the receiver of
light.Whenlightfallstherewillbeashortcircuitbetweencollectorandemitter.Thiscanbeusedin
opticalcommunications.Iheardthatyoucanmakeaphototransistorbycuttingtheupperportion
oftransistorBC107andleavingthebase.YoucanuseeitherIRorlaser(cheaponeavailable).Butin
caseoftransmissionwerequirelineofsightpropagation.HereisacircuitfordetectionofIRusing
phototransistor.
http://www.kmitl.ac.th/~kswichit/LFrobot/LFrobot.htm
Herewhenlightisnottherethentheresistanceoftransistorwillbehigh,sotheV(pin2)>V+(pin3)
makingoutputofcomparatorLOW.Thatiswhennoreflectionfromgroundoranyobstacleonthe
IR.WhenlightistherethentheresistancewillbeverylessandV+>V.Sooutputofcomparatoris
HIGH. Suppose if you are using it for line detection, then there is reflection of IR from the white
surface,butIRradiationsareabsorbedbyblacksurface,sonoorlessreflectionfromthesurfacein
blackstrip.RemembertocheckthevoltageacrossIRtoseewhetherIRLEDisworkingornotandit
shouldbegreaterthan2V.Whenblackstripcomes,outputofcomparatorbecome0VandtheLED
glows(visiblelightLED).
113|P a g e
TSOP1738
SupplyVoltage(Pin2)VS0.3...6.0V
SupplyCurrent(Pin2)IS5mA
OutputVoltage(Pin3)VO0.3...6.0V
OutputCurrent(Pin3)IO5mA
Continuousdatatransmissionpossible
(upto2400bps)
Suitableburstlength.10cycles/burst
costRs.15
DISTANCEMEASUREMENTS
Forasmalldistancemeasurementwecanuseaphotodiodeorphototransistor,butonlydistance
upto57cm.YoujustconnecttheoutputtoADCoranycomparatortomeasurement.Supposeifwe
useoneLM324fordistancemeasurement,youcanmeasure1cm,2cm,3cm,4cm.Youjustconnecta
330ohminserieswithIRLED.Attheotherenduseaphotodiodeinreverseregion.
http://www.multyremotes.com/IRSw.htm
http://www.roboticsindia.net/modules.php?name=Forums&file=viewtopic&t=410
http://www.windowschallenge.com/Final%20Reports%5CFINAL%20RE
PORTFINAL.doc
http://www.robotroom.com/Infrared555.html
http://www.students.uwosh.edu/~piehld88/laser.htm
http://www.wanyrobotics.com/distance.html#
Ifyouwantagooddistancethenyoushoulduse38KhzmodulatedIRwithTSOP1738detector.Use
IC555togenerate38Khzsquarewave.Bettertutorialsavailableinroboticsindia,see
http://www.roboticsindia.net/modules.php?name=News&file=article&sid=32&mode=&order=0&th
old=0
http://www.roboticsindia.net/modules.php?name=News&file=article&sid=35&mode=&order=0&th
old=0
Youcangetrangeabout1Meter.IfyouwanttomeasurevariousdistancethenyoushouldvaryRa
oftheIC555.Supposeifyouwanttomeasuredistancefromafixedpoint,thenyouhavetovarythe
frequencyofIC555.YoucandoitfixingRb>Raand varyRasothatfrequencywillvaryslightlyfrom
some36Khzto40Khzandfindcorrespondingreading.Youcandoitbyusingthefollowingtechnique
114|P a g e
Supposeifyouwanttomeasuredistancefromafixedpoint.Thisisdonebyvaryingthefrequency.
When S1=1 thenRaeq=R1//Ra1= R1Ra1/(Ra1+R1). So this will produce a differentfrequency some
between36 to 40Khz. When S2=1 Raeq=R1//Ra2. Andwhen S1=S2=1 then Raeq=R1//Ra1//Ra2. By
varying S1,S2 you canmeasure the distance from it. But this mostly require the need of
somecircuitary. Better go for a microcontroller. Adjust Ra1,Ra2 so that desiredfrequencies are
obtained.
AbouttherangeofIRsensor
http://www.triindia.co.in/forums/viewtopic.php?t=12
http://www.triindia.co.in/forums/viewtopic.php?t=4
http://users.triera.net/zupanbra/senzor.html
COLORSENSING:
Ihaven'theardofavailabilityofcolorsensors.Butwecanmakeitfromscratch.Supposeifyouwant
tosensethecolorofball.Firstthingyouhavetobringrobotneartheball.Thedistanceoftheball
fromtherobotshouldbefixed.Secondthingtheeffectsofexternallight.Firstmaketherobotafixed
distancefromtheball.ThisismadebyusingaIRLED+photodiodecombination.Bringrobotcloseso
thatyouwillgetagoodresponse.ForsensingcoloryouuseLED+LDRcombination.Buttheproblem
withexternallightwillbehigherinthiscase.Soyoushouldprovidesomemechanicalmechanismto
hide external light. Photo diode or modulated38Khz+TSOP is used for distance measurement. But
photo diode is enoughto get distance about 5cm or near. Use comparator output to the output
ofphoto diode for distance measurement. Use LDR to sense the color. But theaccuracy is a real
problem.
RANGEFINDING:
http://www.roboticsindia.net/modules.php?name=Forums&file=viewtop
ic&t=148
SONAR
http://www.leang.com/robotics/info/articles/minison/minison.html
ANGLEMEASUREMENT
Supposeifyourrobotisgoingoveraninclinedplaneandwewanttomeasuretheinclinationofthe
plane then we should go for anglemeasurement. This is done simply using the principle of a
pendulum.Ifyougoesupaninclinedplaneapendulumkeptperpendiculartothegravitywillchange
its angle with normal. Attach a somewhat heavy ball tothe shaft of the variable resistor
(potentiometer). When robot goes up theplane, the inclination of the pendulum changes and the
shaftofthevariableresistorwillvary.YouconnecttheoutputofthevariableresistortoADCtoget
reading.Insteadofpendulumandvariableresistorkeepasourceoflightperpendiculartotheground
115|P a g e
18.1 AnalogSe
ensor
orconsistsof:
TheIRanalogsenso
Transm
mitter:AnInffraRedemittiingdiode
Receivver:APhototrransistor(also
oreferredasphotodiode)
ItisbeettertokeepR2asavariacctovarythessensitivity.
The ou
utput varies from 0V to 5V
5 depending upon the amount
a
of IR
R it receives, hence the name
n
analogg.
116|P a g e
Theou
utputcanbe takentoam
microcontrolleereithertoitsADC(AnalogtoDigital Converter)o
orLM
339caanbeusedasacomparato
or.
18.2 DigitalIRSensorT
TSOPSenssor
117|P a g e
TSOP1738Sensorisad
digitalIRSensor;Itislogic1(+5V)when
nIRbelowatthresholdisfaalling
onitandlo
ogic0(0V)wh
henitreceivessIRabovethreshold.
It does nott respond to any stray IR
R, it only resp
ponds to IR falling
f
on it at
a a pulse rate of
38KHz.Hen
ncewehaveaamajoradvan
ntageofhighimmunityaggainstambien
ntlight.
Nocomparratorisrequirredandtheraangeofthese
ensorcanbevariedbyvarryingtheinteensity
oftheIRem
mittingdiode(thevariacin
nfigure).
Chap
pter19 PrrojectWork
19.1 Linefollow
wingRobo
ot
ALLinefollowinggrobotisam
machinewhichcanfollowagivenpath.APathcanb
beintheform
mofa
black line
l
on a white surface or
o reverse of it. The Path can also be in the form of magnetic lines
which isoutofsco
opeofthisco
ourse.Suchro
obot
c
loop system havving a feedb
back
is a closed
mechaanism to co
orrect wron
ng moves. Line
following robots can
c
be drive
en using analog
compaarator based
d circuit likee opamp orr by
microccontroller both
b
using feedback ffrom
analoggordigitalsen
nsors.
Deetectionoflin
neisusuallyd
donebyemittting
lighto
onthesurfacee.Iflightgettsreflected back,
b
thenittiswhitesurrfaceelsetheesurfaceisbllack.
Emissionoflightis usuallydoneewiththehellpof
IRLEDs(LightEmitttingDiodes). Anarrayofssuch
LEDsiss used.Theeemitted light isthenreceived
using phototransisstors, LDR (LLight Depend
dent
Registeer),TSOP.Baasedonthevvalueoflight received,theereceiveden
nergyisconveertedtoelecctrical
energyy.
Ifttherobotgettsoffthetracck,thespeedofwheelmottorsisproporrtionallyvarie
edtomakeitback
ontheetrack.
Lin
ne following property of a robot is veery useful in designing au
utomated carrs. Also, indu
ustrial
robotssmayusesucchmechanism
minordertob
beonproperpath.
Blo
ockDiagramforLineFollowingRobot
118|P a g e
Chapter20DefinitionsofEmbeddedsystem
2:TypesofEmbeddedSys:
RealtimeEmbeddedSystems
NonRealtimeEmbeddedSystems
3:Nonrealtimeembeddedsystemisoneinwhichthereisnodeadline,eveniffastresponseor
highperformanceisdesiredorpreferred.
4:RealtimeEmbeddedSys
RealtimeEmbeddedSystemsareagainsubclassifiedas
Softrealtimeembeddedsystems
Hardrealtimeembeddedsystemsbasedontheconsequenceofmissingthedeadlinetime.
Hard realtimeembedded system, are one in which the completion of an operation after its
deadline is considered useless ultimately, this may lead to a critical failure of the complete
system(Missiledefencesystem,Anticollisionsystem).
Soft realtime system on the other hand will tolerate such lateness, and may respond with
decreased service quality (e.g., dropping frames while displaying a video) otherwise called as
gracefuldegradation.
5: CPU specific buzz words:A microprocessor incorporates most or all of the functions of a
centralprocessingunit(CPU)onasingleintegratedcircuit(IC).
6:WhatsMicrocontroller?:Amicrocontroller(alsoMCUorC)isasmallcomputeronasingle
integrated circuit consisting of a relatively simple CPU combined with support functions such as a
crystaloscillator,timers,watchdog,serialandanalogI/Oetc.
7:WhatsARM?:TheARMarchitecture(previously,theAdvancedRISCMachine,andpriorto
thatAcornRISCMachine)isthemostwidelyused32bitprocessorarchitectureintheworld.
8:PIC?:ItisafamilyofHarvardarchitecturemicrocontrollersmadebyMicrochipTechnology,
derived from the PIC1640 originally developed by General Instrument's Microelectronics Division.
ThenamePICinitiallyreferredto"PeripheralInterfaceController".
9:WhatsAVR?:TheAVR(Advancedvirtualrisc)isaModifiedHarvardarchitecture8bitRISC
singlechipmicrocontroller(C)whichwasdevelopedbyAtmelin1996.TheAVRwasoneofthefirst
microcontrollerfamiliestouseonchipflashmemoryforprogramstorage.
119|P a g e
10: THUMB : To improve compiled codedensity, processors from the ARM7TDMI on have
featuredtheThumbmode.Wheninthismode,theprocessorexecutes16bitinstructions.Mostof
these16bitwideThumbinstructionsaredirectlymappedtonormalARMinstructions.
11:WhatsanInterrupt?:Itisanasynchronoussignalfromhardwareindicatingtheneedfor
attention or a synchronous event in software indicating the need for a change in execution. A
hardware interrupt causes the processor to save its state of execution via a context switch, and
beginexecutionofaninterrupthandler.
12:WhatsaCrossCompiler?:Acrosscompilerisacompilercapableofcreatingexecutable
code for a platform other than the one on which the compiler is run. Cross compiler tools are
generallyfoundinusetogenerateexecutablesforembeddedsystemormultipleplatforms.
or
Itisatoolthatonemustuseforaplatformwhereitisinconvenientorimpossibletocompileon
that platform, like microcontrollers that run with a minimal amount of memory for their own
purpose.
14:WhatsaLinker?:Alinkerisaprogramthattakesoneormoreobjectsfilesgeneratedbya
compilerandcombinesthemintoasingleexecutableprogram.
15: Whats a Loader ?: It is the part of an operating system that is responsible for loading
programs from executables (i.e., executable files) into memory, preparing them for execution and
thenexecutingthem.
16:Systemsoftware:Systemsoftwareiscloselyrelatedto,butdistinctfromOperatingSystem
software. It is any computer software that provides the infrastructure over which programs can
operate,i.eitmanagesandcontrolscomputerhardwaresothatapplicationsoftwarecanperform.
Examples:OtherthanOS,Antivirussoftware,Communicationsoftwareandprinterdrivers.
17:Simulators:Aapplicationthatcreatesanenvironmentthatisascloseaspossibletoreality.
Inflightsimulators,engineerscreateacockpitenvironmentidenticaltotheoneinarealairplane.In
aflightsimulatorapilotwillsee,hearandfeellikeheorsheisinarealaircraft.
19:WhatsBottleneck?:Alimitofthroughputbetweencomputerprocessorandmemory.
20: Throughput: The maximum number of instructions a processor executes per unit time is
called its throughput. The same is the case for microcontrollers also. The higher the throughput(
whichagaindependsonvariousfactors)thebetteristheprocessor/microcontroller.
21:Instructionsetcapability:Thisreferstothecapabilitytheinstructionsetofthatparticular
microprocessor/ microcontrollers have such as with code density and DSP related instructions or
someinstructionswhicharecomplexlyimplemented.
22:Firmware:Itisatermsometimesusedtodenotethefixed,usuallyrathersmall,programs
thatinternallycontrolvariouselectronicdevices.
24:BoardSupportpackage:BSPisimplementationspecificsupportcodeforagivenboardthat
conforms to a given operating system. It is commonly built with a bootloader that contains the
minimaldevicesupporttoloadtheOSanddevicedriversforallthedevicesontheboard.
25: Boot Sequence : A boot sequence is the initial set of operations that the computer
performswhenitisswitchedon.Thebootloadertypicallyloadsthemainoperatingsystemforthe
computer
26: Watchdog Timer : A watchdog timer (or computer operating properly timer) is a computer
hardware timing device that triggers a system reset if the main program, due to some fault
condition, such as a hang.A special timer that is used specifically for the purpose of resetting the
system if it overflows. A piece of program resets the watchdog timer every so often before the
watchdogtimerexpires.However,iftheprogramfailstoresetthetimer,indicatingthattheprogram
has crashed or entered into some infinite loop(indicating unwanted and unexpected program or
systembehavior),thewatchdogtimeroverflowsandthisgeneratesaprocessorresetsignal.
27:Preemption:Preemption:Itistheactoftemporarilyinterruptingataskbeingcarriedout
by a computer system, without requiring its cooperation, and with the intention of resuming the
taskatalatertime.Suchachangeisknownasacontextswitch.
28:Multitasking:Multitaskingisamethodbywhichmultipletasks,alsoknownasprocesses,
sharecommonprocessingresourcessuchasaCPU.
29: MultiProcessing : Multiprocessing is the use of two or more central processing units
(CPUs)withinasinglecomputersystem.Thetermalsoreferstotheabilityofasystemtosupport
morethanoneprocessorand/ortheabilitytoallocatetasksbetweenthem.
30:Multithreading:Theabilityofanoperatingsystemtoexecutedifferentpartsofaprogram,
called threads, simultaneously. The programmer must carefully design the program in such a way
thatallthethreadscanrunatthesametimewithoutinterferingwitheachother.
31:POSIX :PortableOperatingSystemInterface,isthecollectivenameofafamilyofrelated
standards specified by the IEEE to define the application programming interface (API), along with
shellandutilitiesinterfacesforsoftwarecompatiblewithvariantsoftheUnixoperatingsystem.
32:MISRA:MotorIndustrySoftwareReliabilityAssociation.Thisassociationsetsstandardsand
guidelines for usage of C/C++ coding in safety critical systems such as automotive domain in
particular.127rulesincodingChastobefollowedwhichmakesCcodesocalledSafecode.
33: Fuzzy Logic : Fuzzy logic is a form of multivalued logic to deal with reasoning that is
approximateratherthanprecise.
Chapter21GLOSSARY
ADC:Acronymforanalogtodigitalconverter.Anelectronicdeviceorsystemthatencodes
analogvoltage/currenttoamultileveldigitalnumber.
121|P a g e
ADDRESSBUS:Agroupofsignalsinamicroprocessorsystemthatindicatestheaddressof
thememorylocationfromwherethedataistobereadorwrittento.
ASCII: American standards committee for information interchange.A 7bit coding scheme
foralphabets,numerals,punctuation,aswellascontrolcharacters.
ASIC:AcronymforApplicationSpecificIntegratedCircuit.
ASSEMBLER:Asoftwareprogramthattakesatextfilecalledthesourcefile,andconvertsit
intoanotherfilewiththemachineopcodes(simplycalledthemachinecodeorobjectcode).
BCD:AcronymforBinaryCodedDecimal.
BOD:BrownoutDetector.Anelectronicdevicethatdetectsadropinsupplyvoltagebelowa
thresholdandgeneratesasignaltoresettheprocessortillthesupplyvoltageisrestoredto
acceptablelevel.
BIT:Binarydigit.
Bps:AcronymforBitspersecond.
Byte:Anumberwithamaximumofeightbits.Thusthebytewidenumberisbetween0and
255(decimal).
CISC:Acronymforcomplexinstructionsetcomputer.Thisatypeofprocessorarchitecture
thatischaracterizedbyavariableinstructionlength,usuallysmallnumbersofregisterand
multipleaddressmodes.
COMPILER: A software program that converts a highlevel language source code into the
machinelanguagethattheprocessorcanexecute.
COUNTER:Aregisterthatisincrementedforeachoccurrenceofaneventonaninputpinof
thecounter.Theeventisindicatedbyapulse.Foreachpulse,thecounterisincremented
CRITICAL SECTION: A chunk of code that must be executed without any interruption for
properoperation.
CPLD:Acronymforcomplexprogrammablelogicdevice.Aprogrammablelogicdevicerich
ingatesandinterconnectioncircuitry.
CPU:Acronymforcentralprocessingunit.TheCPUisthecomputationalandcontrolunitof
acomputer.
DAC:AcronymforDigitaltoAnalogconverter.Adeviceoraprocessthatconvertsadigital
numbertoacorrespondinganalogvoltageorcurrent.
DataBus:Asetofsignalsthatcarriesthedatainformationbetweentheprocessorandthe
memoryand/orI/Odevices.
DEBUG:Tocorrectmistakesinaprogram.
122|P a g e
Dongle: A mechanism to ensure only authorized users can use a particular software with
the help of an electronic lock provided with the software to deter software piracy.The
dongleneedstobeconnectedtothePCparallelport,serialport,ortheUSBtobeabletouse
thesoftware.
DUPLEX:Termusedincommunicationsystemthatmeansthatboththetransmitterandthe
receivercansendandreceivesignalsatthesametime.
Embedded controller: A piece of hardware including some processor and software that
controlsadevice.
Emulator: Adevicethatmimicsthebehaviorandfunctionsofanotherdevice.Aprocessor
emulator.
EMI: Acronymforelectromagneticinterference.Thisisaphenomenonbywhichadevice
orasystemcangenerateanelectromagneticfieldintheradiofrequencyspectrumwiththe
potentialtodisruptoperationofotherelectroniccomponentsorsysteminthevicinity.
EEPROM:AcronymforElectricallyErasableandProgrammableReadOnlyMemory.
EPROM:AcronymforElectricallyProgrammableReadOnlyMemory.
FINITESTATEMACHINE:Adevicethatstoresthestatusofsomethingatagiventime,with
someinputsthatcanchangethestateandand/oroutputs.
FLAG:Abitusedbyaprogramtoremembersomethingortoconveybinaryinformationto
anotherpieceofprogram.
FLASHMEMORY:Anonvolatilememorythatcanbeerasedandreprogrammedinunitsof
memorycalledblocks.Thenameflashmemorymeansthememorycellscanbeerasedinan
electrontunnelingprocessinaflashbyremovinganelectronicchargefromafloatinggate
associatedwitheachmemorycell.
FPGA:AcronymforFieldProgrammableGateArray.Alargeanddenseprogrammablelogic
device.
FSM:Acronymforfinitestatemachine.
FullDuplex:SameasDuplex.
Glitch:Anunwantedtransientsignaltransitionfromthecurrentleveltotheotherleveland
backtotheoriginallevel.
HALFDuplex:Termusedincommunicationsystemsthatmeansthateitherthetransmitter
cansendorthereceivercanreceivesignalsatagiventime.
Handshake signal: control and feedback signals used between two(or more) devices to
facilitateexchangeofdata.
Hexadecimal:Abase16numbersystem.Thenumbersgofrom0to9,A,B,C,D,EandF.
123|P a g e
Host: A computer system acting as a master that provides services to other connected
devicesorsystems.
IC:Acronymforintegratedcircuit.Asemiconductorchipwithmanytransistorandresistors
connectedtomakeanelectroniccircuit.
ICE: Acronym for Incircuit emulator. A development tool for developing microprocessor
basedsystemanddevices.TheICEmimicstheoperationofthetargetprocessorduringthe
developmentprocess.
IIC or I2C: Acronym for InterIC communication. A communication bus with only two
signals.
Infrared:Partofthelightspectrumthatisjustabovethatofvisiblelightintheredendof
thespectrum.
IRDA:AcronymforInfraredDataassociation.IrDAisanindustrysponsoredorganizationto
designstandardsforthehardwareandsoftwareusedininfraredcommunicationlinks.
Instruction:Lowestlevelcommandgiventotheprocessorbyaprogram.
Interrupt:Anasynchronoussignalgeneratedbyaperipheraldevicetotheprocessorthat,
when asserted, indicates to the processor to take notice and execute a special piece of
programcalledanISR.
I/O: Input Output .peripheral devices of a processor to interact with the physical
environmentaroundit.
I/O map: A table containing the addresses,withinthe I/Ospace, ofthe inputand output
devicesofacomputersystem.
I/Ospace:AtypeofaddressingregionthatallowsaprocessortoconnectI/Odevices.
ISA: Acronym for industry standard architecture .ISA is a bus architecture used in IBM
personalcomputers.Itallowsconnectivitybetweenprocessorandtheassociatedperipheral
circuitsanddevices.
ISR:Acronymforinterruptsubroutine.Aprogramthatisexecutedbytheprocessorwhen
aninterruptoccursinacomputersystem.
Interruptvector:AddressofanISR.
Latency:Usuallyassociatedwiththeinterruptsinacomputersystemandreferstothetime
ittakestotakestorespondtoaninterruptsignal.
LED: Acronym for light emitting Diode. A semiconductor device that emits light when a
voltageofappropriatepolarityandvalueisappliedtoit.
124|P a g e
Logic analyzer: an instrument to observe digital signals as a function of time. The logic
analyzerhasaflurescentorLCDdisplaythatsignals.
Logicgate:Adigitalcircuitthathasoneormoreinputsandanoutput.Itperformsalogical
operation(suchasAND,OR,XOR,XNOR,NAND,NOR,NOT)ontheinputsandproducesaresult
onthe
Output.
Microcontroller:Amicrocomputeronasinglechip.
Microprocessor:AcentralProcessorunit(CPU)onasinglechip.
MNEMONIC:Anabbreviation,anaidforrememberingthecodeofaprocessor.
NVRAM: AcronymforNonvolatileRandomaccessmemory.RAMwithbatterybackupfor
retainingthecontentsoftheRAMwhenthemainpowerisputoff.
Objectcode:Aprogramthataprocessorcanexecutedirectly.
Pipeline:Referstoanintrernalimplementationofaprocessorinwhichtheinstructionsare
continuouslybeingfetchedbyasectionoftheprocessorandplacedinaqueueforexecution
sectionsectionoftheprocessor,whichinturnplacestheresultsinanoutputqueuetobe
stored back to the designated destination. A nonpipelined processor, on the other hand,
fetches an instruction, executes it, and stores the results before fetching the next
instruction. Pipelining improves overall execution speed because of overlapping of the
variousstagesofprogramexecution.
PLD:AcronymforProgrammableLogicDevice.Adigitalcircuitwhosefunctionalitycanbe
changed as per the logic required. The PLD has a combination of AND,OR and NOT gates
connectedthroughanetwork.Bychoosingtherightgatesandtherightinterconnects,the
PLDcanbemadetoimplementanylogicfunction.
ProgramCounter:SameasInstructionPointer.
PWM:AcronymforPulseWidthModulation.InPWM,thepulsewidthofthefrequencyis
changedwhilekeepingthefrequencyconstant.ThischangestheDCvalueofthesignal.For
lowwidthpulse,theDCValueissmallerthanapulseofhigherwidth.
RAM: Acronym for Random Access Memory. A memory device any part of which can be
accessed directly. In the early days of computing, this was contrasted with tape memory,
which was sequential access memory. Now RAM usually means some sort of volatile,
read/writememory.
RISC:AcronymforReducedInstructionSetComputer.Atypeofcomputerarchitecturewith
a small number of minimum instructions, characterized by a very regular instruction
structure of fixed length, a loadstore approach to memory access, and a large number of
register.ContrastitwithCISC.
125|P a g e
RESET: To restart. A signal in a processor that initializes the internal register and control
circuittoadefaultvalueandstartsexecutingtheprogramfromthefirstmemorylocation.
RESETVECTOR:Addressofresetcode.
RESETADDRESS:Theaddressthattheprocessorfirstaccessesforthefirstinstruction,after
theresetsignalisapplied.
RESETPOINTER:Addressoftheresetcode.
RESETCODE:Theprogramthattheuserwritesaspartofthesysteminitialization.
Rs232:Aprotocolforserialasynchronoustransferofdata.
Simulator:Asoftwareformonitoringtheexecutionofaprogram.Simulatorallowstheuser
toexecutetheprograminstructionandinspectregister,memoryandI/Oportcontents.The
simulatorallowssectionofprogramtorunatfullspeedbyplacingbreakpoints.
SPI: Acronym for serial peripheral Interconnect. A fourwire serial synchronous serial
communicationprotocolbetweentwodevicesorICs.
STACK:aread/writestoragespaceusedforstoringthereturnaddressofacallingprogram.
Thestackhasalastinfirstoutstructure.Thevaluewrittenlastisreadfirst.
StackPointer:Anaddressregisterthatpointstothecurrenttoplocationinthestack.
Timer:Acounterthatisincrementedbyaclocksignal.
Targetdevice:Referstotheprocessorinthetargetsystemthatisunderdevelopment.
Chapter22References
[1]Atmega16Datasheet
[2]www.wikipedia.org
[3]http://www.cmosexod.com/micro_uart.htm
[4]http://www.bestmicrocontrollerprojects.com/hardwareinterrupt.html
[5]http://www.avrtutor.com/tutorial/interrupt/interrupts.php
126|P a g e
Experiment Book
TableofContents
OverviewofBreadBoard...............................................................................................................6
Experiment1:MonostableandAstableMultivibratorusingthe555IC.........................................10
ProblemStatement...........................................................................................................................10
CircuitDiagram.................................................................................................................................10
Calculation........................................................................................................................................10
Experiment2:CounteronSevenSegmentDisplay........................................................................11
ProblemStatement...........................................................................................................................11
PartA:...............................................................................................................................................11
PartB:................................................................................................................................................12
Experiment3:IntroductiontoLDRandOperationalAmplifier.......................................................13
ProblemStatement...........................................................................................................................13
Experiment4:LDRbasedcounter.................................................................................................14
ProblemStatement...........................................................................................................................14
OverviewofAVRbasedTrainerBoard..........................................................................................15
INTRODUCTION.................................................................................................................................15
FEATURES..........................................................................................................................................16
HOWTOUSETHEMANUAL..............................................................................................................17
MODULELIST&DISCRIPTION...........................................................................................................18
1A.MicrocontrollerModule:Primary...............................................................................................18
1B.MicrocontrollerModule:Secondary...........................................................................................18
2.SerialProgrammerModule...........................................................................................................19
3.SerialInterfaceModule.................................................................................................................18
4A.SensorModule:Analog...............................................................................................................19
4B.SensorModule:Digital................................................................................................................22
5.LCDinterfaceModule...................................................................................................................23
6.LEDarraymodules........................................................................................................................24
7.SwitchpadModule........................................................................................................................24
8.VariacModule...............................................................................................................................25
9.MotorDriverModules..................................................................................................................24
10A.ExternalConnectionmodulefordigitalIRsensors...................................................................25
10B.ExternalConnectionmoduleforBuzzers,relaysetc................................................................27
11.Powersupplymodule.................................................................................................................28
EXPERIMENTSINEMBEDDEDSYSTEMS.........................................................................................29
Experiment1:DigitalInput/OutputinaMicrocontroller..............................................................28
FamiliarizingwithAtmega16............................................................................................................28
PartA:ToglowavisiblelightLEDusingAtmega16.........................................................................29
ProblemStatement...........................................................................................................................32
CircuitOverview................................................................................................................................32
PartB:UsingaresetswitchtooperateanLED.................................................................................33
ProblemStatement...........................................................................................................................34
CircuitOverview................................................................................................................................34
PartC:MakingdifferentLEDglowpatterns.....................................................................................35
ProblemStatement...........................................................................................................................35
CircuitOverview................................................................................................................................35
PartD:...............................................................................................................................................35
ProblemStatement...........................................................................................................................35
CircuitOverview................................................................................................................................35
Experiment2:Tointerfacea16x2LCDwithAtmegaandimplementtheLCDfunctions................36
LCDconnections................................................................................................................................36
PartA:ToprintaconstantstringonLCD..........................................................................................37
ProblemStatement...........................................................................................................................37
SomeoftheusefulLCDfunctions:....................................................................................................37
CircuitOverview................................................................................................................................37
PartB:ToprintstringsinlooponLCD..............................................................................................38
ProblemStatement...........................................................................................................................38
CircuitOverview................................................................................................................................38
PartC:DisplayofintegerdataonLCD.............................................................................................39
ProblemStatement...........................................................................................................................39
PrintinganintegeronLCD................................................................................................................39
PartD:DisplayoffloatingpointdataonLCD...................................................................................40
ProblemStatement...........................................................................................................................41
PrintingafloatingpointnumberonLCD..........................................................................................41
Experiment3:Interfacinga16keykeypad....................................................................................42
ProblemStatement...........................................................................................................................42
DesigningofKeypad..........................................................................................................................42
Logicbehindthecodeusedtointerface...........................................................................................43
CircuitOverview................................................................................................................................43
Experiment4:WorkingwithTimersCTCmode............................................................................44
TimerinCTCmode............................................................................................................................44
PartA.................................................................................................................................................44
ProblemStatement...........................................................................................................................44
PartB.................................................................................................................................................45
ProblemStatement...........................................................................................................................45
Connectingaspeaker........................................................................................................................46
CircuitOverview................................................................................................................................46
Experiment5:WorkingwithTimersFastPWMmode.................................................................46
TimerinFastPWMmode.................................................................................................................46
ProblemStatement...........................................................................................................................46
Experiment6:WorkingwithADC(AnalogtoDigitalConvertor)....................................................47
AnalogtoDigitalConvertor..............................................................................................................47
InitializingADC..................................................................................................................................47
ProblemStatement...........................................................................................................................47
CircuitOverview................................................................................................................................47
Experiment7:DatacommunicationbyUART................................................................................48
PartA:...............................................................................................................................................48
ProblemStatement...........................................................................................................................48
CircuitOverview................................................................................................................................48
PartB:................................................................................................................................................48
ProblemStatement...........................................................................................................................48
CircuitOverview................................................................................................................................48
PartC:................................................................................................................................................48
ProblemStatement...........................................................................................................................48
CircuitOverview................................................................................................................................48
PartD:...............................................................................................................................................48
ProblemStatement...........................................................................................................................48
CircuitOverview................................................................................................................................48
Experiment8:DatatransferbySPIprotocol..................................................................................49
ProblemStatement...........................................................................................................................49
CircuitOverview................................................................................................................................49
Experiment9:UsingExternalInterrupts........................................................................................50
ProblemStatement...........................................................................................................................50
CircuitOverview................................................................................................................................50
EXPERIMENTSINROBOTICS/AUTOMATION..................................................................................51
Experiment1:AnalogIRSensor....................................................................................................51
PartA:InterfacingAnalogIRSensorwithmicrocontrollerandtodisplayvariationinoutputon
LCD....................................................................................................................................................51
ProblemStatement...........................................................................................................................51
CircuitOverview................................................................................................................................51
PartB:AnalogIRSensorusedasacolorsensor..............................................................................51
ProblemStatement...........................................................................................................................52
PartC:AnalogIRSensorusedfordistancemeasuring....................................................................52
ProblemStatement...........................................................................................................................52
Experiment2:DigitalIR(TSOP)sensor.........................................................................................53
PartA:InterfacingDigitalTSOPIRSensorwithmicrocontrollerandtodisplayvariationinoutput
onLCD/LED......................................................................................................................................53
ProblemStatement...........................................................................................................................53
CircuitOverview................................................................................................................................53
PartB:DigitalTSOPIRSensorusedascontrastvariationdetectionsensor....................................54
ProblemStatement...........................................................................................................................54
PartC:DigitalTSOPIRSensorusedasobjectdetectingsensor......................................................54
ProblemStatement...........................................................................................................................54
Experiment3:MotorControlusingdriverL293.............................................................................55
ProblemStatement...........................................................................................................................55
CircuitOverview................................................................................................................................55
Experiment4:SpeedcontrolofDCMotor....................................................................................55
ProblemStatement...........................................................................................................................55
CircuitOverview................................................................................................................................55
Experiment4:Automation...........................................................................................................56
PartA:ControllingMotorthroughsensors......................................................................................56
ProblemStatement...........................................................................................................................56
CircuitOverview................................................................................................................................56
PartB:SwitchingRelay/Transistorthroughsensors.........................................................................57
ProblemStatement...........................................................................................................................57
CircuitOverview................................................................................................................................57
LINEFOLLOWERROBOT................................................................................................................57
OverviewofBreadBoard
BREADBOARD
Breadboard is used to make circuits. But mostly after testing your circuits on
breadboard you will be making PCB. But I never made PCB for any of my circuits.
Normally everyone says that if you connect on breadboard then wires may get loose
and circuit will get disturbed due to shock.But no such problem occurred to me, all
you have to do is to do a good wiring.Then you can gain time for making PCB's.
This breadboard has a medium sized holes.I mostly prefer this one. But I have not
seen this breadboard nowadays. The one which is available nowadays is given below.
Breadboards costs from Rs.80-120(depends on place where you are in India).
The main problem with small holes is that, it will be tough to insert IC's like 7805
,power transistors so on.Even there is problem with size of wires also.
WIRING
Following figures show good wiring practices you should follow so that your circuit
won't be disturbed by any shocks.
In this you can see that the length of the wires used are of exact length between two
points. If you do this type of wirings then no problems occur. But in this you can see
that resistor is not properly inserted, for this you should cut the leads of the resistor
so that its body is just touching(or touching the breadboard).
Above figures shows how to make good connections. In last one you can see how they
made connections so that no problems will occur. Below you can see what
connections you should not have to do.
EXPERIMENTSINBASICELECTRONICS
Experiment1:MonostableandAstableMultivibratorusingthe555IC
ProblemStatement
Using555ICdesignanastablemultivibratorwithTimeperiod=1secanddutycycle=0.75.
CircuitDiagram
Calculation
TakeC=100uF
Calculate
Hint:
and
forT=1secanddutycycle=0.75.
2
2and
10
Experiment2:CounteronSevenSegmentDisplay
ProblemStatement
PartA:MakeaCounterusingIC4029whichcountsfrom09andchecktheresultusingLEDs.
Note:LogicHigh+5V LogicLow0V
Stepstobeperformed:
1. Setpinnumber1,5,8and9tologiclow.
2. Setpinnumber10and16tologichigh.
3. TheoutputinastablemultivibratorfromIC555servesastheclockforthecountercircuit.
ConnecttheoutputoftheIC555topin15of4029.
4. Connectpins2,6,11and14tothegroundthrougha220ohmresistorandanLED.These
serveasoutputpinsofthecounter.ThesequencefromMostSignificantBit(MSB)toLeast
SignificantBit(LSB)ispin2,14,11,6i.e.Q4,Q3,Q2,Q1.
11
PartB:Toviewtheoutputofthe4029counteronaSevenSegmentDisplayusingtheIC7447.
Stepstobeperformed:
1. ThepinconfigurationofthesevensegmentdisplayandIC7447isshowninthefigure.
Connectthepins9through15ofIC7447tothecorrespondingletterpinsoftheseven
segmentdisplay.
2. Connecttheoutputofthe4029totheinputpins1,2,6and7ofthe7447ICwithAbeingthe
LSBandDbeingtheMSB.SotheinputtotheICisDCBA.
3. Makethepins3,4and5oftheIC7447logichigh.
4. Connect+5Vtopin16andground(0V)topin8oftheIC7447.
5. AlsogroundboththeCOMpinsofthesevensegmentdisplay.
12
Experiment3:IntroductiontoLDRandOperationalAmplifier
ProblemStatement
CheckthechangeinpotentialacrossanLDRusingamultimeterwhenlightfallsonit.Digitalizethe
analogoutputusinganOpampinComparatormode.
AssembletheabovecircuitandmeasurethevoltageacrosstheLDRwithadigitalmultimeter
withandwithoutanylightincidentonit.
AssembletheaboveshownOpampcomparatorcircuitandsetVinasthevoltageacrossthe
LDRinthepreviouscircuit.
SetVrefasthevoltageatwhichthecomparatoroutputishighwiththelightincidentonLDR
andlowwithnolightincidentonit.
13
Experiment4:LDRbasedcounter
ProblemStatement
DesignaLDRbasedcountercircuittoincrementbyonewheneverlightfallsontheLDR.IC555is
usedinmonostablemodesothatcounteritistriggeredonlywhenthereisafallingedgeatits
Triggerpin.
Assembletheabovecircuit,takeR=9.1kandC=100uF.(T=RCln3)
GivetheoutputoftheOpampinExperiment3topin2(Trigger)ofLM555.Thisservesasa
methodtotriggermonostablemultivibratorwheneverabarrierisplacedinfrontoftheLDR.
Assemblethecounterandthesevensegmentdisplaycircuitasinexperiment2andconnect
theoutputpin3ofthemultivibratorcircuittopin15(Clock)ofIC4029.
Theresultingsystemshouldbehaveasacounterwhichcountsthenumberoftimeslighthas
beenblockedinfrontoftheLDR.
14
OverviewofAVRbasedTrainerBoard
INTRODUCTION
TheEmbeddedDevelopmentBoardprovidedtoyouhasbeendesignedkeepinginmindtheneedsof
engineeringstudentsandenthusiastssothattheycanmatchuptothepresentindustrystandards
onlatestdevelopmentsintherisingfieldofEmbeddedSystemsDesign/Developmentandisbetter
thananyexistingboardsavailableinthemarket.
TheboardhasbeenintensivelydesignedtocoverallexistingfeaturesofAVRmicrocontrollersandis
readytousewithitssupportingequipmentmountedintheperiphery.
FEATURES
ATmega16&8microcontrollerswithfacilityof
Onboardserialprogrammer.
OptionforInSystemProgramming(ISP)basedonexternallyprovidedSTK500platform.
OnboardDigitalandAnalogIRsensors.
RS232serialinterfaceforestablishingconnectionsbetweenthemcuandcomputersystem.
OnboardLEDarrays,keypadandexternalconnectionsforinterfacinganumberofdevices.
Onboardmotordrivercircuitsetc.
15
HOWTOUSETHEMANUAL
Theboardhasbeendividedinmodulesandeachmodulehasbeenthusdescribedwithproperpart
details,circuitdiagramandDIYconnectiondiagram.
MODULELIST&DISCRIPTION
1A.MicrocontrollerModule:Primary
FeaturesanATmega16microcontrollerwith
ConnectorsforPortsA,B,C&D
Aref(referencevoltage)
SPI
16MHzexternalcrystaloscillatorUARTSlaveselect
Resetswitch
Ext.GND
16
1B.MicrocontrollerModule:Secondary
FeaturesanAtmega8microcontrollerwith
ConnectorsforPortsB,C&D
SPI(pin6,7,8,9,10,11)
16MHzexternalcrystaloscillator
UART
Slaveselect
Resetswitch
Ext.GND
17
2.SerialProgrammerModule
RS232SerialPort
ConnectorforSPI
3.SerialInterfaceModule
RS232Serialport
18
ConnectorforUART
MAX232IC&circuitry
4A.SensorModule:Analog
TxRx
Associatedcircuitry
ConnectorforOutput
19
4B.SensorModule:Digital
IRTxLED
TSOP1738IRRx
Associatedcircuitry
Connectorforoutput
20
5.LCDinterfaceModule
16pinLCDconnector
PORTconnector
Contrastcontrol
21
6.LEDarraymodules
Features8LEDarray
PORTconnector
Associatedcircuitry
7.SwitchpadModule
8Switchpad
PORTconnector
ExternalVCC/GND
22
8.VariacModule
4VariacsforADCandmisc.applications
OutputPinsforinterfacing
23
9.MotorDriverModules
ICl293D
Outputpinsformotors
Connectorsforspeed&directioncontrol
24
10A.ExternalConnectionmodulefordigitalIRsensors
Supportsasmanyas8TSOPbasedIRsensors
PORTconnectorsforinterfacingwithatmega
25
10B.ExternalConnectionmoduleforBuzzers,relaysetc
Supportsvarietyofdevicesforinterfacingpurposes.
Forexamplevarietyofrelays,buzzers.
NPNtransistorsareusedassimpleswitches.
26
11.Powersupplymodule
IC7805
Associatedcircuitry
Outputfor5Vsupplyout
27
EXPERIMENTSINEMBEDDEDSYSTEMS
Experiment1:DigitalInput/OutputinaMicrocontroller
FamiliarizingwithAtmega16
28
AboveshownisthepinconfigurationofAtmega16IC.
Itisa40pinICwithpinnumbersstartingfromtheleftsideoftheUshapednotch.
Pinnumbers11and31shouldbeconnectedtoground.
Pinnumber10isconnectedto+5volts.
Pinnumbers32(AREF)and30(AVCC)areshortedandconnectedto+5volts.
Pinnumber9(RESET)shouldbeconnectedto+5voltsthroughapullupresistorasshown
below.
RESETpin
PartA:ToglowavisiblelightLEDusingAtmega16
ProblemStatement
1. ConnectaLEDtopinnumber40i.e.PA0ofAtmega.
29
2. Connectthepositiveend(longerleg)oftheLEDtothepinandthenegativeend(shorter
leg)togroundviaa220Ohmresistor(asshown).
3. ProgramtheICtoswitchonandofftheLEDaftercertaintimeintervals.
4. Considermodule1A/1Bformcuandmodule6forLEDarrayconnections.
CircuitOverview
LED
Atmega16
PartB:UsingaresetswitchtooperateanLED
ProblemStatement
1. MaketheLEDconnectionsasinpreviousexperiment.
2. Connectaresetswitchtopinnumber1i.e.PB0ofAtmega.
3. Connectonelegoftheswitchtogroundandtheotherlegtothepinpulledupbya10KOhm
resistor(asshown).
30
PORTB.0
4. MakePB0asinputpinandprogramtheICtocontroltheLEDwiththeswitch.
5. Considermodule1Aformcu,module6forLEDarrayandmodule7forswitchpad
connections.
6. NowintegrateasmanyswitchesandLEDsasyouwantandglowthemusingswitchesby
makingchangesintheprogramcode.
CircuitOverview
LED
Atmega16
SWITCH
PartC:MakingdifferentLEDglowpatterns
ProblemStatement
1.
2.
3.
4.
Connect8LEDstotheentirePORTCofAtmegai.e.pinnumber33to40.
EachLEDistobeconnectedinthemannershownbefore.
ProgramtheICtodisplaydifferentLEDpatternsusingthePORTCI/Opins.
Someofthepatternsforpracticeare:
LEDsglowinalinewithcertaindelayinbetween.
AlternativeglowingLEDs.
Convergingpattern.
Divergingpattern.
31
5.Considermodule1Aformcu,module6forLEDarrayconnections.
CircuitOverview
Atmega16
Setof8LEDs
PartD:TochangepatternofglowingLEDsusingswitch
ProblemStatement
1.
2.
3.
4.
MaketheLEDconnectionsasbefore.
MaketheswitchconnectionstoPB0asbefore.
ProgramtheICtodisplaydifferentLEDpatternsonthepressandreleaseoftheswitch.
Considermodule1A/1Bformcu,module6forLEDarrayandmodule7forswitchpad
connections.
CircuitOverview
Atmega16
Setof8LEDs
SWITCH
Experiment2:Tointerfacea16x2LCDwithAtmegaandimplement
theLCDfunctions
32
LCDcon
nnections
Conneecta16x2LCD
DwithPORTC
CofAtmegaaasperthecon
nnectionssho
owninmodule
5.
2LCDalreadyydoneonBoaard
Actualconnecttionsfor16x2
Note:PortX==C
PartA:Toprinta
aconstanttstringonLCD
Problem
mStateme
ent
1. InitializetheLCDatPORTCintheCVAVRgraphicalinterface.
2. ProgramtheAtmegatodothefollowing:
STATICPRINTINGPrintyournameatdifferentlocationsoftheLCD.
SomeoftheusefulLCDfunctions:
lcd_clear()ClearstheLCD.
lcd_gotoxy(x,y)Takesthecursortothecoordinate(x,y).
lcd_putchar(c)PrintsthecharactercontheLCD.
lcd_puts(str)PrintsthestringstrontheLCD.
lcd_putsf(ABC)PrintsABContheLCD.FunctionusedtoprintconstantstringsonLCD.
CircuitOverview
Atmega16
LCD
PartB:ToprintstringsinlooponLCD
ProblemStatement
1. InitializetheLCDatPORTCintheCVAVRgraphicalinterface.
2. ProgramtheAtmegatodothefollowing:
34
DYNAMICPRINTINGPrintyournameandmakeitmove(left/right)onLCD.
CircuitOverview
Atmega16
LCD
PartC:DisplayofintegerdataonLCD
ProblemStatement
1. MaketheLCDconnectionsasinpreviousexperiment.
2. ProgramtheICtoprintthefollowingontheLCD:
Yourdateofbirth
PrintinganintegeronLCD
Create acharacterbufferwithsizeatleast1morethanthenumberofdigitsinthe
integer.
itoa(int,char[n])Thisfunctionconvertstheintegertoastring.
Uselcd_puts()toprintthestringontheLCD.
ExampleToprint99ontheLCD
inta=99;
charbuff[3];
itoa(a,buff);
lcd_gotoxy(0,0);
lcd_puts(buff);//prints99atlocation(0,0)
PartD:DisplayoffloatingpointdataonLCD
ProblemStatement
1. MaketheLCDconnectionsasinpreviousexperiment.
2. ProgramtheICtoprintthefollowingontheLCD:
YourclassXIIboardpercentage
35
PrintingafloatingpointnumberonLCD
Create acharacterbufferwithsizeatleast1morethanthenumberofdigitsinthe
floatnumber.(decimalpointcountedasadigit)
ftoa(float,int,char[n])Thisfunctionconvertstheintegertoastring.
Thesecondargument(int)ofthefunctiondecidesthenumberofplacesafter
decimalinthestringcreated.
Uselcd_puts()toprintthestringontheLCD.
ExampleToprint99.99ontheLCD
floata=99;
charbuff[6];
ftoa(a,2,buff);
lcd_gotoxy(0,0);
lcd_puts(buff);//prints99.99atlocation(0,0)
Experiment3:Interfacinga16keykeypad
ProblemStatement
1. Interfacethegiven16keykeypadtothe8pinsofPORTAofAtmega.
2. MakeconnectiontoLCDwithPORTCasdonebefore.
3. PressthekeysofkeypadonebyoneandobtaincorrespondingdisplayonLCD.
4. Considermodule1A/1Bformcuand16matrixkeypadconnections.
36
DesigniingofKeypad
Sch
hematic
The16resetswitchesare
econnectedinasquarematrixfashionwith8outputwires
onnectedto
oan8pinFRCfemaleconnector.
co
Logicbehindthecodeused
dtointerfa
ace
Fiirstlythefirsstfourpinso
oftheport(verticalliness)aremadeasoutputpinswith0
outputandth
heremaininggfour(horizzontallines)aremadein
nputpinswitthaninternaal
pullup.
Iffanyswitchispressedth
hena0appeearsononeofthehorizo
ontallinewhenitisread
d.
In
nthesecond
dpartthefirrstfourpinsaremadein
nputpinswitthinternalpullupand
reemainingfou
uraremadeeoutputpinsswith0outp
put.
Iffanyswitchispressedth
hena0appeearsononeoftheverticcallinewhen
nitisread.
Thiswaytheexactswitch
hpressedisdetermined.
CircuitOverview
Atmega16
LCD
16keyKeypad
Experiment4:WorkingwithTimersCTCmode
TimerinCTCmode
InCTCmodedutycycleisfixedto50%,butfrequencyofpulsecanbeselected.
InthegraphicalinterfaceofCVAVRuseTimer0andTimer2forCTCmode.
Dofollowingsettings:
ClocksourceSystemclock
ClockvalueSelectanyfromthelistasperfrequencyrequired.Callitft
ModeCTCtop=OCRx(x=0or2)
OutputToggleoncomparematch
IntheprogramwritethevalueofOCRxregister.Thisdeterminestheoutputfrequency
accordingtotheformula:
38
f=ft/(2x(OCRx+1))
TheoutputpulseisobtainedatPB3(forTimer0)andPD7(forTimer2).
Considermodule1Aformcupinconnections.
PartA
ProblemStatement
1. ProgramtheAtmegatogenerateaclockofthefollowingtwofrequenciesusingCTCmode:
38kHz
120kHz
2. Measurethefrequencyandthevoltageusingadigitalmultimeterandcomparewith
theoreticalpredictions
Theoreticalvalue
Frequency
Experimentalvalue
Frequency
Theoreticalvalue
Voltage
Experimentalvalue
Voltage
39
38kHz
120kHz
2.5V
2.5V
PartB
ProblemStatement
Generateaclockpulseoffrequencyintheaudiblerange(20Hzto20kHz)andapplyitona
speakertomakeabuzzer.
Connectingaspeaker
Connectonewireofthespeakertogroundandtheotherwiretotheoutputpinofthe
timer.
Considermodule1Aformcu,module10BforExternalBuzzersconnections.
CircuitOverview
Atmega16
Speaker
Timer
40
Experiment5:WorkingwithTimersFastPWMmode
TimerinFastPWMmode
InFastPWMmodefrequencyisfixed,butdutycycleofpulsecanbeselected.
InthegraphicalinterfaceofCVAVRuseTimer0,Timer1andTimer2forFastPWMmode.
Dofollowingsettings:
ClocksourceSystemclock
ClockvalueSelectanyfromthelistasperfrequencyrequired.Callitft
Thefrequencyofthepulsewouldthenbefixedtoft/256.
ModeFastPWMtop=FFh
OutputNonInvertedPWM(InvertedPWMisjustthenegationofthis).
IntheprogramwritethevalueofOCRxregister.Thisdeterminestheoutputdutycycle
accordingtotheformula:
DutyCycle=(OCRx/256)x100%
Theoutputvoltagemeasuredbymultimeterisgivenby:
Voltage=(OCRx/256)xVcc
TheoutputpulseisobtainedatPB3(forTimer0),PD4(forTimer1B),PD5(forTimer1A)and
PD7(forTimer2).
Considermodule1Aformcuconnections.
41
ProblemStatement
1. TogeneratepulseswithdutycyclebyusingtimerinPWMmode:
25%
50%
75%
2. MeasurethefrequencyandtheaverageDCvoltageusingadigitalmultimeterandcompare
withtheoreticalpredictions.
DutyCycle
Theoreticalvalue
Frequency
25%
50%
75%
Experimentalvalue
Frequency
Theoreticalvalue
Voltage
Experimentalvalue
Voltage
42
Experiment6:WorkingwithADC(AnalogtoDigitalConvertor)
AnalogtoDigitalConvertor
AtmegaoffersinbuiltADCfacilityatPORTAi.e.pinnumber33to40.
VoltageappliedtotheADCpincanvaryfrom0voltstothevoltageappliedatAREFpini.e.
pin32ofAtmega.
Thedigitalconversioncanbe8bitor10bitatthediscretionoftheuser.
FunctionusedtoreadtheADCvalueisread_adc(x)(xisthepinnumberrangingfrom0
to7).Itreturnsanintegercorrespondingtothevoltageatthepin.
Considermodule1AformcuADCconnections.
InitializingADC
IntheCVAVRgraphicalinterface,clickonADCandenablethefacility.
Bydefault10bitconversionisdone.SelectUse8bitsoptionfor8bitconversion.
VoltagereferencecanbemadeAREForAVCCsincebothpinsareshorted.
ClockrepresentstheADCsamplingfrequency.Selectitas125,000kHz.
ProblemStatement
43
Makeavoltagedividercircuitusinga1kOhmresistoranda1kOhmpotentiometer
(asshown).
ConnectittooneoftheADCpinsofAtmega16andreadtheADCvalue.
Connecta16x2LCDatPORTCofAtmegaanddisplaythefollowingonLCD:
Correspondingdigitalvoltage8bit/10bit(dobothcases)
Correspondingvoltagevalues(inVolts)
Considermodule1AformcuADC,module8forVARIACandmodule5forLCDconnections.
CircuitOverview
ADCof
Atmega16
LCD
Potentiometer
Circuit
Experiment7:DatacommunicationbyUART
44
PartA:Tosendcharactersfrommicrocontrolleranddisplayingoncomputerscreen.
ProblemStatement
1. InitializeUARTofAtmega16withfollowingparameters:
CommunicationParameters:8Data,1Stop,NoParity
USARTReceiver:On
USARTTransmitter:On
USARTMode:Asynchronous
USARTBaudrate:9600
2. WriteaprogramtocontinuouslysendacharactertthoughUART.
3. ConfirmthetransferofdataoncomputerusingsoftwareDocklight.Keepthesame
communicationparameters.
4. Considermodule1AformcuUARTconnections,module3forSerialInterfaceModule
connections.
CircuitOverview
Atmega16
SerialPort
MAX232
Docklight
Computer
PartB:TosendADCvaluesfromuCtocomputer.
ProblemStatement
1. Designavoltagedividercircuitusingpotentiometertogenerateanalogvoltages.
2. ConnecttheanalogoutputtoPA0
45
3. InitializetheUARTinpreviouspartsmode.
4. Writeaprogramtoconverttheanalogvoltageto8bitdigitalwordandtransfer
continuouslytocomputerusingUART.Giveadelayof>20msbetweentwo
readingstoavoidcrashingofcomputer.
5. MonitorthevaluesinintegermodeoncomputerusingsoftwareDocklight.
6. Varythepotentiometerandanalyzethereadings.
CircuitOverview
Atmega16
MAX232
SerialPort
Potentiometer
Docklight
Computer
PartC:TosendcharactersfromcomputerkeyboardtouCandprintonLCD.
ProblemStatement
1. InitializetheUARTasbefore.
2. UsingDocklightsenddatafromthecomputertotheuCviaUARTprotocol.
3. MakeLCDconnectionstoPORTCofAtmega.
46
4. WriteaprogramtodisplaythereceiveddataontheLCD.
5. Considermodule1AformcuUARTconnections,module3forSerialInterfaceModule
connectionsandmodule5forLCDconnections.
CircuitOverview
Docklight
Computer
SerialPort
LCD
Atmega16
MAX232
PartD:TosendcharactersfromoneuCtoanotheranddisplayingitonLCD.
ProblemStatement
1. InitializeUARTonbothmicrocontrollersasbefore.
47
2. Makeoneofthemasthereceiverandtheotherasthetransmitterwithsameparity
3.
4.
5.
andbaudratesettingsinboth.
ConnecttheRxpinofuC1toTxpinofuC2andTxpinofuC1toRxpinofuC2.
Makesurethatthegroundconnectionsofboththemicrocontrollersaresamefor
propercommunication.
WriteaprogramtosendcharactersfromoneuC.
ReceivethemontheotheruCanddisplaythemona16x2LCDconnectedtoPORTC.
6.
7. Considermodule1A/1BformcuUARTconnections.
CircuitOverview
Atmega1
Through
UART
Atmega2
LCD
Experiment8:DatatransferbySPIprotocol
ProblemStatement
1. InthegraphicalinterfaceofCVAVR,enableSPIanddothefollowingsettings:
SPIclockrate2000kHz
SPItypeMakeonemicrocontrollerthemasterandtheotherslave
ClockphaseCyclehalf
48
Clockp
polarityLow
Datao
orderMSBfirrst
2. Co
onnectthefo
ollowingpinn
numbersofon
neuCtotheccorrespondin
ngpinsoftheotheruC
(A
Asshown):
Pinnu
umber5(SSb
bar)
Pinnu
umber6(MOSSI)
Pinnu
umber7(MISO)
Pinnu
umber8(SCK))
3. Makesureth
M
hatthegroundconnectiionsofboththemicroco
ontrollersarresamefor
propercomm
munication.
4. Writeaprogr
W
ramtosendcharactersffromthemaaster.
5. Receivethem
montheslavveanddisplaaythereceivveddataonaa16x2LCD.
6. Co
onsidermodu
ule1A/1BforrmcuSPIconnections,mo
odule5forLCDconnection
ns.
7. Nowmakeano
othercodeto
osendADCvaaluesfromuC
C1touC2anddisplayingitonLCD.
CircuitOverview
w
Atmega1
Through
SPI
Atmegaa2
LCD
Experiment9:UsingExternalInterrupts
ProblemStatement
1.
2.
3.
4.
5.
InitializeINT0inFallingEdgemode.
WriteanLEDblinkingprogramintheInterruptServiceRoutine.
PutapullupresistanceandaswitchconnectingtoGndtoprovideinterrupt.
PresstheswitchtoblinktheLED.
Considermodule1Aformcuinterruptpinconnections,module6forLEDarrayconnections
andmodule7forswitchpad.
CircuitOverview
Atmega
LED
Interrupt
Switch
50
EX
XPERIMEN
NTSINRO
OBOTICS/
/AUTOMA
ATION
Experiment1:A
AnalogIRSensor
PartA:Interfacin
ngAnalogIRSensorrwithmicrocontrolllerandtodisplay
variatio
oninoutp
putonLCD
D.
P
ProblemSt
tatement
1. Makethecircuitassho
owninthefigure.
otransistorD
D1andIRLED
Dmustbead
djacenttoeacchother(buttnot
2. Thephoto
touching)andperpend
diculartotheebreadboard
d.
kingtheconn
nections,meaasurethevoltageVOutputb
byamultimetter.
3. Aftermak
1andIRLED
Dandnotethe
4. Nowbringgaplanerefllectingsurfacce(whitepaper)overD1
gradualch
hangeinthevoltage.
ndnotethechangeinran
ngeofsensorr.
5. Varytherresistanceusingvariacan
bleADCofAttmega16and
dcheckUse8bits.
6. Nowenab
f theinputpin
nsforADC(ee.g.,PINA.0)
7. Bringtheoutputoftheeanalogsenssoratoneof
LCD.
andwriteacodetoreaaditsdigitalvalueanddiisplayitonL
8.. Considerm
module4AforAnalogSenssorModuleco
onnections.
CircuitOverview
w
IRAnaalogSensor
Atmega16
LC
CD
PartB:AnalogIRSensorusedasacolorsensor.
ProblemStatement
1.Usethecircuitconnectionsfromthepreviouspartwithoutanychanges.
2.NowchangetheprogramcodeofthemcutoreadADCvaluesfordifferentcolorsviztake
threefourcolorsforinstancelikeRED,GREEN,BLACK,BLUE.
3.TakeapenandpaperandnotedowntherangeofvariationsinADCvalueswhenthe
sensorisexposedtothesecolorsonebyone.
4.NowaltertheprogramcodetochecktherangeofADCvaluesanddisplaycorresponding
colornameonLCD.
5.Findouthowmanycolorsthemcucandifferentiate.
PartC:AnalogIRSensorusedfordistancemeasuring.
ProblemStatement
1.Usethecircuitconnectionsfromthepreviouspartwithoutanychanges.
2.NowchangetheprogramcodeofthemcutoreadADCvaluesfordistancesoftheorderof
centimeters
3.TakeapenandpaperandnotedowntherangeofvariationsinADCvaluescmbycm.
4.NowaltertheprogramcodetochecktherangeofADCvaluesanddisplaythedistanceon
LCD.
5.FindouttheminimumdistancemcucanresolveusingIRsonsor.
52
Experiment2:D
DigitalIR
R(TSOP)ssensor
PartA:IntterfacingD
P
DigitalTSO
OPIRSenssorwithm
microcontrrollerand
to
odisplayv
variationi
inoutputo
onLCD/L
LED.
P
ProblemSt
tatement
1. Makethecircuitassho
owninthefigure.
ouching)and
d
2. TheTSOPsensorandIIRLEDmusttbeadjacentttoeachotheer(butnotto
breadboard.
perpendicculartotheb
0ofAtmega16withfollo
owing
3. Togeneraateapulseoff38kHz,initializeTimer0
parameterrs:
ClockSource:SysttemClock
ClockValue:1000.000kHz
Mode::CTCtop=OCR0
Outpu
ut:ToggleonCompareMaatch
SetCo
ompareValueeascalculateedforapulseeof38kHz(inhexadecim
mals).
heoutputpin
nofTimer0withthepossitiveterminalofIRLEDsoastogivee
4. Connectth
itapulseo
of38kHz.
V(whennoIRfallsonit)
5. CheckthatthedefaultoutputvoltaageofTSOPssensoris+5V
nbringingap
planereflectiingsurface(w
whitepaper))overthesen
nsorandthee
and0Von
IRLED.
necttheoutputpinofTSO
OPsensortoanI/OpinofAtmega16(e.g.,PIND.0
0)
6. Nowconn
andconneectthepositiiveterminalofanLEDtoanotherI/OpinoftheuC
C(e.g.,
PIND.1).C
ConnectnegaativeterminaaloftheLEDtogndthrou
ugha220ohm
mresistance.
OPsensoran
ndglowstheLEDwhen
7. NowwriteeacodethatttakesinputfromtheTSO
thesensorrreceivesIR
R.
ndnotethechangeinran
ngeofsensorr.
8. Varytherresistanceusingvariacan
module4BforrDigitalSensorModuleco
onnections.
9.. Considerm
CircuitOverview
w
TSO
OPSensor
Attmega16
LED
PartB:DigitalTSOPIRSensorusedascontrastvariationdetection
sensor.
ProblemStatement
1.Usethesamecircuitconnections.
2.Writeaprogramcodefordetectingcontrastvariations,viz.blackandwhite.
3.Contrastvariationcomeshandyindesigninglinefollowingrobots.
PartC:DigitalTSOPIRSensorusedasobjectdetectingsensor.
ProblemStatement
1.Usethesamecircuitconnections.
2.Writeaprogramcodefordetectingobstaclesinfrontofdigitalsensor.
3.Obstacledetectioncomeshandyinobstacledetectionrobots.
54
Experiment3:M
MotorCon
ntrolusin
ngdriverL
L293
Problem
mStateme
ent
onnectanytw
woI/Opinso
ofAtmega16((pinno.39&40)withtheinputpinsofmotordriverr
1. Co
L2
293Di.e.,Direection1Aan
ndDirection2
2A.
2. Co
onnecttheen
nablepin(PW
WMA)andVC
CC1(pinno.1
16)withconsttant5Vandggroundas
sh
hown.
3. Co
onnecttheoutputpinsofL293Dwithttheterminalsofthemotorr.
4. Give12VasVCC2toL293D
D.
5. Writeacodet
W
osoastomaakepin39ofuChighandp
pin40aslowandnotetheedirectionof
ro
otationofthe
emotor.
6. Nowinterchan
ngetheoutpu
utsthesepinssofuCandno
otethechanggeindirection
nofrotation.
7. Nowmakebotththepinsasshigh(orlow)andobserveethelockingeffectinthemotor.
8. Co
onsidermodu
ule1Aformccuconnection
ns,module9fforMotorDriiverModulecconnections.
CircuitOverview
w
A
Atmega16
L2
293D
Experiment4:S
Speedcon
ntrolofDCMotor
DCM
Motor
Problem
mStateme
ent
1.. InitializeTimer0ofAtm
mega16withfollowingparameters:
ClockSSource:SysteemClock
ClockV
Value:1000.0
000kHz
Mode::FastPWMto
op=FFh
Output:NonInverttedPWM
SetCo
ompareValueto80(decim
mal128=hex8
80)
2. NowConn
necttheTimer0outputpin
n,i.e.,PINB.3(OCR0)toth
heenablepinofL293D,
markedassPWMA.
3. Allotherconnectionsaresameasin
nExp.14.
4. Notethereductioninspeedofmoto
orascompareedtothatinExp.14.
emotoratfullspeedagain
n,changeOCR
R0valueto25
55.
5. Torunthe
6.. Considerm
module9forMotordriverconnections..
CircuitOverview
w
A
Atmega16
Experiment4:A
Automation
L2
293D
DCM
Motor
PartA:ControllingMotorthroughsensors.
ProblemStatement
1.InterfaceDigitalSensorandMotordrivermodulewithmcu.
2.Writeaprogramcodeforthefollowing:
Motor1changesdirectionwhenobstaclecomesinfrontofsensor.
Motor2changesdirectionwhenobstaclecomesinfrontofsensor.
Trytointerfacetwosensorsandfourmotorstogether.Easy..isntit?
CircuitOverview
TSOP
ATMEGA
MOTOR
PartB:SwitchingRelay/Transistorthroughsensors.
ProblemStatement
1.InterfaceDigitalSensorandTransistormodulewiththemcu.
2.Writeaprogramcodeforthefollowing:
Relaysswitchwhenobstaclecomesinfrontofsensor.
CircuitOverview
TSOP
ATMEGA
RELAY
TRANS.SWITCH
LINEFOLLOWERROBOT
Task:
Todesignanautonomousrobottofollowaline.
57
Therecanbetwocases:
A:Brightstripoverdarkbackground(WhiteoverBlack)
B:Darkstripoverbrightbackground(BlackoverWhite)
Howtodifferentiatewhiteandblack?
DigitalIRSensor(TSOP)usedforcontrastdetectionasdiscussed.
Howtofollowaline?
Wehavesensorstodifferentiatebetweenwhiteandblacksurfaces.Hencewecanusethemina
patterntodetectlineandmoverobotaccordingly.
Arrangementof3sensors:
LEFTCENTRERIGHT
EachpurplecirclerepresentsaTxRxpair.
Sensoroverwhitesurface:outputlow(logiclevel0)
Sensoroverblacksurface:outputhigh(logiclevel1)
Design:
SENSOR
MICROCONTROLLER
MOTOR
MOTORDRIVER
58
Howtocontrolrobot:
a
PositionofLine
Sensor(on)
Movement
vv
ExtremeLeft
Left
Turnsharpleft
Left
CentreandRight
Turnleft
Centre
Centre
Moveforward
Right
CentreandRight
Turnright
ExtremeRight
Right
Turnsharpright
SimplifyingLineFollowerRobot:
Usetwosensorsinstead,oneforleftandotherforright.
LEFT
RIGHT
Howtocontrolrobot:
PositionoflineSensor(on)Movement
LeftLeftTurnright
CentreNoneMoveForward
RightRightTurnleft
59