key board interfacing

Upload: naresh-ram

Post on 08-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Key Board Interfacing

    1/99

    Key Board Interfacing:

    Keyboards are organized in a matrix of rows and columnsThe CPU accesses both rows and columns through portsTherefore, with two 8-bit ports, an 8 x 8 matrix of keys can be connected to a microprocessorWhen a key is pressed, a row and a column make a contact

    Otherwise, there is no connection between rows and columnsIn IBM PC keyboards, a single microcontroller takes care of hardware and software interfacing

    A 4x4 matrix connected to two ports

    The rows are connected to an output port and the columns are connected to an input port

    It is the function of the microcontroller to scan the keyboard continuously to detect and identify the key pressed

    To detect a pressed key, the microcontroller grounds all rows by providing 0 to the output latch, then it reads thecolumns

    If the data read from columns is D3 D0 =1111, no key has been pressed and the process continues till key pressis detected

    If one of the column bits has a zero, this means that a key press has occurredFor example, if D3 D0 = 1101, this means that a key in the D1 column has been pressedAfter detecting a key press, microcontroller will go through the process of identifying the key

    Starting with the top row, the microcontroller grounds it by providing a low to row D0 only

    It reads the columns, if the data read is all 1s, no key in that row is activated and the process is moved to the nextrow

    It grounds the next row, reads the columns, and checks for any zeroThis process continues until the row is identifiedAfter identification of the row in which the key has been pressedFind out which column the pressed key belongs to

    Program 12-4 for detection and identification of key activation goes through the following stages:

    1. To make sure that the preceding key has been released, 0s are output to all rows at once, and the columns are read

    and checked repeatedly until all the columns are high

    When all columns are found to be high, the program waits for a short amount of time before it goes to the next

    stage of waiting for a key to be pressed2. To see if any key is pressed, the columns are scanned over and over in an infinite loop until one of them has a 0

    on it

    Remember that the output latches connected to rows still have their initial zeros (provided in stage 1), makingthem grounded

    After the key press detection, it waits 20 ms for the bounce and then scans the columns again(a) it ensures that the first key press detection was not an erroneous one due a spike noise

    (b) the key press. If after the 20-ms delay the key is still pressed, it goes back into the loop to detect a real key press

  • 8/7/2019 Key Board Interfacing

    2/99

    3. To detect which row key press belongs to, it grounds one row at a time, reading the columns each time

    If it finds that all columns are high, this means that the key press cannot belong to that row Therefore, it groundsthe next row and continues until it finds the row the key press belongs to

    Upon finding the row that the key press belongs to, it sets up the starting address for the look-up table holding thescan codes (or ASCII) for that row4. To identify the key press, it rotates the column bits, one bit at a time, into the carry flag and checks to see if it is

    low

    Upon finding the zero, it pulls out the ASCII code for that key from the look-up tableotherwise, it increments the pointer to point to the next element of the look-up table

    Program 12-4: Keyboard Program;keyboard subroutine. This program sends the ASCII;code for pressed key to P0.1 ;P1.0-P1.3 connected to rows,

    P2.0-P2.3 to column

    MOV P2,#0FFH ; make P2 an input port

    K1: MOV P1,#0 ; ground all rows at onceMOV A,P2 ; read all col

    ;(ensure keys open)

    ANL A,00001111B ; masked unused bits

    CJNE A,#00001111B,K1 ; till all keys release

    K2: ACALL DELAY ; call 20 msec delayMOV A,P2 ; see if any key is pressed

    ANL A,00001111B ; mask unused bits

    CJNE A,#00001111B,OVER; key pressed, find row

    SJMP K2 ; check till key pressed

    OVER: ACALL DELAY ; wait 20 msec debounce time

    MOV A,P2 ; check key closureANL A,00001111B ; mask unused bits

    CJNE A,#00001111B,OVER1; key pressed, find row

    SJMP K2 ; if none, keep polling

    OVER1: MOV P1, #11111110B ; ground row 0

    MOV A,P2 ; read all columnsANL A,#00001111B ; mask unused bits

    CJNE A,#00001111B,ROW_0 ; key row 0, find col.

    MOV P1,#11111101B ; ground row 1

    MOV A,P2 ; read all columns

    ANL A,#00001111B ; mask unused bits

  • 8/7/2019 Key Board Interfacing

    3/99

    CJNE A,#00001111B,ROW_1 ; key row 1, find col.

    MOV P1,#11111011B ; ground row 2

    MOV A,P2 ; read all columns

    ANL A,#00001111B ; mask unused bits

    CJNE A,#00001111B,ROW_2 ; key row 2, find col.MOV P1,#11110111B ; ground row 3MOV A,P2 ; read all columnsANL A,#00001111B ; mask unused bits

    CJNE A,#00001111B,ROW_3 ; key row 3, find col.

    LJMP K2 ; if none, false input,

    ;repeat

    ROW_0: MOV DPTR,#KCODE0 ; set DPTR=start of row 0

    SJMP FIND ; find col. Key belongs to

    ROW_1: MOV DPTR,#KCODE1 ; set DPTR=start of row

    SJMP FIND ; find col. Key belongs to

    ROW_2: MOV DPTR,#KCODE2 ; set DPTR=start of row 2SJMP FIND ; find col. Key belongs to

    ROW_3: MOV DPTR,#KCODE3 ; set DPTR=start of row 3FIND: RRC A ; see if any CY bit lowJNC MATCH ; if zero, get ASCII code

    INC DPTR; point to next col. addrSJMP FIND ; keep searching

    MATCH: CLR A ; set A=0 (match is found)

    MOVC A,@A+DPTR; get ASCII from table

    MOV P0,A ; display pressed key

    LJMP K1

    ;ASCII LOOK-UP TABLE FOR EACH ROW

    ORG 300HKCODE0: DB 0,1,2,3 ;ROW 0KCODE1: DB 4,5,6,7 ;ROW 1KCODE2: DB 8,9,A,B ;ROW 2

    KCODE3: DB C,D,E,F ;ROW 3

    END

    ADC interfacing with Microcontrollers: Introduction

    Introduction

    In our daily life, anything we deal like sound, prassure, voltage or any measurable quantity, are usually in analog form Sowhat if we want to interface any analog sensor with our digital controllers? There must be something that translate theanalog inputs to digital output, and so Analog to digital convertors come to play. Usually we call them ADC (Analog to digitalconvertor). Before going to learn how to interface an ADC with a controller we first take a look at basic methods of analogto digital conversion.

    This is a sample of the large number of analog-to-digital conversion methods. The basic principle of operation is to use the

    comparator principle to determine whether or not to turn on a particular bit of the binary number output. It is typical for anADC to use a digital-to-analog converter (DAC) to determine one of the inputs to the comparator.

    Following are the most used converion methods:

    Digital-Ramp ADC Successive Approximation ADC Flash ADC

  • 8/7/2019 Key Board Interfacing

    4/99

    Digital-Ramp ADC

    Conversion from analog to digital form inherently involves comparator action where the value of the analog voltage at somepoint in time is compared with some standard. A common way to do that is to apply the analog voltage to one terminal of acomparator and trigger a binary counter which drives a DAC. The output of the DAC is applied to the other terminal of thecomparator. Since the output of the DAC is increasing with the counter, it will trigger the comparator at some point when itsvoltage exceeds the analog input. The transition of the comparator stops the binary counter, which at that point holds thedigital value corresponding to the analog voltage.

    Successive Approximation ADC

    Illustration of 4-bit SAC with 1 volt step size

    The successive approximation ADC is much faster than the digital ramp ADC because it uses digital logic to converge on thevalue closest to the input voltage. A comparator and a DAC are used in the process. A flowchart explaning the working isshown in the figure below.

  • 8/7/2019 Key Board Interfacing

    5/99

    Flash ADC

    Illustrated is a 3-bit flash ADC with resolution 1 volt (after Tocci). The resistor net andcomparators provide an input to the combinational logic circuit, so the conversion time is just the propagation delay throughthe network - it is not limited by the clock rate or some convergence sequence. It is the fastest type of ADC available, but

    requires a comparator for each value of output (63 for 6-bit, 255 for 8-bit, etc.) Such ADCs are available in IC form up to 8-bit and 10-bit flash ADCs (1023 comparators) are planned. The encoder logic executes a truth table to convert the ladder ofinputs to the binary number output.

  • 8/7/2019 Key Board Interfacing

    6/99

    ADC interfacing with Microcontrollers: Interfacing ADC0804

    ADC0804 Pinoutand TypicalConnections

    As shown in the typica circuit, ADC0804 can be interfaced with any microcontroller. You need a minimum of 11 pins tointerface ADC0804, eight for data pins and 3 for control pins. As shown in the typical circuit the chip select pin can be madelow if you are not using the microcontroller port for any other peripheral (multiplexing).

    There is a universal rule to find out how to use an IC. All you need is the datasheet of the IC you are working with and takea look at the timing diagram of the IC which shows how to send the data, which signal to assert and at what time the signalshould be made high or low etc.

    Note: Keep this in mind that whenever you are working with an IC and you want to know how to communicate with thatIC, then simply look into the timing diagram of that IC from its datasheet. It gives you complete information that you needregarding the communication of IC.

  • 8/7/2019 Key Board Interfacing

    7/99

    The above timing diagrams are from ADC0804 datasheet. The first diagram (FIGURE 10A) shows how to start a conversion.Also you can see which signals are to be asserted and at what time to start a conversion. So looking into the timing diagram

    FIGURE 10A. We note down the steps or say the order in which signals are to be asserted to start a conversion of ADC. Aswe have decided to make Chip select pin as low so we need not to bother about the CS signal in the timing diagram. Belowsteps are for starting an ADC conversion. I am also including CS signal to give you a clear picture. While programming wewill not use this signal.

    1. Make chip select (CS) signal low.2. Make write (WR) signal low.3. Make chip select (CS) high.

    4. Wait for INTR pin to go low (means conversion ends).

    Once the conversion in ADC is done, the data is available in the output latch of the ADC. Looking at the FIGURE 10B whichshows the timing diagram of how to read the converted value from the output latch of the ADC. Data of the new conversionis only avalable for reading after ADC0804 made INTR pin low or say when the conversion is over. Below are the stepts toread output from the ADC0804.

    1. Make chip select (CS) pin low.2. Make read (RD) signal low.3. Read the data from port where ADC is connected.4. Make read (RD) signal high.

    5. Make chip select (CS) high.

  • 8/7/2019 Key Board Interfacing

    8/99

  • 8/7/2019 Key Board Interfacing

    9/99

    DIGITAL TO ANALOG.

    Digital To Analog Converter.

  • 8/7/2019 Key Board Interfacing

    10/99

  • 8/7/2019 Key Board Interfacing

    11/99

    Introduction

    Thepurposeofthischapteristoprovide basicinformationaboutmicrocontrollersthatoneneedsto know

    inorderto beabletousethemsuccessfully inpractice. Thisiswhy thischapterdoesn'tcontainany super

    interestingprogramordeviceschematicwithamazingsolutions.Instead,thefollowingexamplesare

    betterproofthatprogramwritingisneitheraprivilegenoratalentissue, buttheability ofsimply putting

    puzzlepiecestogetherusingdirectives.Restassuredthatdesignanddevelopmentofdevicesmainly

    consistsofthefollowingmethod test-correct-repeat.Ofcourse,themore youareinit,themore

    complicatedit becomessincethepuzzlepiecesareputtogetherby bothchildrenandfirst-class

    architects...

    6.1 Basic connecting

    Asseeninthefigureabove,inordertoenablethemicrocontrollertooperateproperly itisnecessary to

    provide:

    y Powersupply:

    y Resetsignal:and

    y Clock signal.

    Clearly,itisaboutvery simplecircuits, butitdoesnothaveto bealwayslikethat.Ifthetargetdeviceis

    usedforcontrollingexpensivemachinesormaintainingvitalfunctions,everythinggetsincreasingly

    complicated. However,thissolutionissufficientforthetime being...

    Power supply

    Eventhoughthismicrocontrollercanoperateatdifferentpowersupply voltages,why totest Murphys

    low?! A 5V DCismostcommonly used. Thecircuit,showninthefigure,usesacheapintegratedthree-

    terminalpositiveregulatorLM7805,andprovideshigh-quality voltagestability andquiteenoughcurrentto

    enablethemicrocontrollerandperipheralelectronicstooperatenormally (enoughcurrentinthiscase

    means 1Amp).

    Reset signal

    Inorderthatthemucrocontrollercanoperateproperly,alogic0 (0V)must beappliedtotheresetpinRS.

    Thepush buttonconnectingtheresetpinRStopowersupply VCCisnotnecessary. However,itisalmost

    alwaysprovided becauseitenablesthemicrocontrollersafereturntonormaloperatingconditionsif

    somethinggoeswrong. 5V is broughttothispin,themicrocontrollerisresetandprogramstartsexecution

    fromthe beginning.

    Clock signal

  • 8/7/2019 Key Board Interfacing

    12/99

    Eventhoughthemicrocontrollerhasa built-inoscillator,itcannotoperatewithouttwoexternalcapacitors

    andquartzcrystalwhichstabilizeitsoperationanddeterminesitsfrequency (operatingspeedofthe

    microcontroller).

    Ofcourse,itisnotalwayspossibletoapply thissolutionsothattherearealwaysalternativeones. Oneof

    themistoprovideclock signalfromaspecialsourcethroughinvertor.Seethefigureontheleft.

    6.2 Additional components

    Regardlessofthefactthatthemicrocontrollerisaproductofmoderntechnology,itisofnousewithout

    beingconnectedtoadditionalcomponents.Simply put,theappearanceofvoltageonitspinsmeans

    nothingifnotusedforperformingcertainoperations (turnsomethingon/off,shift,display etc.).

    Switches and Push buttons

    Therearenosimplerdevicesthanswitchesandpush-buttons. Thisisthesimplestway ofdetecting

    appearanceofavoltageonthemicrocontrollerinputpin.

    Nevertheless,itisnotsosimpleinpractice...Itisaboutcontact bounce-acommonproblemwithmech

    anicalswitches. Whenthecontactsstriketogether,theirmomentumandelasticity acttogetherto

    cause bounce. Theresultisarapidly pulsedelectricalcurrentinsteadofacleantransitionfromzerotofull

    current.Itmostly occursduetovibrations,slightroughspotsanddirt betweencontacts. Thiseffectis

    usually unnoticeablewhenusingthesecomponentsineveryday life becausethe bouncehappenstoo

    quickly.Inotherwords,thewholethisprocessdoesnotlastlong (afewmicro-ormiliseconds), butitis

    longenoughto beregistered by themicrocontroller. Whenusingonly apush-buttonasapulsecounter,

    errorsoccurinalmost 100%ofcases!

    ThesimplestsolutiontothisproblemistoconnectasimpleRCcircuittosuppressquick voltagechanges.

    Sincethe bounceperiodisnotdefined,thevaluesofcomponentsarenotprecisely determined.Inmost

    cases,itisrecomendedtousethevaluesshowninfigure below.

    Ifcompletestability isneededthenradicalmeasuresshould betaken. Theoutputofthecircuit,shownin

    figure (RSflip-flop),willchangeitslogicstateonly afterdetectingthefirstpulsetriggered by contact

    bounce. Thissolutionisexpensive (SPDT switch), buteffecient,theproblemisdefinitely solved.Since

    thecapacitorisnotused,very shortpulsescanalso beregisteredinthisway.

  • 8/7/2019 Key Board Interfacing

    13/99

    Inadditiontothesehardwaresolutions,thereisalsoasimplesoftwaresolution. Whenaprogramtests

    thestateofaninputpinanddetectsachange,thecheck should bedoneonemoretimeafteracertain

    delay.Ifthechangeisconfirmed,itmeansthataswitchorpush buttonhaschangeditsposition. The

    advantagesofsuchsolutionareobvious:itisfreeofcharge,effectsofnoisesareeliminatedanditcan be

    appliedtothepoorerquality contactsaswell.DisadvantageisthesameaswhenusingRCfilter,i.e.

    pulsesshorterthanprogramdelay cannot beregistered.

    Optocoupler

    Anoptocouplerisadevicecommonly usedtogalvanically separatemicrocontrollerselectronicsfromany

    potentially dangerouscurrentorvoltageinitssurroundings. Optocouplersusually haveone,twoorfour

    lightsources (LEDdiodes)ontheirinputwhileontheiroutput,oppositetodiodes,thereisthesame

    numberofelementssensitivetolight (phototransistors,photo-thyristorsorphoto-triacs). Thepointisthat

    anoptocouplerusesashortopticaltransmissionpathtotransferasignal betweentheelementsofcircuit,

    while keepingthemelectrically isolated. Thisisolationmakessenseonly ifdiodesandphoto-sensitive

    elementsareseparately powered.Inthisway,themicrocontrollerandexpensiveadditionalelectronics

    arecompletely protectedfromhighvoltageandnoiseswhicharethemostcommoncauseofdestroying,

    damagingorunstableoperationofelectronicdevicesinpractice. Themostfrequently usedoptocouplers

    arethosewithphototransistorsontheiroutputs. Whenusingtheoptocouplerwithinternal base-to-pin 6

    connection (therearealsooptocouplerswithoutit),the basecan beleftunconnected. Anoptional

    connectionwhichlessenstheeffectsofnoises by eliminatingvery shortpulsesispresented by the

    brokenlineinthefigure.

    Relay

    A relaysisanelectricalswitchthatopensandclosesundercontrolofanotherelectricalcircuit.Itis

    thereforeconnectedtoouputpinsofthemicrocontrollerandusedtoturnon/offhigh-powerdevicessuch

    asmotors,transformers,heaters, bulbs,antennasystemsetc. Thesearealmostalwaysplacedaway

    fromthe boardsensitivecomponents. Therearevarioustypesofrelays butallofthemoperateinthesameway. Whenacurrentflowsthroughthecoil,therelay isoperated by anelectromagnettoopenor

    closeoneormany setsofcontacts.Similartooptocouplers,thereisnogalvanicconnection (electrical

    contact) betweeninputandoutputcircuits.Relaysusually demand bothhighervoltageandcurrentto

    startoperation, buttherearealsominiatureoneswhichcan beactivated by alowcurrentdirectly

    obtainedfromamicrocontrollerpin.

  • 8/7/2019 Key Board Interfacing

    14/99

    Thefigureshowsthesolutionspecifictothe8051 microcontroller. A darlingtontransistorisusedhereto

    activaterelays becauseofitshighcurrentgain. Thisisnotinaccordancewith rules, butisnecessary in

    theeventthatlogiconeactivationisappliedsincetheoutputcurrentisthenvery low (pinactsasan

    input).

    Inordertopreventtheappearanceofself-inductionhighvoltage,caused by asuddenstopofcurrentflow

    throughthecoil,aninvertedpolarizeddiodeisconnectedinparalleltothecoil. Thepurposeofthisdiode

    isto cutoffthevoltagepeak.

    Light-emitting diode (LED)

    Light-emittingdiodesareelementsforlightsignalizationinelectronics. They aremanufacturedindifferent

    shapes,colorsandsizes.Fortheirlowprice,lowpowerconsumptionandsimpleuse,they havealmost

    completely pushedasideotherlightsources, bulbsatfirstplace. They performsimilartocommondiodes

    withthedifferencethatthey emitlightwhencurrentflowsthroughthem.

    Itisimportanttolimittheircurrent,otherwisethey will bepermanently destroyed.Forthisreason,a

    conductormust beconnectedinparalleltoan LED.Inordertodeterminevalueofthisconductor,itis

    necessary to knowdiodesvoltagedropinforwarddirection,whichdependsonwhatmaterialadiodeis

    madefromandwhatcolouritis. Typicalvaluesofthemostfrequently useddiodesareshownintable

    below. Asseen,therearethreemaintypesofLEDs.Standardonesgetful brightnessatcurrentof

    20mA.Low Currentdiodesgetful brightnessattentimeslowercurrentwhileSuper Brightdiodesproduce

    moreintensivelightthanStandardones.

    COLOR T YPE T YP I C AL C U R RENT ID

    ( M A ) M A X I M AL C U R REN T I F

    ( M A ) VOL T AGE D

    ( V )

    Infrared - 30 50 1.4

    Red Standard 20 30 1.7

    RedSuperBright

    20 30 1.85

    Red Low Current 2 30 1.7

    Orange - 10 30 2.0

    Green Low Current 2 20 2.1

    Yellow - 20 30 2.1

    Blue - 20 30 4.5

    White - 25 35 4.4

  • 8/7/2019 Key Board Interfacing

    15/99

    Sincethe8051 microcontrollercanprovideonly lowoutputcurrentandsinceitspinsareconfiguredas

    outputswhenvoltageprovidedonthemis0V,directconnectingto LEDsisperformedasshowninfigure

    ontheright (Low currentLED,cathodeisconnectedtotheoutputpin).

    LED displays

    Basically,an LEDdisplay isnothingmorethanseveral LEDsmouldedinthesameplasticcase. Thereare

    many typesofdisplayscomposedofseveraldozensofbuiltindiodeswhichcandisplay different

    symbols.

    Mostcommonly usedisasocalled 7-segmentdisplay.Itiscomposedof8 LEDs, 7 segmentsare

    arrangedasarectangleforsymboldisplayingandthereisanadditionalsegmentfordecimalpoint

    displaying.Inordertosimplify connecting,anodesandcatodesofalldiodesareconnectedtothe

    commonpinsothattherearecommonanodedisplaysandcommoncatodedisplays,respectively.

    Segmentsaremarkedwiththelattersfrom A to G,plusdp,asshowninthefigureontheleft. On

    connecting,eachdiodeistreatedsepartely,whichmeansthateachmusthaveitsowncurrentlimiting

    resistor.

    Displaysconnectedtothemicrocontrollerusually occupy alargenumberofvaluableI/O pins,whichcan

    bea bigproblemespecially ifitisneededtodisplay multy digitnumbers. Theproblemismorethan

    obviousif,forexample,itisneededtodisplay two 6-digitnumbers (asimplecalculationshowsthat 96

    outputpinsareneededinthiscase). Thesolutiontothisproblemiscalled MULTIPLEXING. Thisishow

    anopticalillusion basedonthesameoperatingprincipleasafilmcameraismade. Only onedigitis

    activeatatime, butthey changetheirstatesoquickly makingimpressionthatalldigitsofanumberare

    simultaneously active.

    Hereisanexplanationonthefigureabove.Firsta byterepresentingunitsisappliedonamicrocontroller

    portandatransistorT1 isactivatedatthesametime. Afterawhile,thetransistorT1 isturnedoff,a byte

    representingtensisappliedonaportandatransistorT2 isactivated. Thisprocessis beingcyclicallyrepeatedathighspeedforalldigitsandcorrespondingtransistors.

    Thefactthatthemicrocontrolleris justa kindofminiaturecomputerdesignedtounderstandonly the

    languageofzerosandonesisfully expressedwhendisplayingany digit.Namely,themicrocontroller

    doesn't knowwhatunits,tensorhundredsare,norwhattendigitsweareusedtolook like. Therefore,

    eachnumberto bedisplayedmust bepreparedinthefollowingway:

  • 8/7/2019 Key Board Interfacing

    16/99

    Firstofall,amulty digitnumbermust besplitintounits,tensetc.inaparticularsubroutine. Theneachof

    thesedigitsmust bestoredinspecial bytes.Digitsgetfamiliarformat by performing masking.Inother

    words,a binary formatofeachdigitisreplaced by adifferentcombinationofbitsinasimplesubroutine.

    Forexample,thedigit8 (0000 1000)isreplaced by the binary number0111 111 inordertoactivateall

    LEDsdisplayingdigit8. Theonly dioderemaininginactiveinthiscaseisreservedforthedecimalpoint.If

    amicrocontrollerportisconnectedtothedisplay insuchaway that bit0activatessegment a, bit 1

    activatessegment b, bit 2 segment cetc.,thenthetable belowshowsthe maskforeachdigit.

    D I G I T S TO D I SPL AY D I SP LAY SEG MEN T S

    dp a b c d e

    0 1 0 0 0 0 0

    1 1 0 0 1 1 1

    2 1 0 0 1 0 0

    3 1 0 0 0 0 1

    4 1 1 0 0 1 1

    5 1 0 1 0 0 1

    6 1 0 1 0 0 0

    7 1 0 0 0 1 1

    8 1 0 0 0 0 0

    9 1 0 0 0 0 1

    Inadditiontodigitsfrom0to 9,somelettersofalphabet- A,C,E, J,F, U, H, L, b,c,d,o,r,t-canalso be

    displayed by performingappropriatemasking.

    Iftheeventthatcommonchatodedisplaysareusedallunitsinthetableshould bereplaced by zerosand

    viceversa. Additionally,NPNtransistorsshould beusedasdriversaswell.

    Liquid Crystal Displays (LCD)

    An LCDdisplay isspecifically manufacturedto beusedwithmicrocontrollers,whichmeansthatitcannot

    beactivated by standardICcircuits.Itisusedfordisplayingdifferentmessagesonaminiatureliquid

    crysaldisplay.

  • 8/7/2019 Key Board Interfacing

    17/99

    Themodeldescribedhereisforitslowpriceandgreatcapabilitiesmostfrequently usedinpractice.Itis

    basedonthe HD44780microcontroller(Hitachi)andcandisplay messagesintwolineswith 16

    characterseach.Itdisplaysallthelettersofalphabet, Greek letters,punctuationmarks,mathematical

    symbolsetc.Inaddition,itispossibletodisplay symbolsmadeup by theuser. Otherusefulfeatures

    includeautomaticmessageshift (leftandright),cursorappearance, LED backlightetc.

    LCDPins

    Therearepinsalongonesideofasmallprinted board. Theseareusedforconnectingtothe

    microcontroller. Thereareintotalof14pinsmarkedwithnumbers (16 ifithas backlight). Theirfunctionis

    describedinthetable bellow:

    F UNC T ION P IN NU M BER NAME LOG I C S T A TE DES C R IPT ION

    Ground 1 Vss - 0V

    Power supply 2 Vdd - +5V

    Contrast 3 Vee - 0 - Vdd

    Control of operating

    4 RS01

    D0 D7 are interpreted as coD0 D7 are interpreted as

    5 R/W01

    Write data (from controller Read data (from LCD to con

    6 E

    0

    1From 1 to 0

    Access to LCD disable

    Normal operatingData/commands are transferr

    Data / commands

    7 D0 0/1 Bit 0 LSB

    8 D1 0/1 Bit 1

    9 D2 0/1 Bit 2

    10 D3 0/1 Bit 3

    11 D4 0/1 Bit 4

    12 D5 0/1 Bit 5

    13 D6 0/1 Bit 6

    14 D7 0/1 Bit 7 MSB

  • 8/7/2019 Key Board Interfacing

    18/99

    LCD screen

    An LCDscreenconsistsoftwolineseachcontaining 16 characters.Eachcharacterconsistsof5x8or

    5x11 dotmatrix. This book coversthemostcommonly useddisplay,i.e.the 5x8characterdisplay.

    Display contrastdependsonthepowersupply voltageandwhethermessagesaredisplayedinoneor

    twolines.Forthisreason,varyingvoltage0-Vddisappliedonthepinmarkedas Vee. Trimmer

    potentiometerisusually usedforthatpurpose.Some LCDdisplayshave built-in backlight (blueorgreen

    LEDs). Whenusedduringoperation,acurrentlimitingresistorshould beserially connectedtooneofthe

    pinsforbacklightpowersupply (similarto LEDs).

  • 8/7/2019 Key Board Interfacing

    19/99

    Iftherearenocharactersdisplayedorifallofthemaredimmedwhenthedisplay ison,thefirstthingthat

    should bedoneistocheck thepotentiometerforcontrastregulation.Isitproperly adjusted? Thesame

    appliesifthemodeofoperationhas beenchanged (writinginoneortwolines).

    LCD Memory

    The LCD display contains three memory blocks:

    y DDRAM Display DataRAM;

    y CGRAM CharacterGeneratorRAM; and

    y CGROM CharacterGeneratorROM.

    DDRAM Memory

    DDRAM memory isusedforstoringcharactersto bedisplayed. Thesizeofthismemory issufficientfor

    storing80characters.Somememory locationsaredirectly connectedtothecharactersondisplay.

  • 8/7/2019 Key Board Interfacing

    20/99

  • 8/7/2019 Key Board Interfacing

    21/99

  • 8/7/2019 Key Board Interfacing

    22/99

    TheaddressesofCGROM memory locationsmatchthecharactersofASCII.Iftheprogram being

    currently executedencountersacommand sendcharacterP toport,thenthe binary value0101 0000

    appearsontheport. Thisvalueisthe ASCIIequivalenttothecharacterP.Itisthenwrittento LCD,which

    resultsindisplayingthesymbolfrom0101 0000locationofCGROM.Inotherwords,thecharacterPis

    displayed. Thisappliestoalllettersofalphabet (capitalsandsmall), butnottonumbers.

    Asseenontheprevious map,addressesofalldigitsarepushedforward by 48relativetotheirvalues

    (digit0addressis48,digit 1 addressis49,digit 2 addressis 50etc.). Accordingly,inordertodisplay

    digitscorrectly,eachofthemneedsto beaddedadecimalnumber48priorto besentto LCD.

    Fromtheirinceptiontilltoday,computerscanrecognizeonly numbers, butnotletters.Itmeansthatall

    dataacomputerswapswithaperipheraldevicehasa binary format,eventhoughthesameisrecognized

    by themanasletters (keyboardisanexcellentexample).Every charactermatchestheunique

    combinationofzeroesandones. ASCIIischaracterencoding basedontheEnglishalphabet. ASCIIcode

    specifiescorrespondancebetweenstandardcharactersymbolsandtheirnumericalequivalents.

    CGRAM memory

    Apartfromstandardcharacters,the LCDdisplay canalsodisplay symbolsdefined by theuseritself.It

    can beany symbolinthesizeof5x8pixels.RAM memory calledCGRAM inthesizeof64 bytesenables

    it.

    Memory registersare8 bitswide, butonly 5 lowerbitsareused. Logicone (1)inevery registerrepresents

    adimmeddot,while8locationsgroupedtogetherrepresentonecharacter.Itis bestillustratedinfigure

    below:

  • 8/7/2019 Key Board Interfacing

    23/99

  • 8/7/2019 Key Board Interfacing

    24/99

    Symbolsareusually definedatthe beginnigoftheprogram by simply writingzerosandonestoregisters

    ofCGRAM memory sothatthey formdesiredshapes.Inordertodisplay themitissufficienttospecify

    theiraddress. Pay attentiontothefirstcoloumnintheCGROM mapofcharacters.Itdoesn'tcontainRAM

    memory addresses, butsymbols beingdiscussedhere.Inthisexample, display 0means-display ,

    display 1means-display etc.

    /&'%DVLF&RPPDQGV

    Alldatatransferredto LCDthroughtheoutputsD0-D7 will beinterpretedasacommandoradata,which

    dependsonthepinRSlogicstate:

    RS = 1-BitsD0-D7 areaddressesofthecharactersto bedisplayed. LCDprocessoraddressesone

    characterfromthecharactermapanddisplaysit. TheDDRAM addressspecifiesthelocationonwhich

    thecharacteristo bedisplayed. Thisaddressisdefined beforethecharacteristransferredortheaddress

    ofpreviously transferredcharacterisautomatically incremented.

    RS = 0-BitsD0-D7 arecommandswhichdeterminethedisplay mode. Thecommandsrecognized by

    the LCDaregiveninthetable below:

    COM M AND R S R W D7 D 6 D5 D4 D3 D 2 D 1 D 0 EXEC U T

    Clear display 0 0 0 0 0 0 0 0 0 1 1.6

    Cursor home 0 0 0 0 0 0 0 0 1 x 1.6

    Entry mode set 0 0 0 0 0 0 0 1 I/D S 40

    Display on/off control 0 0 0 0 0 0 1 D U B 40

    Cursor/Display Shift 0 0 0 0 0 1 D/C R/L x x 40

    Function set 0 0 0 0 1 DL N F x x 40

    Set CGRAM address 0 0 0 1 CGRAM address 40

    Set DDRAM address 0 0 1 DDRAM address 40

    Read BUSY flag (BF) 0 1 BF DDRAM address

    Write to CGRAM or DDRAM 1 0 D7 D6 D5 D4 D3 D2 D1 D0 40

    Read from CGRAM or DDRAM 1 1 D7 D6 D5 D4 D3 D2 D1 D0 40

    I/D 1 = Increment (by 1) R/L 1 = Shift right

    0 = Decrement (by 1) 0 = Shift left

    S 1 = Display shift on DL 1 = 8-bit interface

    0 = Display shift off 0 = 4-bit interface

    D 1 = Display on N 1 = Display in two lines

    0 = Display off 0 = Display in one line

  • 8/7/2019 Key Board Interfacing

    25/99

    U 1 = Cursor on F 1 = Character format 5x10 dots

    0 = Cursor off 0 = Character format 5x7 dots

    B 1 = Cursor blink on D/C 1 = Display shift0 = Cursor blink off 0 = Cursor shift

    What is the Busy flag?

    Comparedtothemicrocontroller,the LCDisanextremely slowcomponent.Becauseofthis,itwas

    necessary toprovideasignalwhichwill,uponcommandexecution,indicatethatthedisplay isready to

    receiveanewdata. Thatsignal,calledthe busy flag,can bereadfromlineD7. WhentheBF bitiscleared

    (BF=0),thedisplay isready toreceiveanewdata.

    LCD Connection

    Dependingonhowmany linesareusedforconnectingthe LCDtothemicrocontroller,thereare8-bitand

    4-bit LCDmodes. Theappropriatemodeisselectedatthe beginningoftheoperation. Thisprocessis

    called initialization.8-bit LCDmodeusesoutputsD0-D7 totransferdataintheway explainedonthe

    previouspage. Themainpurposeof4-bit LEDmodeistosavevaluableI/O pinsofthemicrocontroller.

    Only 4higherbits (D4-D7)areusedforcommunication,whileothermay beleftunconnected.Eachdata

    issenttothe LCDintwosteps:fourhigherbitsaresentfirst (normally throughthelinesD4-D7),thenfour

    lowerbits.Initializationenablesthe LCDtolink andinterpretreceived bitscorrectly.Dataisrarely read

    fromthe LCD (itismainly transferredfromthemicrocontrollerto LCD)sothatitisoftenpossibletosave

    anextraI/O pin by simpleconnectingR/W pintoground.Suchsavinghasitsprice. Messageswill be

    normally displayed, butitwillnot bepossibletoreadthe busy flagsinceitisnotpossibletoreadthe

    display either.

  • 8/7/2019 Key Board Interfacing

    26/99

    Fortunately,thereisasimplesolution. Aftersendingacharacteroracommanditisimportanttogivethe

    LCDenoughtimetodoits job. Owingtothefactthatexecutionoftheslowestcommandlastsfor

    approximately 1.64mS,itwill besufficienttowaitapproximately 2mSforLCD.

    LCD Initialization

    The LCDisautomatically clearedwhenpoweredup.Itlastsforapproximately 15mS. Afterthat,the

    display isready foroperation. Themodeofoperationisset by default.Itmeansthat:

    1. Display iscleared

    2. Mode

    o DL= 1 Communicationthrough8-bitinterface

    o N=0 Messagesaredisplayedinoneline

    o F=0Characterfont 5 x8dots

  • 8/7/2019 Key Board Interfacing

    27/99

    3. Display/Cursoron/off

    o D=0Display off

    o U=0Cursoroff

    o B=0Cursor blink off

    4. Characterentry

    o ID= 1 Displayedaddressesareautomatically incremented by 1

    o S=0Display shiftoff

    Automaticresetisinmostcasesperformedwithoutany problems.Inmostcases, butnotalways!Iffor

    any reasonthepowersupply voltagedoesnotreachfulvaluewithin 10mS,thedisplay willstartto

    performcompletely unpredictably.Ifthevoltagesupply unitisnotabletomeetthisconditionorifitis

    neededtoprovidecompletely safeoperation,theprocessofinitializationisapplied.Initialization,among

    otherthings,causesanewresetenablingdisplay tooperatenormally.

    Refertothefigure belowfortheprocedureon8-bitinitialization:

  • 8/7/2019 Key Board Interfacing

    28/99

  • 8/7/2019 Key Board Interfacing

    29/99

  • 8/7/2019 Key Board Interfacing

    30/99

    6.3Examples

    Theschematic belowisusedintheseveralfollowingexamples:

    Apartfromcomponentsnecessary fortheoperationofthemicrocontrollersuchasoscillatorwith

    capacitorsandthesimplestresetcircuit,therearealsoseveral LEDsandonepush button. Theseare

    usedtoindicatetheoperationoftheprogram.

    All LEDsarepolarizedinsuchaway thatthey areactivated by drivingamicrocontrollerpinlow (logic0).

    LED Blinking

  • 8/7/2019 Key Board Interfacing

    31/99

    ThepurposeofthisexampleisnottodemonstratetheoperationofLEDs, buttheoperatingspeedofthe

    microcontroller.Simply put,inordertoenable LED blinkingto bevisible,itisnecessary toprovide

    sufficientamountoftimetopass betweenon/offstatesofLEDs.Inthisexampletimedelay isprovided by

    executingasubroutinecalledDelay.Itisatripleloopinwhichtheprogramremainsforapproximately 0.5

    secondsanddecrementsvaluesstoredinregistersR0,R1 orR2. Afterreturningfromthesubroutine,the

    pinstateisinvertedandthesameprocedureisrepeated...

    ;************************************************************************

    ;* PROGRAM NAME : Delay.ASM

    ;* DESCRIPTION: Program turns on/off LED on the pin P1.0

    ;* Software delay is used (Delay).

    ;************************************************************************

    ;BASIC DIRECTIVES

    $MOD53

    $TITLE(DELAY.ASM)

    $PAGEWIDTH(132)

    $DEBUG

    $OBJECT

    $NOPAGING

    ;STACK

    DSEG AT 03FH

    STACK_START: DS 040H

  • 8/7/2019 Key Board Interfacing

    32/99

    ;RESET VECTORS

    CSEG AT 0

    JMP XRESET ;Reset vector

    ORG 100H

    XRESET: MOV SP,#STACK_START ;Define Stack pointer

    MOV P1,#0FFh ;All pins are configured as inputs

    LOOP:

    CPL P1.0 ;Pin P1.0 state is inverted

    LCALL Delay ;Time delay

    SJMP LOOP

    Delay:

    MOV R2,#20 ;500 ms time delay

    F02: MOV R1,#50 ;25 ms

    F01: MOV R0,#230

    DJNZ R0,$

  • 8/7/2019 Key Board Interfacing

    33/99

    DJNZ R1,F01

    DJNZ R2,F02

    END ;End of program

    Using Watch-dog Timer

    Thisexampledescribeshowthewatch-dogtimershouldnotoperate. Thewatch-dogtimerisproperly

    adjusted (nominaltimeforcountingis 1024mS), butinstructionusedtoresetitisintentionally leftoutso

    thatthistimeralways "wins". Asaresult,themicrocontrollerisreset (stateinregistersremains

    unchanged),programstartsexecutionfromthe beginningandthenumberinregisterR3isincremented

    by 1 andthencopiedtoport P1.

    LEDsdisplay thisnumberin binary format...

    ;************************************************************************

    ;* PROGRAM NAME : WatchDog.ASM

    ;* DESCRIPTION : After watch-dog reset, program increments number in

    ;* register R3 and shows it on port P1 in binary format.

    ;************************************************************************

    ;BASIC DIRECTIVES

    $MOD53

    $TITLE(WATCHDOG.ASM)

    $PAGEWIDTH(132)

  • 8/7/2019 Key Board Interfacing

    34/99

  • 8/7/2019 Key Board Interfacing

    35/99

  • 8/7/2019 Key Board Interfacing

    36/99

    $DEBUG

    $OBJECT

    $NOPAGING

    ;DECLARATION OF VARIABLES

    ;STACK

    DSEG AT 03FH

    STACK_START: DS 040H

    ;RESET VECTORS

    CSEG AT 0

    JMP XRESET ; Reset vector

    ORG 00BH

    JMP TIM0_ISR ; Timer T0 reset vector

    ORG 100H

  • 8/7/2019 Key Board Interfacing

    37/99

  • 8/7/2019 Key Board Interfacing

    38/99

    Anotherinterruptisgeneratedupon TimerT1 reset.Routine TIM1_ISRinwhichthe bitstateDIRECTION

    invertsisexecuted.Sincethis bitdeterminesdirectionofbitrotationthenthemovingdirectionofLEDis

    alsochanged.

    Ifyoupressapush button T1 atsomepoint,alogiczero (0)onthe P3.2 outputwilldisable TimerT1.

    ;************************************************************************

    ;* PROGRAM NAME : Split.ASM

    ;* DESCRIPTION: Timer TL0 rotates bit on port P1, while TL1 determines

    ;* the rotation direction. Both timers operate in mode

    ;* 3. Logic zero (0) on output P3.2 disables rotation on port P1.

    ;************************************************************************

    ;BASIC DIRECTIVES

    $MOD53

    $TITLE(SPLIT.ASM)

    $PAGEWIDTH(132)

    $DEBUG

    $OBJECT

    $NOPAGING

    ;DECLARATION OF VARIABLES

  • 8/7/2019 Key Board Interfacing

    39/99

  • 8/7/2019 Key Board Interfacing

    40/99

    ORG 01BH

    JMP TIM1_ISR ; Timer T1 reset vector

    ORG 100H

    XRESET: MOV SP,#STACK_START ; Define Stack pointer

    MOV TMOD,#00001011B ; Define MOD3

    MOV A,#0FFH

    MOV P1,#0FFH

    MOV R0,#30D

    SETB TR0 ; TL0 is turned on

    SETB TR1 ; TL1 is turned on

    MOV IE,#08AH ; Interrupt enabled

    CLR C

    CLR DIRECTION ; Rotate to the right

    LOOP1: SJMP LOOP1 ; Remain here

    TIM0_ISR:

    DJNZ R0,LAB3 ; Slow down rotation by 256 times

    JB DIRECTION,LAB1

  • 8/7/2019 Key Board Interfacing

    41/99

    RRC A ; Rotate contents of Accumulator

    to the right through

    ; Carry flag

    SJMP LAB2

    LAB1: RLC A ; Rotate contents of Accumulator

    to the left through

    ; Carry flag

    LAB2: MOV P1,A ; Contents of Accumulator is moved

    to port P1

    LAB3: RETI ; Return from interrupt

    TIM1_ISR:

    DJNZ R1,LAB4 ; Slow down direction of rotationby 256 times

    DJNZ R2,LAB4 ; When time expires, change

    rotation direction

    CPL SMER

    MOV R2,#30D

    LAB4: RETI

    END ; End of program

  • 8/7/2019 Key Board Interfacing

    42/99

    Simultaneous use of timers T0 and T1

    Thisprogramcan beconsideredascontinuationofthepreviousone. They sharethesameidea, butin

    thiscasetruetimers T0and T1 areused.Inordertodemonstratetheoperationofbothtimersonthe

    sameportatthesametime,timerT0resetisusedtoshiftlogiczero (0)ontheport,while TimerT1 reset

    isusedtochangerotationdirection. ThisprogramspendsmostofitstimeintheloopLOOP1waitingfor

    aninterruptto becaused by reset.By checkingtheDIRECTION bit,informationonrotationdirectionof

    both bitsinaccumulatoraswellasofmovingport LEDisobtained.

    ;************************************************************************

    ;* PROGRAM NAME : Tim0Tim1.ASM

    ;* DESCRIPTION: Timer TO rotates bit on port P1 while Timer1

    ;* changes rotation direction. Both timers are configured to operate in mode

    1.

    ;************************************************************************

    ;BASIC DIRECTIVES

    $MOD53

    $TITLE(TIM0TIM1.ASM)

    $PAGEWIDTH(132)

    $DEBUG

    $OBJECT

    $NOPAGING

  • 8/7/2019 Key Board Interfacing

    43/99

  • 8/7/2019 Key Board Interfacing

    44/99

    ORG 01BH ; Timer 1 Reset vector

    JMP TIM1_ISR

    ORG 100H

    XRESET: MOV SP,#STACK_START ; Define Stack pointer

    MOV TMOD,#11H ; Select MOD1 for both timers

    MOV A,#0FFH

    MOV P1,#0FFH

    MOV R0,#30D ; R0 is initialized

    SETB TR0 ; TIMER0 is turned on

    SETB TR1 ; TIMER1 is turned on

    MOV IE,#08AH ; Timer0 and Timer1 Interrupt

    enabled

    CLR C

    CLR DIRECTION ; Rotate to the right

    LOOP1: SJMP LOOP1 ; Remain here

  • 8/7/2019 Key Board Interfacing

    45/99

    TIM0_ISR:

    JB DIRECTION,LAB1

    RRC A ; Rotate contents of accumulator

    to the right through

    ; Carry flag

    SJMP LAB2

    LAB1: RLC A ; Rotate contents of Accumulator

    to the left through

    ; Carry flag

    LAB2: MOV P1,A ; Contents of Accumulator is moved

    to port P1

    RETI ; Return from interrupt

    TIM1_ISR:

    DJNZ R0,LAB3 ; When time expires, change

    rotation direction

    CPL DIRECTION

    MOV R0,#30D ; Initialize R0

    LAB3:

    RETI

    END ; End of program

    Using Timer T2

  • 8/7/2019 Key Board Interfacing

    46/99

    ThisexampledescribestheuseofTimerT2 configuredtooperateinAuto-Reloadmode.Inthisvery

    case, LEDsareconnectedtoport P3whilethepush buttonusedforforcedtimerreset (T2EX)is

    connectedtothe P1.1 pin.

    Programexecutionissimilartothepreviousexamples. Whentimerendscounting,aninterruptisenabled

    andsubroutineTIM2_ISRisexecuted,thusrotatingalogiczero (0)inaccumulatorandmovingthe

    contentsofaccumulatortothe P3pin. Atlast,flagswhichcausedaninterruptareclearedandprogram

    returnstotheloop LOOP1 whereitremainsuntilanewinterruptrequestarrives...

    Ifpush button T2EXispressed,timeristemporarily reset. Thispush buttonresetstimer,whilepush

    buttonRESET resetsthemicrocontroller.

    ;************************************************************************

    ;* PROGRAM NAME : Timer2.ASM

    ;* DESCRIPTION: Program rotates log. "0" on port P3. Timer2 determines

    ;* the speed of rotation and operates in auto-reload mode

  • 8/7/2019 Key Board Interfacing

    47/99

  • 8/7/2019 Key Board Interfacing

    48/99

  • 8/7/2019 Key Board Interfacing

    49/99

    TIM2_ISR: RRC A ; Rotate contents of Accumulator

    to the right through

    ; Carry flag

    MOV P3,A ; Move the contents of Accumulator

    A to PORT3

    CLR TF2 ; Clear timer T2 flag TF2

    CLR EXF2 ; Clear timer T2 flag EXF2

    RETI ; Return from interrupt

    END ; End of program

    Using External Interrupt

    Hereisanotherexampleofinterruptexecution. Anexternaliterruptisgeneratedwhenalogiczero (0)is

    presentonpin P3.2 orP3.3.Dependingonwhichinputisactive,oneoftworoutineswill beexecuted:

    A logiczero (0)onthe P3.2 pininitiatesexecutionofinterruptroutineIsr_Int0,thusincrementingnumber

    inregisterR0andcopyingittoport P0. Logiczeroonthe P3.3pininitiatesexecutionofsubroutine

    Isr_Int1,numberinregisterR1 isincremented by 1 andthencopiedtoport P1.

    Inshort,eachpressonpush buttonsINT0andINT1 will becountedandimmediately shownin binary

    formatonappropriateport (LEDwhichemittslightrepresentsalogiczero (0)).

  • 8/7/2019 Key Board Interfacing

    50/99

    ;************************************************************************

    ;* PROGRAM NAME : Int.ASM

    ;* DESCRIPTION : Program counts interrupts INT0 generated by appearance of

    high-to-low

    ;* transition signal on pin P3.2 Result appears on port P0. Interrupts INT1

    are also

    ;* counted up at the same time. They are generated byappearing high-to-low

    transition

    ;* signal on pin P3. The result appears on port P1.

  • 8/7/2019 Key Board Interfacing

    51/99

  • 8/7/2019 Key Board Interfacing

    52/99

    ORG 100H

    XRESET:

    MOV TCON,#00000101B ; Interrupt INT0 is generated by

    appearing

    ; high-to-low transition signal on pin

    P3.2

    ; Interrupt INT0 is generated by

    appearing

    ; high-to-low transition signal on pin

    P3.3

    MOV IE,#10000101B ; Interrupt enabled

    MOV R0,#00H ; Counter starting value

    MOV R1,#00H

    MOV P0,#00H ; Reset port P0

    MOV P1,#00H ; Reset port P1

    LOOP: SJMP LOOP ; Remain here

    Isr_Int0:

    INC R0 ; Increment value of interrupt INT0

    counter

    MOV P0,R0

  • 8/7/2019 Key Board Interfacing

    53/99

    RETI

    Isr_Int1:

    INC R1 ; Increment value of interrupt INT1

    counter

    MOV P1,R1

    RETI

    END ; End of program

    Using LED display

    ThefollowingexamplesdescribetheuseofLEDdisplays.Commonchatodedisplaysareusedhere,

    whichmeansthatall built-in LEDsarepolarizedinsuchaway thattheiranodesareconnectedtothe

    microcontrollerpins.Sincethecommonway ofthinkingisthatlogicone (1)turnssomethingonandlogic

    zero (0)turnssomethingof, LowCurrentdisplays (lowpowerconsumption)andtheirdiodes (segments)

    areconnectedserially toresistorsofrelatively highresistance.

    InordertosaveI/O pins,fourLEDdisplaysareconnectedtooperateinmultiplexmode.Itmeansthatall

    segmentshavingthesamenameareconnectedtooneoutputporteachandonly onedisplay isactiveat

    atime.

    Tranzistorsandsegmenatsondisplaysarequickly activated,thusmakingimpressionthatalldigitsare

    activesimultaneously.

  • 8/7/2019 Key Board Interfacing

    54/99

  • 8/7/2019 Key Board Interfacing

    55/99

    determinedcombinationofzeroesandonesappearsoneachofthesenewlocations (digit 1 mask,digit 2

    mask...digit 9 mask). Whenthiscombinationistransferredtotheport,thedisplay showsdesireddigit.

    ;************************************************************************

    ;* PROGRAM NAME : 7Seg1.ASM

    ;* DESCRIPTION: Program displays number "3" on 7-segment LED display

    ;************************************************************************

    ;BASIC DIRECTIVES

    $MOD53

    $TITLE(7SEG1.ASM)

    $PAGEWIDTH(132)

    $DEBUG

    $OBJECT

    $NOPAGING

    ;STACK

    DSEG AT 03FH

    STACK_START: DS 040H

  • 8/7/2019 Key Board Interfacing

    56/99

  • 8/7/2019 Key Board Interfacing

    57/99

    DB 3FH ; Digit 0 mask

    DB 06H ; Digit 1 mask

    DB 5BH ; Digit 2 mask

    DB 4FH ; Digit 3 mask

    DB 66H ; Digit 4 mask

    DB 6DH ; Digit 5 mask

    DB 7DH ; Digit 6 mask

    DB 07H ; Digit 7 mask

    DB 7FH ; Digit 8 mask

    DB 6FH ; Digit 9 mask

    END ; End of program

    Writing and changing digits on LED display

    Thisprogramisonly anextendedversonofthepreviousone. Thereisonly onedigitactive-thefirstone

    ontheright,andthereisnouseofmultiplexing. Unlikethepreviousexample,alldecimalnumbersare

    displayed (0-9).Inordertoenabledigitstochangeatreasonablepace,asoubroutine L2 whichcausesa

    shorttimedelay isexecutedpriortoeachchangeoccurs.Basically,thewholeprocessisvery simpleand

    takesplaceinthemainloopcalled LOOP whichlooksasfollows:

    1. R3iscopiedto AccumulatorandsubroutineformaskingdigitsDispisexecuted;

    2. Accumulatoriscopiedtotheportanddisplayed;

    3. ThecontentsoftheR3registerisincremented;

    4. Itischeckedwhether 10cyclesarecountedornot.Ifitis,registerR3isresetinorderto

    enablecountingtostartfrom0; and

    5. Instructionlabeledas L2 withinsubroutineisexecuted.

    ;************************************************************************

  • 8/7/2019 Key Board Interfacing

    58/99

    ;* PROGRAM NAME: 7Seg2.ASM

    ;* DESCRIPTION: Program writes numbers 0-9 on 7-segment LED display

    ;************************************************************************

    ;BASIC DIRECTIVES

    $MOD53

    $TITLE(7SEG2.ASM)

    $PAGEWIDTH(132)

    $DEBUG

    $OBJECT

    $NOPAGING

    ;STACK

    DSEG AT 03FH

    STACK_START: DS 040H

    ;RESET VECTORS

    CSEG AT 0

    JMP XRESET ; Reset vector

  • 8/7/2019 Key Board Interfacing

    59/99

    ORG 100H

    XRESET: MOV SP,#STACK_START ; Define Stack pointer

    MOV R3,#0 ; Counter initial value

    MOV P1,#0 ; Turn off all display segments

    MOV P3,#20h ; Activate display D4

    LOOP:

    MOV A,R3

    LCALL Disp ; Perform appropriate masking for

    number in

    ; Accumulator

    MOV P1,A

    INC R3 ; Increment number in register by

    1

    CJNE R3,#10,L2 ; Check whether the number 10 is

    in R3

    MOV R3,#0 ; If it is, reset counter

    L2:

    MOV R2,#20 ; 500 mS time delay

    F02: MOV R1,#50 ; 25 mS

  • 8/7/2019 Key Board Interfacing

    60/99

  • 8/7/2019 Key Board Interfacing

    61/99

    END ; End of program

    Writing two-digit number on LED display

    Itistimefortimemultiplexing! Thisisthesimplestexamplewhichdisplaysthenumber23ontwodisplays

    insuchaway thatoneofthemdisplaysunits,whiletheotherdisplaystens. Themostimportantthingin

    theprogramistimesynchronization. Otherwise,everythingisvery simple. TransistorT4enablesdisplay

    D4andatthesametimea bitcombinationcorrespondingtothedigit3issetontheport. Afterthat,

    transistorT4isdisabledandthewholeprocessisrepeatedusingtransistorT3anddisplay D3inorderto

    display digit 2. Thisproceduremust becontinuosly repeatedinordertomakeimpressionthat both

    displaysareactiveatthesametime.

    ;************************************************************************

    ;* PROGRAM NAME: 7Seg3.ASM

    ;* DESCRIPTION: Program displays number "23" on 7-segment LED display

    ;************************************************************************

    ;BASIC DIRECTIVES

    $MOD53

    $TITLE(7SEG3.ASM)

    $PAGEWIDTH(132)

    $DEBUG

    $OBJECT

  • 8/7/2019 Key Board Interfacing

    62/99

  • 8/7/2019 Key Board Interfacing

    63/99

    MOV A,#02 ; Write digit 2 on display D3

    LCALL Disp ; Find mask for that digit

    MOV P1,A ; Put the mask on the port

    SJMP LOOP ; Return to the label LOOP

    Disp: ; Subroutine for writing digits

    INC A

    MOVC A,@A+PC

    RET

    DB 3FH ; Digit 0 mask

    DB 06H ; Digit 1 mask

    DB 5BH ; Digit 2 mask

    DB 4FH ; Digit 3 mask

    DB 66H ; Digit 4 mask

    DB 6DH ; Digit 5 mask

    DB 7DH ; Digit 6 mask

    DB 07H ; Digit 7 mask

    DB 7FH ; Digit 8 mask

    DB 6FH ; Digit 9 mask

  • 8/7/2019 Key Board Interfacing

    64/99

    END ; End of program

    Using four digit LED display

    Inthisexampleallfourdisplays,insteadoftwo,areactivesothatitispossibletowritenumbersfrom0to

    9999. Here,thenumber1 234isdisplayed. Afterinitialization,theprogramremainsintheloop LOOP

    wheredigitalmultiplexingisperformed. ThesubroutineDispisusedtoconvert binary numbersinto

    correspondingcombinationsofbitsforthepurposeofactivatingdisplay lightingsegments.

    ;************************************************************************

    ;* PROGRAM NAME : 7Seg5.ASM

    ;* DESCRIPTION : Program displays number"1234" on 7-segment LED display

    ;************************************************************************

    ;BASIC DIRECTIVES

    $MOD53

    $TITLE(7SEG5.ASM)

    $PAGEWIDTH(132)

    $DEBUG

    $OBJECT

    $NOPAGING

    ;STACK

  • 8/7/2019 Key Board Interfacing

    65/99

    DSEG AT 03FH

    STACK_START: DS 040H

    ;RESET VECTORS

    CSEG AT 0

    JMP XRESET ; Reset vector

    ORG 100H

    XRESET: MOV SP,#STACK_START ; Define Stack pointer

    LOOP: MOV P1,#0 ; Turn off all display segments

    MOV P3,#20h ; Activate display D4

    MOV A,#04 ; Write digit 4 on display D4

    LCALL Disp ; Find mask for that digit

    MOV P1,A ; Put the mask on the port

    MOV P1,#0 ; Turn off all display segments

    MOV P3,#10h ; Activate display D3

    MOV A,#03 ; Write digit 3 on display D3

    LCALL Disp ; Find mask for that digit

  • 8/7/2019 Key Board Interfacing

    66/99

    MOV P1,A ; Put the mask on the port

    MOV P1,#0 ; Turn off all display segments

    MOV P3,#08h ; Activate display D2

    MOV A,#02 ; Write digit 2 on display D2

    LCALL Disp ; Find mask for that digit

    MOV P1,A ; Put the mask on the port

    MOV P1,#0 ; Turn off all display segments

    MOV P3,#04h ; Activate display D1

    MOV A,#01 ; Write digit 1 on display D1

    LCALL Disp ; Find mask for that digit

    MOV P1,A ; Put the mask on the port

    SJMP LOOP ; Return to the lable LOOP

    Disp: ; Subroutine for writing digits

    INC A

    MOVC A,@A+PC

    RET

    DB 3FH ; Digit 0 mask

    DB 06H ; Digit 1 mask

    DB 5BH ; Digit 2 mask

  • 8/7/2019 Key Board Interfacing

    67/99

  • 8/7/2019 Key Board Interfacing

    68/99

  • 8/7/2019 Key Board Interfacing

    69/99

  • 8/7/2019 Key Board Interfacing

    70/99

    LCALL Disp ; Call mask for that digit

    MOV P1,A ; Write units on display D4

    LCALL Delay ; 25ms delay

    MOV P1,#0 ; Turn off all display segments

    MOV P3,#10h ; Activate display D3

    MOV A,R3 ; Copy Register contaning tens

    to A

    LCALL Disp ; Call mask for that digit

    MOV P1,A ; Write tens on display D3

    LCALL Delay ; 25ms delay

    SJMP LOOP

    Delay:

    MOV R1,#50 ; 5 ms delay

    F01: MOV R0,#250

    DJNZ R0,$

    DJNZ R1,F01

    RET

    Disp: ; Subroutine for displaying

    digits

  • 8/7/2019 Key Board Interfacing

    71/99

    INC A

    MOVC A,@A+PC

    RET

    DB 3FH ; Digit 0 mask

    DB 06H ; Digit 1 mask

    DB 5BH ; Digit 2 mask

    DB 4FH ; Digit 3 mask

    DB 66H ; Digit 4 mask

    DB 6DH ; Digit 5 mask

    DB 7DH ; Digit 6 mask

    DB 07H ; Digit 7 mask

    DB 7FH ; Digit 8 mask

    DB 6FH ; Digit 9 mask

    END ; End of program

    Handling EEPROM

    Thisprogramwritesdatatoon-chipEE

    PROM memory.Inthiscase,thedataisahexadecimalnumber23

    whichisto bewrittentothelocationwithaddress00.

    Tomakesurethatthisnumberiscorrectly written,thesamelocationofEEPROM isread 10mSlaterin

    ordertocomparethesetwonumbers.Ifthey match,Fwill bedisplayed. Otherwise,Ewill bedisplayedon

    the LEDdisplay (Error).

  • 8/7/2019 Key Board Interfacing

    72/99

  • 8/7/2019 Key Board Interfacing

    73/99

    THE END EQU 071H ; Display "F"

    ERROR EQU 033H ; Display "E"

    ;STACK

    DSEG AT 03FH

    STACK_START: DS 040H

    ;RESET VECTORS

    CSEG AT 0

    JMP XRESET ; Reset vector

    ORG 100H

    XRESET: MOV IE,#00 ; All interrupts are disabled

    MOV SP,#STACK_START

    MOV DPTR,#0000H ; Choose location address in

    EEPROM

    ORL WMCON,#EEMEN ; Access to EEPROM is enabled

    ORL WMCON,#EEMWE ; Write to EEPROM is enabled

  • 8/7/2019 Key Board Interfacing

    74/99

    MOV TEMP,#23H ; Number written to EEPROM is

    moved to

    MOV A,TEMP ; register TEMP and Accumulator

    MOVX @DPTR,A ; Write byte to EEPROM

    CALL DELAY ; 10ms delay

    MOVX A,@DPTR ; Read the same location and

    compare to TEMP,

    CJNE A,TEMP,ERROR ; If they don't match, jump to

    label ERROR

    MOV A,#KRAJ ; Display F (correct)

    MOV P1,A

    XRL WMCON,#EEMWE ; Write to EEPROM is disabled

    XRL WMCON,#EEMEN ; Access to EEPROM is disabled

    LOOP1: SJMP LOOP1 ; Remain here

    ERROR: MOV A,#ERROR ; Display E (error)

    MOV P1,A

    LOOP2: SJMP LOOP2

    DELAY: MOV A,#0AH ; Delay

    MOV R3,A

    LOOP3: NOP

  • 8/7/2019 Key Board Interfacing

    75/99

    LOOP4: DJNZ B,LOOP4

    LOOP5: DJNZ B,LOOP5

    DJNZ R3,LOOP3

    RET

    END ; End of program

    Data reception via UART

    Inordertoenablesuccessful UART serialcommunication,itisnecessary tomeetspecificrulesofthe

    RS232 standard.Itprimarily referstovoltagelevelsrequired by thisstandard. Accordingly,-10V stands

    forlogicone (1)inthemessage,while +10V standsforlogiczero (0). Themicrocontrollerconverts

    accurately dataintoserialformat, butitspowersupply voltageisonly 5V.Sinceitisnoteasy toconvert

    0V into 10V and 5V into-10V,thisoperationison bothtransmitandreceivesidelefttoaspecializedIC

    circuit. Here,the MAX232 by MAXIM isused becauseitiswidespread,cheapandreliable.

    Thisexampleshowshowtoreceivemessagesent by a PC. TimerT1 generates boudrate.Sincethe

    11.0592 MHzquartzcrystalisusedhere,itiseasy toobtainstandard baudratewhichamoutsto 9600

    bauds.Eachreceiveddataisimmediately transferredtoport P1 pins.

  • 8/7/2019 Key Board Interfacing

    76/99

    ;************************************************************************

    ;* PROGRAM NAME : UartR.ASM

    ;* DESCRIPTION: Each data received from PC via UART appears on the port

    ;* P1.

    ;*

    ;************************************************************************

    ;BASIC DIRECTIVES

  • 8/7/2019 Key Board Interfacing

    77/99

    $MOD53

    $TITLE(UARTR.ASM)

    $PAGEWIDTH(132)

    $DEBUG

    $OBJECT

    $NOPAGING

    ;STACK

    DSEG AT 03FH

    STACK_START: DS 040H

    ;RESET VECTORS

    CSEG AT 0

    JMP XRESET ; Reset vector

    ORG 023H ; Starting address of UART interrupt

    routine

    JMP IR_SER

    ORG 100H

  • 8/7/2019 Key Board Interfacing

    78/99

    XRESET: MOV IE,#00 ; All interrupts are disabled

    MOV SP,#STACK_START ; Initialization of Stack pointer

    MOV TMOD,#20H ; Timer1 in mode2

    MOV TH1,#0FDH ; 9600 baud rate at the frequency of

    ; 11.0592MHz

    MOV SCON,#50H ; Receiving enabled, 8-bit UART

    MOV IE,#10010000B ;UART interrupt enabled

    CLR TI ; Clear transmit flag

    CLR RI ; Clear receive flag

    SETB TR1 ; Start Timer1

    LOOP: SJMP LOOP ; Remain here

    IR_SER: JNB RI,OUTPUT ; If any data is received,

    ; move it to the port

    MOV A,SBUF ; P1

    MOV P1,A

    CLR RI ; Clear receive flag

    OUTPUT RETI

  • 8/7/2019 Key Board Interfacing

    79/99

    END ; End of program

    Data transmission via UART

    Thisprogramdescribeshowtouse UART totransmitdata. A sequenceofnumbers (0-255)istransmitted

    toa PCat 9600 baudrate. The MAX 232 isusedasavoltageregulator.

    ;************************************************************************

    ;* PROGRAM NAME : UartS.ASM

    ;* DESCRIPTION: Sends values 0-255 to PC.

    ;************************************************************************

    ;BASIC DIRECTIVES

    $MOD53

    $TITLE(UARTS.ASM)

    $PAGEWIDTH(132)

    $DEBUG

    $OBJECT

    $NOPAGING

    ;STACK

    DSEG AT 03FH

  • 8/7/2019 Key Board Interfacing

    80/99

    STACK_START: DS 040H

    ;RESET VECTORS

    CSEG AT 0

    JMP XRESET ; Reset vector

    ORG 100H

    XRESET: MOV IE,#00 ; All interrupts are disabled

    MOV SP,#STACK_START ; Initialization of Stack pointer

    MOV TMOD,#20H ; Timer1 in mode 2

    MOV TH1,#0FDH ; 9600 baud rate at the frequency of

    ; 11.0592MHz

    MOV SCON,#40H ; 8-bit UART

    CLR TI ; Clear transmit bit

    CLR RI ; Clear receive flag

    MOV R3,#00H ; Reset caunter

    SETB TR1 ; Start Timer 1

    START: MOV SBUF,R3 ; Move number from counter to a PC

  • 8/7/2019 Key Board Interfacing

    81/99

    LOOP1: JNB TI,LOOP1 ; Wait here until byte transmission is

    ; complete

    CLR TI ; Clear transmit bit

    INC R3 ; Increment the counter value by 1

    CJNE R3,#00H,START ; If 255 bytes are not sent return to

    the

    ; label START

    LOOP: SJMP LOOP ; Remain here

    END ; End of program

    Writing message on LCD display

    Thisexampleusesthemostfrequently usedtypeofLCDwhichdisplaystextintwolineswith 16

    characterseach.InordertosaveI/O ports,only 4pinsareusedforcommunicationhere.Inthisway each

    byteistransmittedintwosteps:firsthigherthenlowernible.

    LCDneedsto beinitializedatthe beginningoftheprogram.Besides,partsoftheprogramwhichrepeatin

    theprogramcreatespecialsubroutines. Allthismay seemextremely complicated, butthewholeprogram

    basically performsseveralsimpleoperationsanddisplaysMikroelektronika Razvojni sistemi .

  • 8/7/2019 Key Board Interfacing

    82/99

  • 8/7/2019 Key Board Interfacing

    83/99

    $MOD53

    $TITLE(LCD.ASM)

    $PAGEWIDTH(132)

    $DEBUG

    $OBJECT

    $NOPAGING

    ;Stack

    DSEG AT 0E0h

    Stack_Start: DS 020h

    Start_address EQU 0000h

    ;Reset vectors

    CSEG AT 0

    ORG Start_address

    JMP Inic

    ORG Start_address+100h

  • 8/7/2019 Key Board Interfacing

    84/99

    MOV IE,#00 ; All interrupts are disabled

    MOV SP,#Stack_Start

    Inic: CALL LCD_inic ; Initialize LCD

    ;*************************************************

    ;* MAIN PROGRAM

    ;*************************************************

    START: MOV A,#80h ; Next character will appear on

    the first

    CALL LCD_status ; location in the first line of

    LCD display.

    MOV A,#'M' ; Display character M.

    CALL LCD_putc ; Call subroutine for character

    transmission.

    MOV A,#'i' ; Display character i.

    CALL LCD_putc

    MOV A,#'k' ; Display character k.

    CALL LCD_putc

    MOV A,#'r' ; Display character r.

    CALL LCD_putc

  • 8/7/2019 Key Board Interfacing

    85/99

    MOV A,#'o' ; Display character o.

    CALL LCD_putc

    MOV A,#'e' ; Display character e.

    CALL LCD_putc

    MOV A,#'l' ; Display character l.

    CALL LCD_putc

    MOV A,#'e' ; Display character e.

    CALL LCD_putc

    MOV A,#'k' ; Display character k.

    CALL LCD_putc

    MOV A,#'t' ; Display character t.

    CALL LCD_putc

    MOV A,#'r' ; Display character r.

    CALL LCD_putc

    MOV A,#'o' ; Display character o.

    CALL LCD_putc

    MOV A,#'n' ; Display character n.

    CALL LCD_putc

    MOV A,#'i' ; Display character i.

    CALL LCD_putc

  • 8/7/2019 Key Board Interfacing

    86/99

    MOV A,#'k' ; Display character k.

    CALL LCD_putc

    MOV A,#'a' ; Display character a.

    CALL LCD_putc

    MOV A,#0c0h ; Next character will appear on

    the first

    CALL LCD_status ; location in the second line

    of LCD display.

    MOV A,#'R' ; Display character R.

    CALL LCD_putc ; Call subroutine for character

    transmission.

    MOV A,#'a' ; Display character a.

    CALL LCD_putc

    MOV A,#'z' ; Display character z.

    CALL LCD_putc

    MOV A,#'v' ; Display character v.

    CALL LCD_putc

    MOV A,#'o' ; Display character o.

    CALL LCD_putc

    MOV A,#'j' ; Display character j.

    CALL LCD_putc

  • 8/7/2019 Key Board Interfacing

    87/99

    MOV A,#'n' ; Display character n.

    CALL LCD_putc

    MOV A,#'i' ; Display character i.

    CALL LCD_putc

    MOV A,#' ' ; Display character .

    CALL LCD_putc

    MOV A,#'s' ; Display character s.

    CALL LCD_putc

    MOV A,#'i' ; Display character i.

    CALL LCD_putc

    MOV A,#'s' ; Display character s.

    CALL LCD_putc

    MOV A,#'t' ; Display character t.

    CALL LCD_putc

    MOV A,#'e' ; Display character e.

    CALL LCD_putc

    MOV A,#'m' ; Display character m.

    CALL LCD_putc

    MOV A,#'i' ; Display character i.

    CALL LCD_putc

  • 8/7/2019 Key Board Interfacing

    88/99

    MOV R0,#20d ; Wait time (20x10ms)

    CALL Delay_10ms ;

    MOV DPTR,#LCD_DB ; Clear display

    MOV A,#6d ;

    CALL LCD_inic_status ;

    MOV R0,#10d ; Wait time(10x10ms)

    CALL Delay_10ms

    JMP START

    ;*********************************************

    ;* Subroutine for wait time (T= r0 x 10ms)

    ;*********************************************

    Delay_10ms: MOV R5,00h ; 1+(1+(1+2*r7+2)*r6+2)*r5

    approximately

    MOV R6,#100d ; (if r7>10)

    MOV R7,#100d ; 2*r5*r6*r7

    DJNZ R7,$ ; $ indicates current

    instruction.

    DJNZ R6,$-4

  • 8/7/2019 Key Board Interfacing

    89/99

  • 8/7/2019 Key Board Interfacing

    90/99

    LCD_read_write BIT P1.1 ;Bit for activating pin RW on

    LCD.

    LCD_reg_select BIT P1.2 ;Bit for activating pin RS on

    LCD.

    LCD_port SET P1 ; Port for connection to LCD.

    Busy BIT P1.7 ; Port pin on which Busy flag

    appears.

    LCD_Start_I_red EQU 00h ; Address of the first message

    character

    ; in the first line of LCD

    display.

    LCD_Start_II_red EQU 40h ; Address of the first message

    character

    ; in the second line of LCD

    display.

    LCD_DB: DB 00111100b ; 0 -8b, 2/1 lines, 5x10/5x7

    format

    DB 00101100b ; 1 -4b, 2/1 lines, 5x10/5x7

    format

    DB 00011000b ; 2 -Display/cursor shift,right/left

    DB 00001100b ; 3 -Display ON, cursor OFF,

    cursor blink off

  • 8/7/2019 Key Board Interfacing

    91/99

    DB 00000110b ; 4 -Increment mode, display

    shift off

    DB 00000010b ; 5 -Display/cursor home

    DB 00000001b ; 6 -Clear display

    DB 00001000b ; 7 -Display OFF, cursor OFF,

    cursor blink off

    LCD_inic:

    ;*****************************************

    MOV DPTR,#LCD_DB

    MOV A,#00d ; Triple initialization in 8-

    bit

    CALL LCD_inic_status_8 ; mode is performed at the

    beginning

    MOV A,#00d ; (in case of slow increment of

    CALL LCD_inic_status_8 ; power supply when the power

    supply is on

    MOV A,#00d

    lcall LCD_inic_status_8

    MOV A,#1d ; Change from 8-bit into

  • 8/7/2019 Key Board Interfacing

    92/99

    CALL LCD_inic_status_8 ; 4-bit mode

    MOV A,#1d

    CALL LCD_inic_status

    MOV A,#3d ; As from this point the

    program executes in

    ;4-bit mode

    CALL LCD_inic_status

    MOV A,#6d

    CALL LCD_inic_status

    MOV A,#4d

    CALL LCD_inic_status

    RET

    LCD_inic_status_8:

    ;******************************************

    PUSH B

    MOVC A,@A+DPTR

  • 8/7/2019 Key Board Interfacing

    93/99

    CLR LCD_reg_select ; RS=0 - Write command

    CLR LCD_read_write ; R/W=0 - Write data on LCD

    MOV B,LCD_port ; Lower 4 bits from LCD port

    are memorized

    ORL B,#11110000b

    ORL A,#00001111b

    ANL A,B

    MOV LCD_port,A ; Data is moved from A to LCD

    port

    SETB LCD_enable ; high-to-low transition signal

    ; is generated on the LCD's EN

    pin

    CLR LCD_enable

    MOV B,#255d ; Time delay in case of

    improper reset

    DJNZ B,$ ; during initialization

    DJNZ B,$

    DJNZ B,$

  • 8/7/2019 Key Board Interfacing

    94/99

  • 8/7/2019 Key Board Interfacing

    95/99

    CLR LCD_reg_select ; RS=O: Command is sent to LCD

    CALL LCD_port_out

    SWAP A ; Nibles are swapped in

    accumulator

    DJNZ B,$

    DJNZ B,$

    DJNZ B,$

    CLR LCD_reg_select ; RS=0: Command is sent to LCD

    CALL LCD_port_out

    POP B

    RET

    ;***************************************************************************

    *

    ;* SUBROUTINE: LCD_putc

    ;* DESCRIPTION: Sending character to be displayed on LCD.

    ;***************************************************************************

    *

  • 8/7/2019 Key Board Interfacing

    96/99

    LCD_putc: PUSH B

    MOV B,#255d

    DJNZ B,$

    SETB LCD_reg_select ; RS=1: Character is sent to

    LCD

    CALL LCD_port_out

    SWAP A ; Nibles are swapped in

    accumulator

    DJNZ B,$

    SETB LCD_reg_select ; RS=1: Character is sent to

    LCD

    CALL LCD_port_out

    POP B

    RET

    ;***************************************************************************

    *

    ;* SUBROUTINE: LCD_port_out

    ;* DESCRIPTION: Sending commands or characters on LCD display

  • 8/7/2019 Key Board Interfacing

    97/99

    ;***************************************************************************

    *

    LCD_port_out: PUSH ACC

    PUSH B

    MOV B,LCD_port ; Lower 4 bits of LCD port are

    memorized

    ORL B,#11110000b

    ORL A,#00001111b

    ANL A,B

    MOV LCD_port,A ; Data is copied from A to LCD

    port

    SETB LCD_enable ; high-to-low transition signal

    ; is generated on the LCD's EN

    pin

    CLR LCD_enable

    POP B

    POP ACC

    RET

  • 8/7/2019 Key Board Interfacing

    98/99

    END ; End of program

    Binary to decimal number conversion

    Whenusing LEDand LCDdisplays,itisoftennecessary toconvertnumbersfrom binary todecimal.For

    example,ifsomeregistercontainsanumberin binary formatthatshould bedisplayedonathreedigit

    LEDdisplay itisfirstnecessary toconvertittodecimalformat.Inotherwords,itisnecessary todefine

    whatshould bedisplayedonthemostrightdisplay (units),middledisplay (tens)andmostleftdisplay

    (hundreds).

    Thesubroutine belowperformsconversionofone byte.Binary numberisstoredintheaccumulator,while

    digitsofthatnumberindecimalformatarestoredinregistersR3,R2 andaccumulator(units,tensand

    hundreds,respectively).

    ;************************************************************************

    ;* SUBROUTINE NAME : BinDec.ASM

    ;* DESCRIPTION : Content of accumulator is converted into three decimal

    digits

    ;************************************************************************

    BINDEC: MOV B,#10d ; Store decimal number 10 in B

    DIV AB ; A:B. Remainder remains in B

    MOV R3,B ; Move units to register R3

    MOV B,#10d ; Store decimal number 10 in B

    DIV AB ; A:B. Remainder remains in B

    MOV R2,B ; Move tens to register R2

  • 8/7/2019 Key Board Interfacing

    99/99

    MOV B,#10d ; Store decimal number 10 in B

    DIV AB ; A:B. Remainder remains in B

    MOV A,B ; Move hundreds to accumulator

    RET ; Return to the main program