10. e&r basic
TRANSCRIPT
-
7/31/2019 10. E&R Basic
1/186
HEWLETT-PACKARD EDUCATION SERVICES
EmbeddedSystems&Robotics
http://www.hpesindia.com
-
7/31/2019 10. E&R Basic
2/186
1|P a g e
Contents
Chapter1Basics............................................................................................... 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
Chapter2SomeIntegratedCircuitsandImplementation............................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
Chapter3IntroductiontoEmbeddedSystems.............................................18
3.1 Applications...................................................................................................................... 19
3.2 EmbeddedSystemTypes.................................................................................................. 19
Chapter4IntroductiontoMicrocontrollers..................................................20
4.1 WhatisMicrocontroller?.................................................................................................. 20
4.2 BasicArchitecturesofMicrocontrollers ........................................................................... 22
4.3 DigitalIntegratedCircuits(ICs)......................................................................................... 25
4.4 ProcessorType&MemoryStructures.............................................................................. 27
-
7/31/2019 10. E&R Basic
3/186
2|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
Chapter5CodeVisionAVR(CVAVR).............................................................38
5.1
CHIP:
..................................................................................................................................
40
5.2 PORT:................................................................................................................................ 40
Chapter6IntroductiontoAtmega16Microcontroller.................................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
Chapter7I/OPorts:....................................................................................... 47
7.1 DDRX(DataDirectionRegister)........................................................................................ 47
7.2 PORTX(PORTXDataRegister)........................................................................................... 48
7.3 PINX(DataReadRegister)................................................................................................ 48
7.4 ASMALLNOTEABOUTDELAY....................................................................................... 49
Chapter8LCDInterfacing.............................................................................. 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
Chapter9ADC:AnalogtoDigitalConverter.................................................56
9.1 Theoryofoperation.......................................................................................................... 57
9.2 SettingupMicrocontroller................................................................................................ 57
9.3 FunctionforgettingADC.................................................................................................. 58
Chapter10 Timers..................................................................................... 59
10.1 WhatisaTimer?........................................................................................................... 59
10.2 HowtoUseTimer......................................................................................................... 59
-
7/31/2019 10. E&R Basic
4/186
3|P a g e
10.3 Prescalar....................................................................................................................... 59
10.4 TimerMode.................................................................................................................. 60
10.5 NormalMode................................................................................................................ 60
10.6 CTCMode......................................................................................................................... 60
10.7 PulseWidthModulation(PWM)Mode........................................................................... 61
(A) PWM:PulseWidthModulation........................................................................................... 61
(B) PWMSignalGenerationUsingAvrTimers.......................................................................... 62
(C) PhaseCorrectPWMMode.................................................................................................. 64
10.8 SETTINGUPTIMERSINCODEVISIONAVR....................................................................... 66
10.9 FastPWMMode........................................................................................................... 70
10.10 CTCMode...................................................................................................................... 71
Chapter11 Communication...................................................................... 72
11.1 Data Transfer................................................................................................................ 72
11.2 Classification................................................................................................................. 72
11.3 BaudRate...................................................................................................................... 73
11.4 DifferentCommunicationTechniques.......................................................................... 74
Chapter12 SPI:SerialPeripheralInterface..............................................74
12.1 TheoryofOperation..................................................................................................... 75
12.2 SettingupSPIinMicrocontroller.................................................................................. 80
12.2.1 MasterMicrocontroller ........................................................................................ 80
12.2.2 SlaveMicrocontroller ............................................................................................ 80
12.3 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 Interrupt................................................................................. 91
-
7/31/2019 10. E&R Basic
5/186
4|P a g e
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 H Bridge:.................................................................................................................... 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 DigitalIRSensor TSOPSensor................................................................................... 117
Chapter19 ProjectWork........................................................................ 118
19.1 LinefollowingRobot................................................................................................... 118
Chapter20 DefinitionsofEmbeddedsystem............................................119
Chapter21 GLOSSARY................................................................................ 121
Chapter22 References.............................................................................. 126
-
7/31/2019 10. E&R Basic
6/186
5|P a g e
SectionADigitalElectronics
-
7/31/2019 10. E&R Basic
7/186
6|P a g e
Chapter1 Basics1.1 WhatisaDigitalsystem?
Inmostgeneralterms,thissystemsbehaviorissufficientlyexplainedbyusingonlytwoofits
statescanbeVoltage(morethanxvoltsorless?),distancecovered(morethan2.5kmorless?],true
falseorweightofanelephant(willmyweighingmachinewithstandit?))
Notethatalthoughineverycase,thealltheintermediatestatesAREPOSSIBLEANDDOEXIST,
ourpointofinterestaresuchthatwedontrequiretheirexplicitdescription.Inelectronicsystems
wemostlydealwithVoltagelevelsasdigitalentities.
1.2 AssigningStatesThereisnospecificfixeddefinitionoflogiclevelsinelectronics.Mostcommonlyusedlevel
designationistheoneusedinCMOSandTTL(transistortransistorlogic)families:
Logichigh>designatedas1
Logiclow>designatedas0
Where high and low are actually higher and lower with respect to a reference voltagelevel (ideally taken as 2.5V)
1.3 NumberSystemsindigitalelectronics1. Binary: Only 0 and 1.
2. Hexadecimal: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
1.4 TypesofDigitalCircuits
CombinatorialCircuits:Inthesecircuits,thepaststatesareimmaterial
andtheoutputdependsonlyuponthepresentstate.Examplelogicgates
Sequentialcircuits:Inthesecircuits,thenextstateiscompletely
determinedbythepaststates.Hencethesefollowapredictablestructure
andessentiallyrequireatimingdevice.Ex.counters,flipflops.
GOOGLY:Whyassign0and1andnotaandb,xandy,catanddog?
ANS:Computationalease!
-
7/31/2019 10. E&R Basic
8/186
7|P a g e
1.5 Clock:BuildingblockofasequentialcircuitAclockissimplyalternatehighandlowstatesofvoltagewithtimei.e.essentiallyasquarewave.
Importanttermsrelatedtoclockareitsdutycycleanditsfrequency:
Dutycycle:ItistheratioofThandTh+Tl
1.6Logic
Gates:
Building block of a combinatorial circuitry
TheseareessentiallycombinatorialcircuitsusedtoimplementlogicalBooleanoperationslikeAND,
NAND,OR,XORandNOT.NOTandNANDarecalleduniversalgatesasanyothergatecanbeformed
usingeitherofthem!
Figure1:TableofLogicGates
-
7/31/2019 10. E&R Basic
9/186
8|P a g e
1.7 PracticalCircuitingElements
1.7.1 Resistor:Acolorschemeisfollowedtogivethespecificationsofaresistor.Thetableforcolorcodeisshown
below:
The1st
twobandsspecifythe2digitsoftheresistorvaluewhereasthe3rdbandspecifiesthemultiplierintermsofthepowertowhich10is
raisedandmultipliedtothe2digits.
Thetolerancetellsthepossible%variationoftheresistorvalueabout
thevalueindicatedbybands.
1.7.2 Capacitor:The2typesofcapacitorswefrequentlyuseincircuitsareceramicandelectrolyticcapacitors.While
ceramiccapacitorsdonothaveafixedpolarity;electrolyticcapacitorsshouldbeconnectedintheir
specifiedpolaritiesonlyelsetheymightblowoff!Thispolarityisusuallyprovidedonthesideofthe
capacitorscorrespondingleg.
Figure4:Electrolyticcapwithvepolaritylegseen Figure3:Ceramiccapwithvalue15x104pF
Figure2:TableofResistance
-
7/31/2019 10. E&R Basic
10/186
9|P a g e
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.
Figure5:Topviewshowingtheconnectingholes.Bottomviewshowsthecontactmetalstrips
Figure6:IC
-
7/31/2019 10. E&R Basic
11/186
10|P a g e
1.7.5 LEDLED(LightEmittingDiode)isfrequentlyusedtodisplaytheoutputsatvariousstagesofthecircuit.It
isessentiallyaDiodewith theenergyreleased in the formofphotonsdue toelectron transitions
fallinginthevisibleregion.Hencenormaldiodepropertiesapplytoit.
It glows only in fwd bias mode i.e. with pjunction connected to +ve voltage and njunction 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 significantamountof powerof theoutputs of the ICs (CMOS
based).Hence it isadvisabletoonlyusethemforcheckingthevoltage level(highor low)andthen
removethem.
Figure7:LEDs
-
7/31/2019 10. E&R Basic
12/186
11|P a g e
Chapter2 SomeIntegratedCircuitsandImplementation2.1 555555isanICusedtogenerateaclock.The
twoattributesofaclockare
Frequency Dutycycle.
BothofthesecanbechangedusingthisIC,
howeverthedutycycleisalways
-
7/31/2019 10. E&R Basic
13/186
12|P a g e
2.1.2 AstablemodeInthismode;theoutputisstableneitherinhighstatenorinlowstate.Henceitoscillatesfrom
onestatetoanothergivingusasquarewaveorclock.WecansettheclockfrequencyandDutycycle
Dbytheformulae:
F=.
D=
Figure10:555inastablemode
NOTE:CapacitorC2isjusttofilterthenoiseanditsvaluecanbesuitablychosentobe0.01F.Itcan
alsobeneglected.
-
7/31/2019 10. E&R Basic
14/186
13|P a g e
2.2 4029counterWiththeclockmade,wearereadytocountthenumberofpulsespassedintothecircuit.Notethat
anykindofcountingrequiresamemory(yougottoknowthatyouhavejustcounted3togoto
4!). Hence4029canalsobeusedasamemoryelementthatremembersitsimmediateprevious
state.
Figure11:4029pinconfiguration
2.2.1 PinDescriptionPINNo. Name Pinfunction Connectionreqd.
1 Parallelload Ifgivenhigh;loadsthevalueof
Parallelbitintotheo/pbits
Gnd
2 OutputBit 3 Mostsignificantbitofo/p Topin6of7447
3 Parallelinputbit3 Mostsignificantbitofparalleli/p Input
4 Parallelinputbit0 Leastsignificantbitofparalleli/p Input
5 Clockenablebar Lowonthispinenablescountingas
pertheclockreceived
Gnd
6 OutputBit 0 Leastsignificantbitofparallelo/p Topin7of7447
7 TCbar Outputbitthatgivesalowwhenthe
countiscomplete.Canbeusedtosignal
theendofcounting.
Noneifyoudont
wanttouseit
8 Gnd Neededforpowering Gnd
9 Binary/Hexbar Tochooseb/wbinaryand
hexadecimalmodes
lowforcount015
highforcount09
10 Up/Downbarcount Tochooseb/wupcountingand
downcountingmodes
Lowfordowncount
Highforupcount
11 Outputbit1 2ndbitofo/p Topin1of7447
12 Parallelinputbit1 2nd
bitofi/p Input
13 Parallelinputbit2 3rdbitofi/p Input
14 Outputbit2 3rdbitofo/p Topin2of7447
15 Clockpulse Clockpulseisgivenhere Clockfrom555
16 Vdd Neededforpowering +5V
-
7/31/2019 10. E&R Basic
15/186
14|P a g e
2.3 7447:BCD to 7 segment display decoderFor displaying the number in the counter output on a seven segment display (i.e. 7 LEDsmaking up a figure of 8 as in a general calculator. See fig. )we need to decode the 4 bits andmatch them to the 7 pins for lighting the LEDs corresponding to the number. This work isdone by 7447.
Figure12:7447pinconfiguration
2.3.1 PinDescription
PIN
no.
Name Function Connectionreqd.
1 i/pB 2ndbit(O1)of4029so/p ToO1of4029
2 i/pC 3rdbit(O2)of4029so/p ToO2of4029
3 LampTest
bar
UsedtocheckthatallLEDsof7seg
areworking.
Highfornormalfn
Lowtoglowall
LEDs
4 BI/RBI Kepthightoallownormalfunction Kepthigh5 RBI Blanks0frombeingdisplayed Kepthigh
6 i/pD Mostsignificantbit(O3)of4029s
o/p
ToO2of4029
7 i/pA 3rdbit(O2)of4029so/p ToO2of4029
8 Gnd Forpower Connectedtognd
915 agasperthe
fig
Theo/ppinsto7segmentdisplay To7segdisplay
16 Vcc Forpower Connectedto+5V
NOTE:
TheCOMpinsaretobeconnectedtoVccvia220ohmresistor.Whyresistorisrequired??
Thedotpinisjustfordisplayofdecimalpointandessentiallyonlymakestheupperand
lowersidesdistinguishablefromeachotherforasingledisplay.withouttheasymmetry
producedbydothowwillwebeabletoseewhichsideisupperandwhichislower?
2.4 LDR(LightDependentResistor)
-
7/31/2019 10. E&R Basic
16/186
15|P a g e
LightDependentResistor(LDR)orphotoresistorisadevicethatactslikearesistanceandits
resistancevarieswiththeintensityoflightincidentonit.Inthisdevice,ifphotonsofsufficient
energyfallonit,theresistancedropsdrasticallyastheelectronsinthesemiconductorareableto
jumpfromthevalencebandtotheconductionbandandareavailableforconduction.TheLDRsused
aremostlyresponsivetovisiblelight.Theresistancemightdropfromashighas1M inthedarkto1
k inbrightlight.
2.5 OperationalAmplifier(Opamp)Opampisaveryimportantdeviceusedineverydayelectronics.Itisessentiallyadifferential
amplifierwithaveryhighgainoftheorderof105!BydifferentialamplifierImeanthatitamplifies
thedifferenceof2signalsandgivestheoutput.
Opampequation:
Vout=A(V+ V) whereAisthegainoftheorder105.
Ironically,thishighgaininopenloopmakesitimpossibletouseitasageneralpurpose
differentialamplifierdirectly.
Figure13:LDRs.Thecoiledportionisresponsivetolight
GOOGLY: If(V+V)=0.005V;Vss=12Vwhatwillbetheoutput??
-
7/31/2019 10. E&R Basic
17/186
16|P a g e
2.5.1 OpampasacomparatorSimplestuseofOpampisasacomparator.Itcanbeusedtoconvertananalogsignaltoadigital
signaldefinedbyafixedthreshold.SetV asthethresholdvoltagesay2.5Vandapplytheanalog
signaltobedigitizedatV+.Whatwillbetheoutput?Wellifyouhaveworkedoutthegoogly;this
shouldbeapieceofcake!
2.6 7805VoltageRegulator7805voltageregulatorisusedtoget+5Voutputoutofahighervoltagesupply(7.5V20V).Weuse
adapterssupplytogenerate+5Vhere.Connectthegndand+12Vofadaptertothepinsasshown
andget+5Vdirectlyasanoutputoutofthe3rdpin.Currentupto0.5Acanbeobtainedfromthis
regulatorwithoutanysignificantfallinvoltagelevel.
NOTE:Use2capacitorsofvaluesay0.1Ftofilterthenoiseintheinputandoutputofregulators
supplyasshown.
-
7/31/2019 10. E&R Basic
18/186
17|P a g e
SectionBEmbeddedSystems
-
7/31/2019 10. E&R Basic
19/186
18|P a g e
Cha
Embe
task/o
syste
music,
tellst
single
(technopera
need
Basic
besh
y
y
y
ter3 Inded system
peration. U
which is u
games, surf
atwholesys
chip cont
ically,
firmions which
fhumancon
lowdiagram
wnas:
Variouswa
An
on
or
Anpu
AnEmbed
fewdedica
or
AnEmbed
in
capabiliapplication
troducti
is a scaled
nlike a gen
ed for a var
ing internet
temisembe
ins both
are).
It
isminimize (o
trol.
forembedd
yswecanDe
Embedded
orafewde
Embedded
poseandca
Asfeatuor
edsystem i
edfunctions
edsystemis
ty
or
progrdevice.
ntoEm
down comp
eral purpos
iety of tasks
etc. The ter
ddedintoan
ardware a
designed
even comp
edcompute
fine
system
is
a
dicatedfunct
ystem isaS
alsocontai
resgetona
saspecialp
,oftenwith
somecombi
ammable,
t
eddedS
uter system
e computer
, like playin
embedded
appliance.A
d software
to
performletely avoid)
systemscan
pecial
purpions,often
oftwarepro
somemech
deddailyde
urposecomp
ealtimeco
inationofco
at
is
specif
stems
which is d
se
computeithrealtime
ramonaH/
anicalmovin
finitionitself
utersystem
puting.
puterhard
ically
design
signed to p
r
system
descomputingc
Wchipdesi
gparts.
isevolving.
designedto
areandsoft
ed
for
a
p
erform a sp
igned
to
peonstraints.
nedforasp
performone
ware,either
articular
kin
ecific
form
ecific
ora
fixed
d
of
-
7/31/2019 10. E&R Basic
20/186
19|P a g e
Someimportantthingstonoteaboutembeddedsystems:
1. Onceanembeddedhardware isprogrammed foracertain task, it isused forever for the
sametask.Changingthefirmwareafterwardsisnotpossible.
2. Such systemsare limited in computational resources likememory,CPUprocessing speed,
I/Ofacilitiesbutarestillcapableofperformingthetaskgiventothemveryefficiently.
3. Embeddedsystemscanalsobehavingareducedfunctionalityversionofoperatingsystem
calledRTOS(RealTimeOperatingSystem)forhighlyspecializedapplications.
4. Is a system built to perform its duty, completely or partially independent of humanintervention?
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 ApplicationsAn 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.),Keyboards4. 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. Automobiles6. Calculators, Electronic wending machines, Electronic weighing scales, Phones(digital
with LCD and phonebook)
7. Cell phones8. 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
-
7/31/2019 10. E&R Basic
21/186
20|P a g e
y NonRealtimeEmbeddedsystem isone inwhichthere isnodeadline,even if fast
responseorhighperformanceisdesiredorpreferred.
y RealtimeEmbeddedSystems:Wheredeadlineistobemet.
Softrealtimeembeddedsystems.
Hardrealtimeembeddedsystems.
y FollowingaresomeapplicationsofEmbeddedSys.butnotrealtime.
SecuritySystems. MobileandPDA.
AlarmSystem.
Automobilesystem.
DigitalCamera.
y ExamplesofRealtimeEmbeddedsystems.
SensorsysteminNuclearplants.
Missiledefencesystem.
Flightcontrolsystem.
AnticollisionsysteminAutomobiles.
Chapter4 IntroductiontoMicrocontrollers4.1 WhatisMicrocontroller?
-
7/31/2019 10. E&R Basic
22/186
21|P a g e
WhatisaMicrocontroller?
A Microcontroller is a programmable digital processor with necessary peripherals. Both
microcontrollers andmicroprocessorsarecomplexsequentialdigitalcircuitsmeanttocarryout
jobaccording to theprogram/ instructions.Sometimesanalog input/output interfacemakesa
part of microcontroller circuit of mixed mode(both analog and digital nature).
AmicrocontrollercanbecomparedtoaSwissknifewithmultiplefunctions incorporated in the
sameIC.
Fig.4.1 AMicrocontrollercomparedwithaSwissknife
MicrocontrollersVsMicroprocessors
1. A microprocessor requires an external memory for program/data storage. Instruction
executionrequiresmovementofdatafromtheexternalmemorytothemicroprocessoror
viceversa.Usually,microprocessorshavegoodcomputingpowerandtheyhavehigherclock
speedtofacilitatefastercomputation.
2. A microcontroller has required onchip memory with associated peripherals. A
microcontrollercanbethoughtofamicroprocessorwithinbuiltperipherals.
3. A microcontroller does not require much additional interfacing ICs for operation and it
functionsasastandalonesystem.Theoperationofamicrocontroller ismultipurpose,just
likeaSwissknife.
4. Microcontrollers are also called embedded controllers. A microcontroller clock speed is
limitedonly toa few tensofMHzMicrocontrollersarenumerousandmanyof themare
applicationspecific.
Development/Classificationofmicrocontrollers(Invisible)
Microcontrollers havegone througha silentevolution (invisible).Theevolutioncanbe rightly
termedassilentastheimpactorapplicationofamicrocontrollerisnotwellknowntoacommon
user,althoughmicrocontrollertechnologyhasundergonesignificantchangesinceearly1970's.
Developmentofsomepopularmicrocontrollersisgivenasfollows.
-
7/31/2019 10. E&R Basic
23/186
22|P a g e
Intel4004 4bit(2300PMOStrans,108kHz)197
1
Intel8048 8bit197
6
Intel8031 8bit(ROMless) .
Intel8051 8bit(MaskROM)198
0
Microchip
PIC16C64
8
bit
198
5
Motorola68HC11 8bit(onchipADC) .
Intel80C196 16bit198
2
AtmelAT89C51 8bit(Flashmemory) .
MicrochipPIC16F877 8bit(Flashmemory+ADC) .
Developmentofmicroprocessors(Visible)
Microprocessors have undergone significant evolution over the past four decades. This
developmentisclearlyperceptibletoacommonuser,especially,intermsofphenomenalgrowth
incapabilitiesofpersonalcomputers.Developmentofsomeofthemicroprocessorscanbegiven
asfollows.
Intel4004 4bit(2300PMOStransistors) 1971
Intel8080
8085
8bit(NMOS)
8bit1974
Intel8088
8086
16bit
16bit1978
Intel80186
80286
16bit
16bit1982
Intel80386 32bit(275000transistors) 1985
Intel80486 SX
DX
32bit
32bit(builtinfloatingpointunit)1989
Intel80586 I
MMX
CeleronII
III
IV
64bit
1993
1997
1999
2000
Z80(Zilog) 8bit 1976
MotorolaPowerPC
601
602
603
32bit 1993
1995
4.2 BasicArchitecturesofMicrocontrollersWe use more number of microcontrollers compared to microprocessors. Microprocessors are
primarilyusedforcomputationalpurpose,whereasmicrocontrollers findwideapplicationindevices
needingrealtimeprocessing/control.
-
7/31/2019 10. E&R Basic
24/186
23|P a g e
Applic
machi
cellph
MBroad
F
In
HaAt
ext
NM
whi
ationofmicr
nes,TVs,air
ones,electri
icrocontroll
Classification
Embedded
16to32M
DigitalSign
aturesofM
BuiltinMo
BuiltinPro
Interrupts
AnalogI/O
SerialI/O
FacilitytoI
Timers
ternalStruc
rvardvs.Pri
times, a mic
ramemory i
OS technolo
ich leads to
ocontrollers
onditioners,
aldrives,an
erChips
ofdifferent
(SelfContai
icrocontrolle
alProcessors
odernMicr
nitorProgra
gramMemo
nterfaceExte
tureofaM
F
ncetonArc
rocontroller
terface isr
gies. Most
reduction i
isnumerous.
microcontro
drob+oticsa
microcontrol
ed)8 bitM
rs
ocontroller
y
rnalMemor
icrocontroll
ig.4.2 Intern
itecture
can have ex
quired).Earl
odern micr
size and
Startingfro
llersareuse
ndinspacea
llerchipscou
icrocontroll
er
lStructureof
ernal memo
ymicrocontr
controllers
ower loss.
domestica
inautomob
pplications.
ldbeasfollo
r
aMicrocontr
ry also (if th
ollerswere
are manufac
urrent dra
pplicationss
iles,process
ws:
oller
ere is no int
anufacture
tured with
n by the I
uchasinwa
controlindus
ernal memo
dusingbipol
MOS techn
is also red
shing
tries,
ry or
aror
logy,
uced
-
7/31/2019 10. E&R Basic
25/186
24|P a g e
con
typ
Ma
to
she
int
the
Ha
ansim
par
Pri
Exam
asfoll
Cycle
Cycle
Ha
siderably fr
icallyataclo
nyyearsago
come up wit
llfordefens
rface.It isa
projectinPr
vardsuggest
the
other
plicity and e
allelismofin
ncetonArc
le:Aninstru
ws:
ReadInstr
ReadData
rvardArchit
m 10mA to
ckspeedof2
,inthelate
h a comput
application
lsoknowna
incetonUniv
edacomput
or
program
ase of imple
structionexe
itecture (S
tion"Reada
uction
outofRAM
ecture (Se
a few micro
0MHz).
940's,theU
r architectu
s.Princeton
VonNeuma
ersityJohnV
erwithtwo
/
instructiomentation,
cution.
inglememo
Fig.4.3
databytefr
andputinto
parateProg
Amperes in
SGovernme
e to be use
suggestedco
nnarchitect
onNeumann
ifferentme
ns.
Althougharvard arch
ryinterface
PrincetonA
ommemory
Accumulator
ramandDa
sleep mode
taskedHar
in computi
mputerarch
reafterthe
(1903 195
oryinterfac
Princeton
a
itecture bec
)
chitecture
ndstoreiti
taMemory
(for a micro
ardandPrin
ng distances
itecturewith
nameofth
BorninBud
es,onefort
rchitecture
me popular
theaccumu
interfaces)
ontroller ru
cetonuniver
of Naval art
asingleme
chiefscient
apest,Hunga
edata/vari
as
acceptelater, due t
lator"isexe
ning
sitys
illery
mory
istof
ry).
ables
d
for
the
uted
-
7/31/2019 10. E&R Basic
26/186
25|P a g e
Thesa
Cycle
Compl
Read
CycleExecu
Read
Hence
modif
cycles.
comp
4.3Youm
There
andm
Nowl
forou
meinstructi
eteprevious
the"Move
te"MoveDa
nextinstruct
each instru
theconten
Thus, due t
redtoPrinc
DigitalIn
ustbeknowi
7404:HexI
7408:Qua
7410:Tripl
7432:Qua
7457:60:1
areAND,XO
uchmore.Ju
tstake
Qua
put.Thetru
n(asshown
instruction
atatoAccu
atoAccumu
ion
tion is effe
of thepro
o parallelis
tonArchitec
egrated
ngaboutDig
nverter
2inputAN
3inputNA
2inputOR
Frequencydi
,NAND,NO
stcheckout
d2input
AN
htableorth
Fig.4.
underPrince
ulator"instr
lator"instru
tively execu
ramcounter
, Harvard a
ture.
ircuits(I
italIntegrate
gate
DGate
ate
vider
R,ORlogicg
7400Seriesa
Dgate
IC.
It
efunctionta
Input1
0
0
1
1
HarvardA
tonArchitec
uction
tion
ted in one i
.Forexampl
chitecture e
s)
dCircuits(IC
teICs,Coun
nd4000Seri
has4AND
g
bleofeachg
Input2
0
1
0
1
citecture
ure)would
nstruction c
e,the "jump
xecutes mor
)right?For
ers,Timers,
esofIntegra
tes,each
ha
teisfixed.T
Output
0
0
0
1
eexecuteda
cle, except
" (or call) in
e instruction
xample:
SevenSegm
edCircuits.
ving2pins
f
hisisasfollo
sfollows:
or the ones
structionsta
s in a given
ntDisplayD
rinput
and
ws,
that
kes2
time
ivers
1pin
-
7/31/2019 10. E&R Basic
27/186
26|P a g e
Similarlyall the Integratedcircuitshave their function tablesand inputandoutputpins fixed.You
cannotchangethefunctionandnoinputpinactasoutputandviceversa.Sowheneveryouwantto
designsomecircuityoufirsthavetogettheoutputasafunctionofinputsandthendesignitusing
gatesorwhatevertherequirementis.
Soonceacircuit isbuiltwecannotchange its function!Even ifyouwant tomake somechanges
again youhave to considerall thegatesand components involved.Now if youaredesigningany
circuit which involves change of the function table every now and then you are in trouble ! For
example if IwanttodesignanAutonomousRobotwhichshouldperformvarioustasksand Idont
justwanttofixthetask.SupposeImakeittomoveinapaththenIwanttochangethepath!Howtodothat?
HerecomestheuseofMicrocontrollers! NowifIgiveyouanIntegratedCircuitwith20pinsandtell
you that you can make any pin as output or input also you can change the function table by
programming the ICusingyourcomputer!Thenyour reactionswillbewow!Thatsnice :)Thats
whatthemostbasicfunctionofamicrocontroller is. 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
WewilldiscussaboutAtmelMicrocontrollers commonlyknownasAVRinthissection.
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, CPUaccessesthe instructionfromRAMwhichaccessyourcodefromFlash.Itsets
theconfigurationofpinsandstartperformingaccordingtoyourprogram.
Question:Howtomakethecode?
Answer:YoubasicallywritetheprogramonyourcomputerinanyofthehighlevellanguageslikeC,
C++,andJAVAetc.Thenyoucompilethecodetogeneratethemachinefile.Nowyouwillaskwhat
thismachinefile is.Allthemachinesunderstandonlyone language,0&1that isonandoff.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.
-
7/31/2019 10. E&R Basic
28/186
27|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 ajust collection of 0 &1 ) Serial Port's protocol is called as UART (Universal
AsynchronousReceiver&Transmitter) Itsvoltage levelsare :12voltfor0 logicand+12volt for1logic.
Now the voltage levels of our microcontroller are based on CMOS (Complementary Metal Oxide
Semiconductor)technologywhichhas0voltfor0logicand+5voltfor1logic.
Twodifferentmachineswith2differentwaystodefine0&1andwewanttoexchangeinformation
betweenthem.ConsidermicrocontrollerasFrenchandComputer'sSerialPortasanIndianperson
(obviouslynocommon language inbetween!) If theywant toexchange information theybasically
needamediatorwhoknowsboththelanguage.Hewilllistenonepersonandthentranslatetoother
person.SimilarlyweneedacircuitwhichconvertsCMOS(microcontroller)toUART(serialport)and
viceversa.Thiscircuit iscalledasprogrammer.Using thiscircuitwecanconnectcomputer to the
microcontrollerandfeedthemachinefiletotheflash.
TheAVR(AdvancedVirtualRisc)isaModifiedHarvardarchitecture8bitRISCsinglechip
microcontroller(C)whichwasdevelopedbyAtmelin1996.TheAVRwasoneofthefirst
microcontrollerfamiliestouseonchipflashmemoryforprogramstorage.
4.4 ProcessorType&MemoryStructures
Microcoded
and
hard
coded
processors:
Theimplementationofcomputerarchitecturecanbebroadlyachievedintwoways.Acomputerisa
complexsequentialdigitalcircuitwithbothcombinationalandsequentialcircuitcomponents. Ina
microcodedprocessor,eachinstructionisrealizedbyanumberofstepsthatareimplementedusing
small subroutines.These subroutinesarecalledmicrocodes storedwithin the instructiondecode
unit.Hence,amicrocodedprocessorcanbecalledaprocessorwithinaprocessor.
Microcodedprocessor:
-
7/31/2019 10. E&R Basic
29/186
28|P a g e
Letus
1.2.3.4.5.6.
Eachs
points
Advan
Disad
Eachi
hard
t
takeanexa
Outputad
Configuret
Enablebus
Storethed
Compared
register.
Disabledat
tepofthein
tothemem
tages: 1.
2.antage:
1.
Hardcode
structionis
o
debug.
Ho
Fig.4
ple.Theinst
resstothed
heinternalb
read.
ataintothe
atareadwit
abus.
structionisr
rywhereth
Easeoffab
Easytodeb
rogramexe
processor:
ealizedbyc
ever,
the
pr
.5 Architect
ruction"Mo
atamemory
usfordatam
ccumulator.
hzerooran
ealizedbya
microcode
ication.
ug.
utiontakesl
mbinational
gram
execu
reofaMicro
eAcc,Reg"
emoryvalue
other impo
subroutine(
fortheinstr
ongertime.
and/orsequ
ion
is
faster.
CodedProces
anbeexecu
tobestored
rtantconditi
icrocode).
ctionisloca
ntialdigital
sor
edinthefoll
inaccumula
onandsetb
Asetofbits
ed.
circuits.The
owingsteps.
or.
its intheST
intheinstru
esigniscom
TUS
ction
plex,
-
7/31/2019 10. E&R Basic
30/186
29|P a g e
M
Inme
vol
call
1.
2.
moryType
a
microcontrmoryrespect
atilei.e,the
edReadOnl
MaskRO
factory.Th
for specifi
manufactu
Reprogram
EPROMwe
erased
witMOSFETbu
Intheunp
OFF state.
potentials
is formed
'ON'.Thec
can be re
packagingi
Fig4
oller,
two
tively.Progra
emorycont
Memory(R
: Some mic
isROMiscal
application,
ringreduces
mable prog
reintroduce
h
UV
radiatitwithacont
ogrammeds
To program
chthatach
etween 'So
harge inthe
oved by e
sdoneinac
.6 Architect
pes
of
memmemoryi
entisnotlo
M).Therear
ocontrollers
ledMaskRO
there is n
hecostfor
ram memor
dinlate197
n.
The
conrolandfloat
Fig4.7 S
tate,the 'flo
the cell, th
argeleaksto
rce' and 'Dr
'float'remai
xposing the
ramicenclo
reofaHard
ory
are
foualsoknown
twhenthep
evarioustyp
with ROM a
M.Sincethe
need to re
ulkproducti
(or) Erasa
's.Thesede
truction
ofsemiconduct
tructureofanat'doesnot
'control' ab
thefloatthr
ain' in thesi
nsfora lon
float to UV
urewithagl
CodedProces
nd.
They
aras'controls
owergoeso
esofROM.
re program
microcontro
program th
n.
le PROM (
icesareele
EPROM
m
orasshown
EPROM
haveanych
ove the 'flo
oughSiO2 in
licon substra
time(typica
radiation.
asswindow.
sor
,
programore'and'fir
ff.Nonvolati
ed while th
llerswithM
m. Some ti
PROM):Mic
tricallyprog
mory
cell
isinthefigure.
rgeandthe
t' is raised
ulatinglayer
teand the
llyover30y
or UV eras
emory
andware'.Itis
ilememoryi
ey are still i
skROMare
es, this ty
ocontrollers
rammablebu
somewhat
l
MOSFET is i
o a high en
.Henceach
OSFET bec
ears).Thec
able version
datanon
also
the
used
e of
with
tare
ike
a
nthe
ough
nnel
omes
arge
, the
-
7/31/2019 10. E&R Basic
31/186
-
7/31/2019 10. E&R Basic
32/186
31|P a g e
Thefi
tofro
Proce
parto
on
a
instru
I/ORe
used i
impor
ureofasing
t,soastofo
sorstacksst
RAMarea
able.
Data
i
tion.
gisters:Inad
n input/out
antformicr
Hardwarei
leSRAMcell
rmalatch.
ore/savethe
herethedat
s
stored
by
ditiontothe
ut and cont
controllerp
nterfacereg
Fig4.9Static
Fig4.10SRA
isshownab
datainasi
aissavedin
executing
a
Datamemo
rol operatio
ripheralint
isters(I/OSp
RAM(SRAM)
memorycel
ve.Thiscon
plewaydur
aLastInFirst
'push'
instru
ry,somespe
ns. These re
rfaceandco
ace)
emorycell
lequivalent
istsoftwoC
ingprogram
Out(LIFO)f
ction
and
d
cialpurpose
gisters are c
ntrolapplicat
MOSinverte
execution.P
shionjustlik
ata
is
read
registersare
alled I/O re
ions.
rsconnected
ocessorstac
eastackof
out
using
a
requiredth
isters. Thes
back
kisa
aper
'pop'
tare
are
-
7/31/2019 10. E&R Basic
33/186
32|P a g e
Aswealre
datatransf
/output (I/
(memory
Inamicro
architectur
I/ORegistInPrinceto
anddatam
variableR
mappedI/
The drawb
overwriteI
I/ORegist
Thesearet
1. I/Oreg2. I/Oreg3. I/Oreg
dyknowa
ertothese
O) devicesa
appedI/O)
ontroller,t
eandHarvar
rspaceinPr
narchitectu
emory(RAM
M area.Thi
.Alternativ
F
ack of mem
Oregisters.
rspaceinH
hefollowing
istersinprog
istersinregis
istersinsepa
icrocontroll
evicestakes
re externally
raseparate
opossiblea
darchitectur
incetonarch
ewehaveo
).Oneoptio
architectur
lyaseparat
ig4.11I/ORe
ory mapped
rvardarchit
optionsavail
ramROM.
terspace(D
ratespace.
rhassome
placethrou
interfaced a
I/Oaddresss
rchitectures
e.
itecture
nlyoneme
istomapt
is simple a
I/Oregister
istersinPrin
I/O is that
ecture
ableforI/Or
taMemory
mbeddedp
hI/Oregist
nd aremap
pace(I/Om
can be used
ory interfac
eI/ORegist
nd straight f
spacecanbe
etonArchitec
a program
egisterspac
rea).
ripheralsan
rs.Inamicr
ed either to
ppedI/O).
i.e.,Princet
eforprogra
rasaparto
rward. This
assigned.
ture
hich wron
inHarvard
dI/Odevices
oprocessor,
memory ad
n(VonNeu
memory(
fdatamem
is called me
ly executed
rchitecture.
.The
input
dress
ann)
OM)
ryor
mory
may
-
7/31/2019 10. E&R Basic
34/186
33|P a g e
4.6Atmel
tools
useC
has li
Vista.
Some
AVRG
4.7
Thefirsto
ROM area.
secondopt
Compiler
Microcontro
vailablefort
AVR(Code
itation of c
famouscom
WINAVR(A
CodeVisio
AVRStudio
Cisaveryni
Program
Fig4.12
tionissome
It is alsoco
ionwhere
I/
/IDE(Int
llersarever
hem.Firsto
isionAVR)E
de size. It
ilers/develo
VRGCCfor
AVR(CVAV
(Atmel'sfre
iceopensou
mer
Organization
hatdifficult
mplicated to
registersar
egratedD
famousast
allweneed
valuationve
orks on co
pmenttools
indows)
)
developing
cecompiler
fI/Oregister
toimpleme
have a sepa
eplaced
in
t
evelopm
heyarevery
aneasyIDE
sionisavaila
puters with
upportingW
tool)
usedbymost
inHarvardA
tasthereis
rate I/Ospa
eregister
sp
ntEnviro
easytouse.
fordevelopi
bleforfree
Windows pl
indowsforA
ofthepeopl
rchitecture
nomeansto
ce as shown
aceis
widely
nment)
Therearem
gcode.Isu
downloadfr
atform that
tmelMicroc
le.
writetopro
in (3). Henc
used.
anydevelop
gestbeginn
mthewebsi
is Windows
ntrollersar
gram
e the
ment
rsto
ite.It
XP &
:
-
7/31/2019 10. E&R Basic
35/186
34|P a g e
Programmerbasicallyconsistsoftwoparts:
Software(toopen.hexfileonyourcomputer)
Hardware(toconnectmicrocontroller)
Hardwaredependson thecommunicationportyouareusingon thecomputer (Serial,Parallelor
USB). Isuggestbeginners touseSerialProgrammeras it isveryeasytobuild.Software forthat is
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.
-
7/31/2019 10. E&R Basic
36/186
35|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.Nowweneedsoftwarewhichsupportthishardwareandcancommunicatewithmicrocontrollerusingthiscircuit.Thereare2goodsoftwares
forWindows.Theyare,
PonyProg
AtProg
BothofthemsupportSerialaswellasParallelport,butIhavealwayspreferredserialportbecauseit
hasonly9pins,henceasmallerconnectorisrequired.
-
7/31/2019 10. E&R Basic
37/186
36|P a g e
Nowletusdiscussaboutthem.
AtProg
I consider it as simplest programmer ever. The circuit we discussed is actually basedon 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.
NowjustopenthedevicefilefromFile>OpenandclickonWrite. Itwillwriteandverifythe
program.Done!Sosimpleisntit?:)
PonyProg
OneofthemostcommonlyusedprogrammersonWindows.Downloaditfromthewebsiteand
installit.Nowletssetitupforourhardware.
FirstselectAVRmicroandAVRAuto(youcanalsospecifydevicename,Atmega16)inthechip
options(lasttwodropdowntabs)
-
7/31/2019 10. E&R Basic
38/186
37|P a g e
GototheSetup>InterfaceSetup.Thendothesettingsasshown inthepicturebelow.Then
connect thecircuitto themicrocontroller,turnon thepowersupply.NowclickonProbe.You
shouldgetTestOKmessage.Ifnot,checkyourconnectionsagain.
Now lets read theMicrocontroller. Go toCommand>Read All. It should start reading the
signatureandtheflashmemory.YoushouldgetReadSuccessfulmessageafterthat.
Sowearedonewiththesettingsandtestings.Everythingisworkingfine:)Nowjustopenthe
hexfilefromFile>OpenDeviceFile
-
7/31/2019 10. E&R Basic
39/186
38|P a g e
Go to Command>WriteProgram (Flash). It will start writing and then verifying the code.
Congratulations:)youdidit!
4.9 USBProgrammerUSBaspisaUSBincircuitprogrammerforAtmelAVRcontrollers.ItsimplyconsistsofanATMega48
oranATMega8anda coupleofpassivecomponents.Theprogrammerusesa firmwareonlyUSBdriver;nospecialUSBcontrollerisneeded.
Chapter5 CodeVisionAVR(CVAVR)
-
7/31/2019 10. E&R Basic
40/186
39|P a g e
AnIDEhasfollowingfunctions:
Preprocessing
Compilation
Assembly
Linking
ObjectTranslation
TextEditor
Ifwejustusecompilerand linker independentlywe stillneed togeta texteditor.Socombiningeverythingwillactuallymess thingsup.So thebestway is togetSoftwarewhichhas itall.Thats
calledanIntegratedDevelopmentEnvironment,inshortIDE.
I consider CodeVisionAVR to be the best IDE for getting started with AVR programming on
WindowsXP,Vista.IthasaverygoodCodeWizardwhichgeneratecodesautomatically!Youneed
notmesswiththeassemblywords.So inallmytutorials IwillbeusingCVAVR.Youcandownload
evaluationversionforfreewhichhascodesizelimitationbutgoodenoughforourpurpose.
For all my examples I will be using Atmega16 as default microcontroller because it very easily
availableand ispowerfulenoughwith sufficientnumberofpinsandperipheralsweuse.Youcan
havealookonthedatasheetofAtmega16inthedatasheetsection.
Letstakealookonthesoftware.Themainwindowlookslikefollowing,
NowclickonFile >New >Project
-
7/31/2019 10. E&R Basic
41/186
40|P a g e
ApopupwindowwillcomeaskingwhetheryouwanttouseCodeWizardAVR,obviouslyselectyes
becausethatisthereasonweareusingCVAVR!
NowhavealookonthisWizard.IthasmanytabswherewecanconfigurePORTS,TIMERS,LCD,ADC
etc.Iamexplainingsomeofthem
5.1 CHIP:Select thechip forwhichyouaregoing towrite theprogram.Thenselect the frequencyatwhich
Chipisrunning.BydefaultallchipsaresetonInternalOscillatorof1MHzsoselect1MHzifthatis
thecase.Ifyouwanttochangetherunningclockfrequencyofthechipthenyouhavetochangeits
fusebits(Iwilltalkmoreaboutthisinfusebitssection).
5.2 PORT:
-
7/31/2019 10. E&R Basic
42/186
41|P a g e
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 isperforming. Iwill talkmoreabout registers later.All thedetailsare
providedinthedatasheet.
Soyoucanconfigureanypinasoutputorinputbyclickingthebox.
ForAtmega16whichhas4Portswecansee4tabseachcorrespondingtoonePort.Youcanalsoset
initial
value
of
the
Pins
you
want
to
assign.
or
if
you
are
using
a
pin
as
input
then
whether
you
want
tomakeitaspulluportristated,againIwilltalkindetailsaboutthesefunctionslater.
SimilarlyusingthiscodewizardyoucanveryeasilyconfigurealltheperipheralsontheAtmega.
NowforgeneratingcodejustgotoFile >Generate,SaveandExit(ofthecodewizard)
-
7/31/2019 10. E&R Basic
43/186
42|P a g e
Now itwillaskyounameand locationforsavingthreefiles.Twobeingprojectfilesandonebeing
the .C filewhich isyourprogram. try tokeepsamenamesofallthree files toavoidconfusion.By
defaultthesefilesaregeneratedinC:\CVAVR\bin
Thegeneratedprogramwillopeninthetexteditor.HavealookithassomedeclarationslikePORT,
DDR,TCCR0andmanymore.Theseareallregisterswhichconfiguresvarious functionsofAtmega
and by changing these value we make different functions. All the details about the registers are
commentedjustbelow them.Nowgodownand find following infinitewhile loop there.We can
startwritingourpartofprogramjustbeforethewhileloop.Andasformostoftheapplicationswe
wantmicrocontrollertoperformthesametaskforeverweputourpartofcodeintheinfinitewhileloopprovidedbythecodewizard!
While (1)
{
//Placeyourcodehere
};
}
Seehowfriendlythiscodewizardis,allthework(configuringregisters)automaticallydoneandwe
dontevenneedtounderstandandgotothedetailsaboutregisterstoo!
Nowwewanttogeneratethehexfile,sofirstcompiletheprogram.EitherpressF9orgotoProject
>Compile.
Itwillshowcompilationerrorsifany.Ifprogramiserrorfreewecanproceedtomakingofhexfile.
SoeitherpressShift+F9orgotoProject >Make.Apopupwindowwillcomewith information
aboutcodesizeandflashusageetc.
Sothemachinefileisreadynow!Itisinthesamefolderwherewesavedthose3files.
-
7/31/2019 10. E&R Basic
44/186
43|P a g e
Cha
6.1
6.2
ter6 InFeatures
Advanced
Upto16M
16KBytes
512BytesE
1KByteInt
32Progra
InSystem
8channel,
Two8bitT
One16bit
FourPWM
Programm
Master/Sla
Byteorient
Programm
Externalan
PinConfi
troducti
ISCArchitec
IPSThrough
fInSystem
EPROM
ernalSRAM
mableI/OLi
rogramming
10bitADC
imer/Counte
Timer/Count
Channels
bleSerialUS
veSPISerialI
edTwo
wire
bleWatchd
dInternalIn
uration
ntoAtm
ure
utat16MH
elfProgram
nes
byOnchip
rswithSepa
erwithSepa
ART
nterface
SerialInterf
gTimerwith
erruptSourc
ega16M
z
mableFlash
ootProgram
atePrescale
ratePrescale
ce
SeparateOn
es
icrocont
rsandComp
r,Compare
chipOscilla
oller
reModes
ode,andCa
or
pture
-
7/31/2019 10. E&R Basic
45/186
44|P a g e
6.3 BlockDiagram
-
7/31/2019 10. E&R Basic
46/186
45|P a g e
6.4 PinDescriptionsVCC:Digitalsupplyvoltage.(+5V)
GND:Ground.(0V)Notethereare2groundPins.
PortA(PA7 PA0)
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(PB7 PB0)
PortBisan8bitbidirectionalI/Oportwithinternalpullupresistors(selectedforeachbit).PortB
also serves the functions of various special features of the ATmega16 as listed on page 58 of
datasheet.
PortC(PC7 PC0)
PortCisan8bitbidirectionalI/Oportwithinternalpullupresistors(selectedforeachbit).PortC
alsoservesthefunctionsoftheJTAGinterfaceandotherspecialfeaturesoftheATmega16aslisted
onpage61 ofdatasheet. If the JTAG interface is enabled, thepullup resistorson pinsPC5(TDI),
PC3(TMS)andPC2(TCK)willbeactivatedevenifaresetoccurs.
PortD(PD7 PD0)
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 toVCC,even if theADC isnotused. If theADC isused, itshouldbeconnected toVCC
throughalowpassfilter.
AREF:AREFistheanalogreferencepinfortheA/DConverter.
-
7/31/2019 10. E&R Basic
47/186
46|P a g e
6.5 DigitalInputOutputPortSoletsstartwithunderstandingthefunctioningofAVR.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.
PA0 PA7(PORTA)
PB0 PB7(PORTB)
PC0 PC7(PORTC)
PD0 PD7(PORTD)
Noticethatallthesepinshavesomefunctionwritteninbracket.Theseareadditionalfunctionthat
pincanperformotherthanI/O.Someofthemare.
ADC(ADC0 ADC7onPORTA)
UART(Rx,TxonPORTD)
TIMERS(OC0 OC2)
SPI(MISO,MOSI,SCKonPORTB)
ExternalInterrupts(INT0 INT2)
6.6 RegistersAlltheconfigurationsinmicrocontrollerissetthrough8bit(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.Therearetotal32x8bitregisters inAtmega16.AsRegistersizeof
thismicrocontrolleris8bit,itcalledas8bitmicrocontroller.
-
7/31/2019 10. E&R Basic
48/186
47|P a g e
Chapter7 I/OPorts:InputOutputfunctionsaresetbyThreeRegistersforeachPORT.
DDRX >SetswhetherapinisInputorOutputofPORTX.
PORTX >SetstheOutputValueofPORTX.
PINX >ReadstheValueofPORTX.
Go
to
the
page
50
in
the
datasheet
or
you
can
also
see
the
I/O
Ports
tab
in
the
Bookmarks.
7.1 DDRX(DataDirectionRegister)Firstofallweneedtosetwhetherwewantapintoactasoutputorinput.DDRXregistersetsthis.
EverybitcorrespondstoonepinofPORTX.LetshavealookonDDRAregister.
Bit 7 6 5 4 3 2 1 0
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 1 1 0 1 0 0 0 1
ForthisconfigurationwehavetosetDDRBas11010001whichinhexadecimalisD1.Sowewillwrite
DDRB=0xD1
Summary
DDRX >tosetPORTXasinput/outputwithabyte.
DDRX.y >tosetythpinofPORTXasinput/outputwithabit(worksonlywithCVAVR).
-
7/31/2019 10. E&R Basic
49/186
48|P a g e
7.2 PORTX(PORTXDataRegister)ThisregistersetsthevaluetothecorrespondingPORT.NowapincanbeOutputorInput.Solets
discussboththecases.
OutputPin
Ifapinissettobeoutput,thenbysettingbit1wemakeoutputHighthatis+5Vandbysettingbit0
wemakeoutputLowthatis0V.
Letstakeanexample.ConsiderIhavesetDDRA=0xFF,thatisallthepinstobeOutput.NowIwant
tosetOutputsasshownintable,
PORTA PA7 PA6 PA5 PA4 PA3 PA2 PA1 PA0
Value High(+5V) High(+5V) Low(0V) Low(0V) Low(0V) High(+5V) High(+5V) Low(0V)
PORTA 1 1 0 0 0 1 1 0
For this configurationwe have to setPORTAas11000110which in hexadecimal isC6. Sowewill
writePORTA=0xC6;
InputPin
Ifapin is set tobe input, thenby setting its correspondingbit inPORTX registerwillmake itas
follows,Setbit0 >TriStatedSetbit1 >PullUp
Tristatedmeanstheinputwillhang(nospecificvalue)ifnoinputvoltageisspecifiedonthatpin.
PullUpmeansinputwillgoto+5Vifnoinputvoltageisgivenonthatpin.Itisbasicallyconnecting
PINto+5Vthrougha10KOhmresistance.
Summary
PORTX >tosetvalueofPORTXwithabyte.
PORTX.y >tosetvalueofyth
pinofPORTXwithabit(worksonlywithCVAVR)
7.3 PINX(DataReadRegister)ThisregisterisusedtoreadthevalueofaPORT.IfapinissetasinputthencorrespondingbitonPIN
registeris,
0forLowInputthatisV2.5V(Ideally,butactually0.8V 2.8Viserrorzone!)
ForanexampleconsiderIhaveconnectedasensoronPC4andconfigureditasaninputpinthrough
DDRregister.NowIwanttoreadthevalueofPC4whetheritisLoworHigh.SoIwilljustcheck4th
bitofPINCregister.
Wecanonly readbitsof thePINXregister;canneverwriteon thatas it ismeant forreading the
valueofPORT.
Summary
PINX >ReadcompletevalueofPORTXasabyte.
PINX.y >ReadythpinofPORTXasabit(worksonlywithCVAVR).
-
7/31/2019 10. E&R Basic
50/186
49|P a g e
7.4 ASMALLNOTEABOUTDELAYChasinbuiltlibrarieswhichcontainmanyprebuiltfunctions.OnesuchfunctionisDelay,which
introducesatimedelayataparticularstep.Toinvokeitinyourprogram,youneedtoaddthe
followinglineatthebeginningofyourcode:
#include;
Thereafter,
it
can
be
used
in
the
program
by
adding
the
following
line:
delay_ms(X);
WhereXisthetimedelayyouwishtointroduceatthatparticularstepinmilliseconds.
IhopeyoumusthavegotbasicideaaboutthefunctioningofI/OPorts.Fordetailedreadingyoucan
alwaysrefertodatasheetofAtmega.
-
7/31/2019 10. E&R Basic
51/186
50|P a g e
Chapter8 LCDInterfacingNowweneedtointerfaceanLCDtoourmicrocontrollersothatwecandisplaymessages,outputs,
etc.SometimesusinganLCDbecomesalmost inevitable fordebuggingandcalibrating thesensors
(discussed later).Wewilluse the16x2 LCD,whichmeans ithas two rowsof16characterseach.
Henceintotalwecandisplay32characters.
8.1Overview
of
LCD
Display
LCD displays are widely used in many applications like mobile phones, robotics, DVD players,
Measurement instrumentsetc. Intelligent LCDdisplaysareverycapablebecause theycandisplay
complete ASCII character set and even graphics. These displays are easily connected with micro
controllerandmicroprocessors. LCDdisplaysarecompleteembedded system in them,because it
includemicrocontroller,RAMandROM.
16X2LCDDISPLAY
LCDModulescanpresenttextualinformationtouser.Itslikeacheapmonitorthatyoucanhook
inallofyourgadgets.
Theycomeinvarioustypes.Themostpopularoneis16x2LCDmodule.Ithas2rows&16columns.
Theintelligentdisplaysaretwotypes:
a)TextDisplay
b)GraphicsDisplay
TextdisplaycandisplayallcharactersetandgraphicsdisplaycanshowanyGraphicsbecause theyareinterfacedpixelwise.
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.
Wewill learnhow to interface the text intelligent LCDdisplay.Thesedisplaysareavailable in themarketof16columnandoneRowandmorethanonerowdisplays.
BlockDiagramofLCDDisplay
-
7/31/2019 10. E&R Basic
52/186
51|P a g e
MICROCONTROLLER:
ItisthebrainofLCDdisplay.ThisishandlingtheallworkingoftheLCD.
DATARAM:
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 ofcharacterswillbegiventothedataregister.
BF(BUSYFLAG):
ItindicatestheinternalworkingoftheLCD.ItshowwhetherLCDisbusyinanyoperationornot.
IfBF=0(LCDisidlewecanproceedfornextoperation)
IfBF=1 (LCD isbusywecannotproceed fornextoperationandwehave towaitunlessoperation
completes).
DESCRIPTION
OF
PINS
IS
GIVEN
BELOW:
VCC,VSSandVO:
WhileVCCandVSSprovide+5Voltsandground,respectivelyVEEisusedforcontrollingLCDcontrast
RS(REGISTERSELECT):
TheRSpinisusedtoselectDataRegisterorCommandRegister.
Data
Register
Command
Register
Busy
Code
RAM
DataRAMMicro
controller
ROM
-
7/31/2019 10. E&R Basic
53/186
52|P a g e
IfRS=
theho
IfRS=
R/W(
When
When
EN(E
The E
suppli
prese
There
D7D0
This is
LCDsi
BKLE
These
LCDdi
8.2There
Thec
8.3When
figure.
,CRRegiste
meetc.
,DRRegiste
READ/WRITE
R/W=0,Writ
R/W=1Read
ABLE):
able pin is
ed to data p
tatthedata
shouldbepo
:
8bitdatap
internalregis
(LEDA,LED
pinsareuse
splaycanbe
CircuitC
are16pinsi
nnectionsha
Settingu
weconnect
ToenableL
isselected,
isselected,
):
eoperation..
Operation
used by the
ins, a negati
pins.Thispu
sitiveedgea
ins.D7D0a
ters.
K):
dtogivethe
viewedinth
nnection
anLCD;See
vetobema
inMicro
anLCDtoAt
Dinterfacin
allowingthe
allowingthe
LCD to latc
ve edge is a
lsemustbe
ENpinwhe
eusedtos
supplytot
dark.
reverseside
easshown
ontrolle
mega16,on
ginthemicr
Fig
usertosend
usertosend
h binary bits
pplied to thi
minimumo
nreadopera
nd informati
eback light
oftheLCDf
elow:
fullPORT is
ocontroller,j
re14:LCDcon
acommand
datatobedi
available o
s pin So tha
450nswid
ionisrequir
ontotheL
oftheLCDd
rthePINco
dedicatedt
ustclickont
ections
suchasclea
splayonthe
its data pi
t the LCD la
.
d.
Dorreadth
isplay.So,th
figuration.
it,denoted
heLCDtabi
rdisplay,cur
LCD.
ns. When d
tches in the
econtentso
atcontento
byPORTXi
theCodeW
erat
ta is
data
fthe
fthe
nthe
izard
-
7/31/2019 10. E&R Basic
54/186
53|P a g e
andselect thePORTatwhichyouwant toconnect theLCD.WewillselectPORTC.Alsoselectthe
numberofcharactersper line inyourLCD.This is16 inourcase.CodeWizardnowshowsyouthe
complete listofconnectionswhichyouwillhavetomake inorderto interfacetheLCD.Theseare
nothingbutthesameasintheabovefigureforgeneralPORTX.
Figure15:LCDsettingsonCVAVRwizardwindow.
Asyoucansee,therearesomespecialconnectionsotherthanthosetouC,Vccandgnd.Thesearegeneral LCD settings. Pin 3 (VO) is for the LCD contrast, ground it through a
-
7/31/2019 10. E&R Basic
55/186
54|P a g e
8.4 PrintingFunctionsNow once the connections have been made, we are ready to display something on our screen.
Displayingournamewouldbegreattostartwith.SomeofthegeneralLCDfunctionswhichyoumust
knoware:
8.4.1 lcd_clear()Clearsthe lcd.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
weneed to firstconvert thatnumericvalue toa stringand thendisplay it.Fore.g., ifwehavea
variableoftype integer,say intk,andweneedtodisplaythevalueofk(whichchangeseverynow
andthen,200nowand250afterasecond...andsoon).Forthis,weusetheCfunctionsitoa()and
ftoa(),butremembertoincludetheheaderfilestdlib.htousetheseCfunctions.
-
7/31/2019 10. E&R Basic
56/186
55|P a g e
8.4.6 itoa(intval,chararr[])Itstores thevalueof integerval in thecharacterarrayarr.E.g.,wehavealreadydefined int iand
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
like
to
see
glowing
on
it!
-
7/31/2019 10. E&R Basic
57/186
56|P a g e
Chapter9 ADC:Analog to Digital ConverterMost 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.Nowwehave broughtaphysical
quantity into theelectricaldomain.Theelectricalquantity inmostcases isvoltage.Tobringthis
quantityintodigitaldomainwehavetoconvertthisintodigitalform.ForthisanADCoranalogue
todigitalconverterisneeded.MostmodernMCUincludingAVRshaveanADConchip.AnADCconvertsaninputvoltageintoanumber.AnADChasaresolution.A8bitADChasarange
of0255.(28=256)TheADCalsohasaReferenceVoltage(ARef).WhentheinputvoltageisGNDthe
outputis0andwhentheinputvoltageisequaltoAReftheoutputis255.Sotheinputrangeis0to
ARefandtheoutputrangeis0to255.
InputVoltage DigitalOutput
0V 0
2.5V 127
5V 255
You
can
see
that
any
analogue
signal
is
not
perfectly
converted
a
factor
that
affects
the
outputquality isthesamplingrate.The ADC cannot continuously read theinputsignal and
change its output it doesso incertain time intervals. The frequencyatwhich itsamplesthe
inputiscalleditssamplingrate.
Also, thevalue of the analoguesignal read is not stored perfectly for example, a voltage
of2.501 would be read as 2.5V i.e. 127 in digital format. Thus, the signal is quantized,or,
inotherterms,thereiscertaingraininesstothedigitalsignalthatyouobtain.Howaccurateyour
digitalsignal isdependsonyourresolutionhigher resolutionwillmakeyourdigitalsignalmore
accurate.
-
7/31/2019 10. E&R Basic
58/186
57|P a g e
9.1What
(logic
requirissuch
ADC is
voltag
value
isnot
Refer
and 1
Refer
used.
+5Vis
9.2
Theoryo
we havesee
).Butwhati
eatool
that
atool.
availableate and get co
rangesfrom
required.
ncevoltage
23 for 10 b
nce Voltage)
Forexample,
digitally102
Settingu
operatio
ntillnowth
fwehavean
convertsthis
PORTAofA
rresponding
to1023.Bu
isthevoltag
it). Hence, t
into 1024
iftherefere
and2.5Vis
Microco
ADC=Vi
ADC=Vi
atthe input
analoginpu
analog
volt
mega16.Th
digital value
twecanals
towhichth
e ADC of At
r 256 equal
ncevoltagei
approximate
troller
x255/Vref
x1023/Vr
giventouC
,i.e.,valuev
geto
discret
swehave8
s. The ADC r
useonly8b
eADCassign
mega16 divi
parts, depen
s5Vandwe
lyequalto5
(8
ef(10bit)
asdigital, i
ariesovera
evalues.
An
pinsavailab
egister is a
itoutofit(0
sthemaxim
des the inpu
ding upon
use10bitA
2.
bit)
.e.,either +5
range,say0
logto
Digita
lewherewe
0 bit regist
to255)ast
umvalue(2
t analog vol
hether 10 b
C,0Vhasdi
V(logic1)
to+5V?Th
lConverter
(
canapplya
r, i.e., the d
omuchpre
5incaseof
age range (
it or 8 bit A
gitalequival
r0V
nwe
ADC)
alogigital
ision
8bit
V to
DC is
nt0,
-
7/31/2019 10. E&R Basic
59/186
58|P a g e
ToenableADCinAtmega16,clickontheADCtabinCodeWizardandenablethecheckbox. Youcan
alsocheckuse8bitsasthatissufficientforourpurposeand10bitaccuracyisnotrequired.Ifthe
inputvoltagerangesfrom0tolessthan+5V,thenapplythatvoltageatAREF(pin32)andselectthe
Volt.Ref.asAREFpin.Butifitrangesfrom0to+5V,youcanselecttheVolt.Ref.asAVCCpinitself.
Keeptheclockat itsdefaultvalueof125kHzandselecttheAutoTriggerSourceasFreeRunning.
Youcanalsoenableaninterruptfunctionifyourequire.
9.3 FunctionforgettingADCNowwhenyougenerateandsavethecode,alltheregistervaluesaresetautomaticallyalongwitha
function:
unsignedcharread_adc(unsignedcharadc_input).
ThisfunctionreturnsthedigitalvalueofanaloginputatthatpinofPORTAwhosenumberispassedasparameter,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);