EELE4315 LectureNotes

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

The Islamic University of Gaza Electrical Engineering Department 2009-2010 Fall semester

Course title & Code Instructor Microcontroller Systems Design (EELE 4315) Prof. Dr. Muhammed ABDELATI Tel 2871 E-mail [email protected] Eng. Tarik Abuisha This course is dedicated to 4th year electrical engineering students who completed successfully the Computer Programming and Logic Design courses. Sunday 11:00-12:00 () Tuesday 11:00-12:00 () These office hours are tentative. Official ones are used to be announced on my office door. The course provides a thorough description of the design and implementation of microcontrollers and microprocessors systems. J. Sanchez and M. Canton , Microcontroller Programming The Microchip PIC, 2007 Nebojsa Matic, "The PIC Microcontrollers ", 2000 Dogan Ibrahim, Advanced PIC Microcontroller Projects in C , 2008 PIC16F84A Datasheet MicroC Users Manual Midterm Examination on Sunday 15/11/2009 at class time 40 Attendance & Participation 20 Final Examination 40 The above dates are fixed. It is your own responsibility to arrange other exams and labs accordingly. For unsolvable situations, you have to consult me before 4/10/2009. Cheating and late submissions are severely penalized. You will lose at least 25% per day for late submissions of your homework and projects. The Attendance and Participation grade is calculated according to the Second Chance System (SCS) which will be used during the course. Basically, your record is updated during each class in three lists: the Attendance List, the White List (positive behavior), and Black List (negative behavior such as coming late, having your mobile phone ringing, .). Details of the SCS will be given at class but for now you should know that missing each class hour costs you 1 point and having two records in the Black List costs you 1 point. In exams a special bonus agreement may be adopted. Missing more 5 hour meetings without official excuse is your easiest way to fail in the course.

Teaching Assistant Prerequisites Office Hours

Course Objectives Text Books

Recommended References Grading (Tentative)

Exams Dates Grading Policy

Course Outline

Week
1-2

Subject
Statement of course objectives, contents, methods, and evaluation Basic Computer Architectures Instruction execution and pipelining Microcontrollers versus microprocessors Harvard versus Von-Neumanns Architecture (RISC, CISC) PIC16F84A Microcontroller Implementing first Application Software & Hardware Development Tools PIC Microcontrollers Families Source Code Format Addressing modes Delay Loops Interrupts Lockup tables EEPROM utilization Macros Midterm Programming PIC microcontrollers in C Flasher Application in C (Simple)

3-4

5-6

7-8

Iqama Application in C (Using interrupts)


9-10 11-12 Keypad and LCD Interface

Analog interface Serial Communication


DC motor control

13-15

Stepper Motor Control Selected Projects

Chapter1Microcon ntrollerBas sics


1.1 SimpleComputerArchitecture

H Seq quence(Fetc chExecute) 1.2 InstructionHandling

1.3 Pipelining

ollersversusmicroproce essors 1.4 Microcontro

1.5 HarvardversusVonNeumannsArchitecture(RISC,CISC)

Program memory

CPU
Address bus Address bus

Data memory

CPU
Address bus

Program and data memory

Instruction bus

Data bus

Data bus

Harvard (RISC)
1.6 PIC16F84A
0000

Von-Neuman CISC

Program memory
1FFF

13-bit

CPU

7-bit

Address bus

Address bus

Data memory

14-bit

Instruction bus

Data bus

8-bit

1.6.1 1Datamemory

1.6.2 2ProgramMemory M

1.7 Implementin ngYourFirstApplication 1 Hardwareconnectio on 1.7.1

1.7.2Softwareprogram 1.7.3ProgramcompilationTools MPLAB,MPASM ;B0=A0 START LOOP

LISTP=PIC16F84A #INCLUDE<P16F84A.INC> __CONFIG_XT_OSC&_PWRTE_ON&_CP_OFF&_WDT_OFF ORG0X000 GOTOSTART ORG0X004 RETFIE BSFSTATUS,RP0;BANK1 BCFTRISB,0;RB0ISOUTPUT BSFTRISA,0;RA0ISINPUT BCFSTATUS,RP0;BANK0 MOVFPORTA,W MOVWFPORTB GOTOLOOP END

1.7.4ProgramLoadingTools WINPIC800,QLPROG 1.7.5Simulationtools Proteus,PICSimulatorIDE

Chapter2ProgrammingmicrocontrollersusingAssemblylanguage 2.1MachinelanguageandAssemblylanguage: Computer:isamachinethatcansolveproblemsbycarryinginstructionsgiventoit. Program:isasequenceofinstructionsdescribinghowtoperformacertaintask. Machinelanguage:isthecomputerprimitiveinstructionsconsistingof0sand1s. 0000 28 05 00000000000000 1 0 1 0 0 0 0 0 0 0 0 1 0 1 0001 xx xx 00000000000001 x x x x x x x x x x x x x x 0002 xx xx 00000000000010 x x x x x x x x x x x x x x 0003 xx xx 00000000000011 x x x x x x x x x x x x x x 0004 00 09 00000000000100 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0005 16 83 00000000000101 0 1 0 1 1 0 1 0 0 0 0 0 1 1 Thisprogram 00000000000110 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0006 10 06 0007 14 05 00000000000111 0 1 0 1 0 0 0 0 0 0 0 1 0 1 copies A0 to B0 0008 12 83 00000000001000 0 1 0 0 1 0 1 0 0 0 0 0 1 1 0009 08 05 00000000001001 0 0 1 0 0 0 0 0 0 0 0 1 0 1 000A 00 86 00000000001010 0 0 0 0 0 0 1 0 0 0 0 1 1 0 000B 28 0B 00000000001011 1 0 1 0 0 0 0 0 0 0 1 0 1 1 000C x x 00000000001100 x x x x x x x x x x x x x x 000D x x 00000000001101 x x x x x x x x x x x x x x 2007 3F F1 10000000000111 1 1 1 1 1 1 1 1 1 1 0 0 0 1 xx xx x x x x x x x x x x x x x x It is almost impossible to write programs directly in machine language. However, they may be written inahumanreadableformofthemachinelanguagewhichiscalledtheAssemblylanguage
GOTO START 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 000A 000B 28 xx xx xx 00 16 10 14 12 08 00 28 05 xx xx xx 09 83 06 05 83 05 86 0B

START

LOOP

RETFI BSF BCF BSF BCF MOVF MOVWF GOTO

0x03,0x5 0x86,0x0 0x85,0x0 0x03,0x5 0x05,0 0x06 LOOP

RETFI BSF BCF BSF BCF MOVF MOVWF

STATUS,RP0 TRISB,0 TRISA,0 PORTA,W PORTB

TheP16F84a.INCfileallowedustowriteidentifiersformemorylocationsinsteadoftheiraddresses

2.2AssemblerStatements(Instructions/Directives)andnumbersRepresentation Instructions are translated to machine code while Directives directs the assembler during translation. For example the END directive informs the assembler to stop. In assembly language, numbers can be represented in decimal, hexadecimal or binary form. We will illustrate this with a number 240: .240 0xF0 b'11110000' decimal hexadecimal binary

2.3AddressingModes ThePIC16F84Acontrollerhas35machinelanguageinstructionseachoneisreferredby36letters mnemonicsintheassemblylanguage.Themnemonicsmaybefollowedbyoneormoreoperands. Themachinecodeofeachinstructionisdividedintofields: Operationcode(opcode):indicatingwhattheprocessoristodo. Operands:indicatingtheinformationneededbytheinstruction(datumoritslocation) OPCODE OPERANDS MOVLW 0x3F MOVF PORTA,w 1 1 0 0 x x 0 0 1 1 1 1 1 1 0 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 1 0 1

MOVWF PORTB BCF BCF CLRF CLRF PORTB,0x0 TRISB,0x0 TMR0 FSR

Thewayinwhichanoperandisspecifiediscalleditsaddressingmode.Thereare2basicaddressing modes: 1.Immediateoperand XORLW0x5F 2.Memoryoperand Direct CLRFTMR0 Indirect CLRFFSR

2.3.1ExpandingtheaddressspacethroughtheideaofBankswhileusingDirect&Indirect Addressing

0000

Program memory
1FFF

13-bit

CPU

7-bit

Address bus

Address bus

Data memory

14-bit

Instruction bus

Data bus

8-bit

10

2.3.2Statusregister

11

2.3.3PORTA, ,TRISA,PO ORTB,TRISB Bregisters

;Ex1 1(Buffer)B0=A A0 LISTP=PIC16F84A P16F84A.INC> > #INCLUDE<P __CONFIG_XT_OSC&_PW _ WRTE_ON&_C CP_OFF&_WDT T_OFF ORG0X000 T GOTOSTART ORG0X004 RETFIE S,RP0;BA ANK1 BSFSTATUS START BCFTRISB,0 0;RB B0ISOUTPUT BSFTRISA,0 0;RA A0ISINPUT BCFSTATUS S,RP0;BA ANK0 OP MOVFPORT TA,W LOO MOVWFPOR RTB GOTOLOOP P END

12

2.4Usingloo ops eratedelays s 2.4.1togene


DECFSZ 0CH GOTO L LOOP1 RETURN ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; END LO OOP MOVLW XORWF CALL GOTO 01h PORTB, F DELAY L LOOP ST TART ;E Ex2 (Flasher) on B0 84A LIST P=PIC16F8 #INCLUDE E <P16F84 4A.INC> __CONFIG G _XT_OS SC&_PWRTE E_ON&_CP_ _OFF&_WDT T_OFF ORG GOTO 0X000 START

ORG 0X004 RETFIE BSF BCF BCF P0 STATUS,RP T TRISB,0 STATUS,RP P0 ;BANK K1 ;RB0 IS OUTPU UT ;BANK K0

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; DE ELAY MOVLW .255 MOVWF 0CH NOP LO OOP1 MOVLW .255 MOVWF 0DH NOP LO OOP0 DECFSZ 0DH GOTO L LOOP0

13

2.4.2toprocessmemoryarrays
LOOP2 GOTO LOOP2 END START LOOP1 ;Ex3 (Memory Block Processing) ;Indirect Addressing application ;Filling All GPR registers with 00h LIST P=PIC16F84A #INCLUDE <P16F84A.INC> __CONFIG _XT_OSC&_PWRTE_ON&_CP_OFF&_WDT_OFF ORG 0X000 GOTO START ORG 0X004 RETFIE MOVLW 0Ch MOVWF FSR CLRF INDF INCF FSR MOVLW 50h SUBWF FSR,w BTFSS STATUS,Z GOTO LOOP1

14

2.5Interrupt ts

;Ex4 (I Interrupt t applica ation) LIST T P=PIC16F84A #INC CLUDE <P16F84A.INC C> __CO ONFIG _XT_OSC&_PW WRTE_ON&_ _CP_OFF&_ _WDT_OFF ORG GOTO O ORG MOVW WF MOVF F MOVW WF BCF MOVL LW XORW WF BCF MOVF F MOVW WF SWAP PF SWAP PF RETF FIE START BSF BCF BSF MOVL LW MOVW WF BCF BCF BCF LOOP 0X000 START 0X004 ;pus 0Eh sh W and Status STATUS,W 0Fh STATUS,RP0 4 PORTB,F N,INTF INTCON 0Fh,W W STATUS 0EH,F 0EH,W W

errupt Fl lag ;Reset the Inte tus ;pop W and Stat

STATUS,RP0 N_REG,6 OPTION TRISB,0

NK 1 ; BAN ; -0-- ---- FOR Edge e program mmig ; B0 IS INPUT T


B'10010000' INTCON N TRISB,1 TRISB,2 STATUS,RP0 ; 1--1 --0CLEAR EX XTERNAL INT I FLAG

;B1 is output ;B2 is output ;BANK K0

MOVL LW 02h XORW WF PORTB,F CALL L DELAY GOTO O LOOP ;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DELAY LW .255 MOVL MOVW WF 0CH LOOP1 NOP MOVL LW .255 MOVW WF 0DH

15

Interrupts are a mechanism of a microcontroller which enables itto respond to some events at the moment theyoccur,regardlessofwhatmicrocontrollerisdoingatthetime. Each interrupt changes the program flow, interrupts it and after executing an interrupt subroutine it continues fromthatsamepointon.

2.5.1SourcesofinterruptforPIC16F84A:
1.TerminationofwritingdatatoEEPROM. 2.TMR0interruptcausedbytimeroverflow. 3.InterruptduringalterationonRB4,RB5,RB6andRB7pinsofportB. 4.ExternalinterruptfromRB0/INTpinofmicrocontroller.

2.5.2Registersusedwithinterrupt: 1. Control interrupt register (INTCON) at 0Bh address. 2. Option register at 81h address. 3. Control EEPROM register (EECON 1) at 88h address.

bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0

R/W0 R/W0 R/W0 R/W0 R/W0 R/W0 R/W0 R/Wx GIE EEIE T0IE INTE RBIE T0IF INTF RBIF bit7 bit0 GIE:GlobalInterruptEnablebit 1=Enablesallunmaskedinterrupts 0=Disablesallinterrupts EEIE:EEWriteCompleteInterruptEnablebit 1=EnablestheEEWriteCompleteinterrupts 0=DisablestheEEWriteCompleteinterrupt T0IE:TMR0OverflowInterruptEnablebit 1=EnablestheTMR0interrupt 0=DisablestheTMR0interrupt INTE:RB0/INTExternalInterruptEnablebit 1=EnablestheRB0/INTexternalinterrupt 0=DisablestheRB0/INTexternalinterrupt RBIE:RBPortChangeInterruptEnablebit 1=EnablestheRBportchangeinterrupt 0=DisablestheRBportchangeinterrupt T0IF:TMR0OverflowInterruptFlagbit 1=TMR0registerhasoverflowed(mustbeclearedinsoftware) 0=TMR0registerdidnotoverflow INTF:RB0/INTExternalInterruptFlagbit 1=TheRB0/INTexternalinterruptoccurred(mustbeclearedinsoftware) 0=TheRB0/INTexternalinterruptdidnotoccur RBIF:RBPortChangeInterruptFlagbit 1=AtleastoneoftheRB7:RB4pinschangedstate(mustbeclearedinsoftware) 0=NoneoftheRB7:RB4pinshavechangedstate

OptionRegister EECON1Register

RBPU

INTEDG

T0CS

T0SE EEIF

PSA WRERR

PS2 WREN

PS1 WR

PS1 RD

16

When an inte W errupt occurs s, its corresp ponding flag g bit is set. It must be cleared in s software in order o to allo ow re epeatinginte erruptevents s.

gtheconte entsofimpo ortantregis sters 2.5.3Keeping


An n important part of the interrupt pr rocess is the e stack. Its basic b role is to t keep the value of pro ogram count ter af fter a jump from f the main program to t an addres ss of a subpr rogram. In order for a pr rogram to kn now how to go ba ack to the point where it started fro om, it has to o return the e value of a program counter from a stack. When moving from a program to a subpro ogram, program counter is being pushed p onto a stack. When W executing URN, RETLW W or RETFIE which were executed at a the end o of a subprog gram, progra am instructions such as RETU ounter was taken t from a stack so th hat program m could continue from where w it stop pped before the interrupt. co Th heseoperatio onsofplacin ngonandtak kingofffrom maprogramcounterstac ckarecalledPUSHandPOP. Ho owever,theprogrammerhastokeep pthevalueof o otherregis stersusedinthemainpr rogramsuchasthestatus an ndworkregis sters.Thismay m bedoneasfollows: MOVWF0Eh MOVFSTA ATUS,W MOVWF0Fh ;pus shWandSta atus

MOVF0Fh,W MOVWFSTA ATUS SWAPF0EH H,F SWAPF0EH H,W

;ISR R(interruptse erviceroutin ne) ;pop pWandStat tus

17

2.6TIMER0(TMR0)module

18

2.6.1DelaywithTIMER0:
Ageneralformulaforcalculatingthenumberoftimerbeatspersecondisasfollows: T=C/(4*P*R) Where T is the number of clock beats per second ,C is the system clock speed in Hz , P is value stored in the prescaler , and R is the number of iterations counted in theTMR0 register. The range of both P and R in this formulais1to256. Delay: MOVFTMR0,W;TIMERVALUEINTOW BTFSSSTATUS,Z;WASITZERO? GOTODelay

2.6.2Countermode:
The PIC16F84A can be programmed so hat portRA4/T0CKI is used to count events or pulses by initializing the Timer0moduleasacounter.Withoutinterrupts,theprocessrequiresthefollowingpreparatorysteps: PortA,line4,(RA4/T0CKI)isdefinedforinput. TheTimer0register(TMR0)iscleared. TheOPTIONregisterbitsPSAandPS0:PS2areinitializediftheprescaleristobeused. TheOPTIONregisterbitT0SEissetsoastoincrementthecountonthehightolowtransitionoftheport piniftheportsourceisactivelow.Otherwisethebitiscleared. TheOPTIONregisterbitT0CSissettoselectactionontheRA4/T0CKIpin.

19

; Ex5 (Counter a) Counter on RA4/T0CKI from 00-FF ; No Interrupt is used here LIST P=PIC16F84A #INCLUDE <P16F84A.INC> __CONFIG _XT_OSC&_PWRTE_ON&_CP_OFF&_WDT_OFF ORG 0X000 GOTO START ORG 0X004 RETFIE START BSF MOVLW MOVWF CLRF MOVLW MOVWF BCF CLRF MOVF MOVWF GOTO END STATUS,RP0 B'10111000' OPTION_REG TRISB B'00011111' TRISA STATUS,RP0 TMR0 TMR0,W PORTB LOOP ; BANK 1 ; xx11 1xxx ; PORT B IS OUTPUT ; PORT A IS INPUT ;BANK0

LOOP

20

; Ex5 (Counter_b) Counter on RA5/T0CKI Using Poling, ; (Bad implementation !) LIST P=PIC16F84A #INCLUDE <P16F84A.INC> __CONFIG _XT_OSC&_PWRTE_ON&_CP_OFF&_WDT_OFF ORG 0X000 GOTO START ORG 0X004 RETFIE START BSF CLRF MOVLW MOVWF BCF CLRF BTFSS GOTO INCF GOTO END STATUS,RP0 TRISB B'00011111' TRISA STATUS,RP0 PORTB PORTA,4 LOOP PORTB LOOP ; BANK 1 ; PORT B IS OUTPUT ; PORT A IS INPUT ;BANK0

LOOP

; Ex5 (Counter_c) Counter on RA5/T0CKI Using Poling, ; (Good implementation !) LIST P=PIC16F84A #INCLUDE <P16F84A.INC> __CONFIG _XT_OSC&_PWRTE_ON&_CP_OFF&_WDT_OFF ORG 0X000 GOTO START ORG 0X004 RETFIE START BSF CLRF MOVLW MOVWF BCF CLRF BTFSS GOTO INCF BTFSC GOTO GOTO END STATUS,RP0 TRISB B'00011111' TRISA STATUS,RP0 PORTB PORTA,4 LOOP PORTB PORTA,4 LOOP1 LOOP ; BANK 1 ; PORT B IS oUTPUT ; PORT A IS INPUT ; BANK0

LOOP

; Key is pressed

LOOP1

; Key is released

21

; Ex5 (Counter_d) Counter on RA5/T0CKI 0-99 twice,0-55 and restart LIST P=PIC16F84A #INCLUDE <P16F84A.INC> __CONFIG _XT_OSC&_PWRTE_ON&_CP_OFF&_WDT_OFF CBLOCK 0X20 TEMP DIG0 DIG1 DIG2 ENDC ORG 0X000 GOTO START ORG 0X004 RETFIE START BSF MOVLW BCF CLRF MOVLW MOVWF BCF CLRF MOVF Call SWAPF IORWF MOVWF GOTO MOVWF CLRF CLRF MOVLW SUBWF BTFSS GOTO INCF GOTO MOVLW AddWF MOVLW SUBWF BTFSS GOTO INCF GOTO MOVLW ADDWF MOVF MOVWF RETURN END STATUS,RP0 B'10111000' OPTION_REG,6 TRISB B'00011111' TRISA STATUS,RP0 TMR0 TMR0,W BCD DIG1,W DIG0,W PORTB LOOP TEMP DIG1 DIG2 .100 TEMP,F STATUS,C _10 DIG2,F _100 .100 TEMP,F .10 TEMP,F STATUS,C _1 DIG1,F __10 .10 TEMP,F TEMP,W DIG0 ; BANK 1 ; 1-11 1000 ; PORT B IS oUTPUT ; PORT A IS INPUT ; BANK0

LOOP

BCD

_100

;EXTRACT 100'S NUMBER ;TEMP=TEMP-100

_10 __10

;EXTRACT TEN'S NUMBER

;TEMP=TEMP-10

_1

22

2.7LookUpTables T

;Ex6(LUT) )Anapplication nforLuokupta ables LISTP=PIC16F84A #INCL LUDE<P16F84A A.INC> __CO ONFIG_XT_OSC C&_PWRTE_ON N&_CP_OFF&_W WDT_OFF ORG0X000 OSTART GOTO ORG0X004 RETFIE P0 ;BANK1 BSF STATUS,RP START TRISB REOUTPUT ;ALLPORTBPINSAR CLRF VLWB'0001111 11' MOV MOV VWFTRISA TAPINSAREIN NPUT ;PORT BCF P0 STATUS,RP VLW C0h MOV ;0 MOV VWF 0Ch MOV VLW 0F9h ;1 MOV VWF 0Dh MOV VLW 0A4h ;2 MOV VWF 0Eh MOV VLW 0B0h ;3 MOV VWF 0Fh MOV VLW 99h ;4 MOV VWF 10h MOV VLW 92h ;5 MOV VWF 11h MOV VLW 82h ;6 MOV VWF 12h MOV VLW 0F8h ;7 MOV VWF 13h MOV VLW 00h ;8 MOV VWF 14h MOV VLW 90h ;9 MOV VWF 15h VLW 0Fh MOV LOOP ANDW WF PORTA,W ADDL LW 0Ch MOV VWF FSR MOV VF INDF,W MOV VWF PORTB GOTO OLOOP END

23

2.8EEPROMutilization ThePIC16F84andPIC16F84Acontain64bytesofEEPROMdatamemory.Thismemoryisbothreadable and writable during normal operation. It is not mapped in the register file space, but is indirectly addressed through the Special Function Registers EECON1, EECON2, EEDATA, and EEADR. The address of EEPROM memory starts at location 0x00 and extends to the maximum contained in the PIC, in this case,0x3f.ThefollowingregistersrelatetoEEPROMoperations:

1.EEDATAholdsthedatabytetobereadorwritten. 2.EEADRcontainstheEEPROMaddresstobeaccessedbythereadorwriteoperation. 3.EECON1containsthecontrolbitsforEEPROMoperations. 4.EECON2protectsEEPROMmemoryfromaccidentalaccess.Thisisnotaphysicalregister. EECON1Register EEIF WRERR WREN WR RD

24

; Ex7 (EE_a) EEP PROM handl ling appli ication LIST T P=PIC1 16F84A #INC CLUDE <P16 6F84A.INC> > __CO ONFIG _XT T_OSC&_PWR RTE_ON&_CP P_OFF&_WDT T_OFF ORG 0X000 O START GOTO ORG 0X004 RETF FIE START BSF F CLRF BSF MOVL LW MOVW WF BCF MOVL LW MOvW WF LOOP0 BTFS SS GOTO O MOVF F MOVW WF BSF BCF BCF BSF MOVL LW MOVW WF MOVL LW MOVW WF BSF BSF LOOP1 BTFS SS GOTO O BCF CLRF F LOOP2 BTFS SC GOTO O BSF BSF BCF BCF F MOVF MOVW WF LOOP3 GOTO O END STATU US,RP0 TRISB B TRISB B,0 B'000 011111' TRISA A STATU US,RP0 07h EEADR R PORTB B,0 LOOP0 0 PORTA A,W EEDAT TA STATU US,RP0 INTCO ON,GIE EECON N1,EEIF EECON N1,WREN 55h EECON N2 0AAh EECON N2 EECON N1,WR INTCO ON,GIE EECON N1,EEIF LOOP1 1 STATU US,RP0 EEDAT TA PORTB B,0 LOOP2 2 STATU US,RP0 EECON N1,RD TRISB B,0 STATU US,RP0 EEDAT TA,W PORTB B LOOP3 3 ;EECON1 1 is at 88 8h ;Readin ng from EE EPROM ;B0 IS OUTPUT ;EEDATA A is at 08 8h ;BANK1 ;ALL PO ORTB PINS ARE OUTPU UT ;Except t B0 is in nput ;PORTA PINS ARE INPUT

ddress ;(1) ad

;(2) da ata

;(3) ;(4) ;(5) ;(6)

di isable int terrupts cl lear EEIF en nable writ ting ke eys

;(7) in nitialize writing ;(8) en nable inte errupts ;wait until u writ ting is do one

25

; Ex7 (EE_b) EEPROM E ha andling applicati a on LIS ST P=PI IC16F84A #IN NCLUDE <P P16F84A.INC> __C CONFIG _XT_OSC&_ _ _PWRTE_ON&_CP_OFF& &_WDT_OFF F ORG G 0X00 00 GOT TO STAR RT ORG G 0X00 04 RET TFIE START BSF F STATU US,RP0 MOV VLW B'00 0000001' MOV VWF TRIS SB MOV VLW B'00 0011111' MOV VWF TRIS SA BCF F STATU US,RP0 MOV VLW 07h MOv vWF EEAD DR LOOP0 BTF FSS PORT TB,0 GOT TO LOOP0 0 MOV VF PORTA A,W MOV VWF EEDA ATA BSF F BCF F BCF F BSF F MOV VLW MOV VWF MOV VLW MOV VWF BSF F BSF F LOOP1 STATU US,RP0 INTC CON,GIE EECO ON1,EEIF EECON N1,WREN 0X55 5 EECO ON2 0XAA A EECO ON2 EECON N1,WR INTCO ON,GIE ;BANK1 ;ALL POR RTB PINS A ARE OUTPU UT ;Except B0 is inp put ;PORTA PINS P ARE INPUT

;(1) add dress

;(2) dat ta

;(3) ;(4) ;(5) ;(6)

disable inte errupts clear EEIF ena able writing key ys

;(7) initialize w writing ;(8) ena able interrupts ;wait un ntil writing is do one

BTF FSS EECO ON1,EEIF GOT TO LOOP P1 BCF F EECON N1,WREN BCF F STATU US,RP0 CLR RF EEDAT TA BTF FSC GOT TO BSF F BSF F BCF F RLF F MOV VWF PORT TB,0 LOOP P2 STATU US,RP0 EECON N1,RD STATU US,RP0 EEDAT TA,W PORTB B

LOOP2

;EECON1 is at 88h h ;Reading g from EEPROM ;EEDATA is at 08h h

GOT TO LOOP0 END D

26

2.9Macros
Macros are a very useful element M e in assembly a language. They y could briefl ly be describ bed as "user defined group of f instructions s which will enter assem mbler program where ma acro was called". It is po ossible to wr rite a progra am ev ven without using macr ros. But with h their use written program is much more rea adable, espe ecially if mo ore pr rogrammersareworking gonthesameprogramto ogether.Macroshaveth hesamepurp poseasfunctionsofhigh her pr rogramlangu uages. W What's thedif fferencebet tweenmacro oandsubrou utine? 1) In exe ecution stage e, the subroutine puts the address of o the called d function in n PC and hides the origin nal valueofPC(beforecalling)inthe t stack. 2) The macro m in com mpilation process (not in execution), copies the macro m in the place where e it is called. It doesn n'tputaddressonstack. 3) Thesu ubroutinecanbewritten norcalledinanyplace,but b themacro omustbede eclaredbefo orecalling. 4) Thesu ubroutinetakesmoretim meinexecuti ion,butusua allycompiles stoshorterp programs

2.9.1UsingMacros M inte ernally


27

;This is an example for using MACROS internally in the program. LIST P=PIC16F84A #INCLUDE <P16F84A.INC> __CONFIG _XT_OSC&_PWRTE_ON&_CP_OFF&_WDT_OFF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; BCDto7segTable Macro ;MACRO BEGINES HERE MOVLW C0h ;0 MOVWF 0Ch MOVLW 0F9h ;1 MOVWF 0Dh MOVLW 0A4h ;2 MOVWF 0Eh MOVLW 0B0h ;3 MOVWF 0Fh MOVLW 99h ;4 MOVWF 10h MOVLW 92h ;5 MOVWF 11h MOVLW 82h ;6 MOVWF 12h MOVLW 0F8h ;7 MOVWF 13h MOVLW 00h ;8 MOVWF 14h MOVLW 90h ;9 MOVWF 15h ENDM ;MACRO ENDS HERE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; START BSF CLRF MOVLW MOVWF BCF STATUS,RP0 TRISB B'00011111' TRISA STATUS,RP0 ;BANK1 ;ALL PORTB PINS ARE OUTPUT ;PORTA PINS ARE INPUT

BCDto7segTable LOOP MOVLW ANDWF ADDLW MOVWF MOVF MOVWF GOTO END 0Fh PORTA,W 0Ch FSR INDF,W PORTB LOOP

;CALLING A MACRO

28

2.9.2UsingMacrosexternally:
;This is an example for using MACROS externally in the program. LIST P=PIC16F84A #INCLUDE <P16F84A.INC> #INCLUDE <MyLibrary.INC> __CONFIG _XT_OSC&_PWRTE_ON&_CP_OFF&_WDT_OFF START BSF STATUS,RP0 ;BANK1 CLRF TRISB ;ALL PORTB PINS ARE OUTPUT MOVLW B'00011111' MOVWF TRISA ;PORTA PINS ARE INPUT BCF STATUS,RP0 BCDto7segTable ;CALLING A MACRO LOOP MOVLW 0Fh ANDWF PORTA,W ADDLW 0Ch MOVWF FSR MOVF INDF,W MOVWF PORTB GOTO LOOP END

BCDto7segTable

Mylibrary.INC Macro MOVLW 0C0h MOVWF 0Ch MOVLW 0F9h MOVWF 0Dh MOVLW 0A4h MOVWF 0Eh MOVLW 0B0h MOVWF 0Fh MOVLW 99h ;4 MOVWF 10h MOVLW 92h ;5 MOVWF 11h MOVLW 82h ;6 MOVWF 12h MOVLW 0F8h MOVWF 13h MOVLW 00h ;8 MOVWF 14h MOVLW 90h ;9 MOVWF 15h ENDM

;0 ;1 ;2 ;3

;7

29

;Ex8 (Macro) Decimal Counter on RA5/T0CKI as Ex5d LIST P=PIC16F84A #INCLUDE <P16F84A.INC> #INCLUDE <ECOM4315.INC> __CONFIG _XT_OSC&_PWRTE_ON&_CP_OFF&_WDT_OFF CBLOCK TEMP DIG0 DIG1 DIG2 ENDC 0X20

ORG 0X000 GOTO START ORG 0X004 RETFIE START BSF MOVLW BCF CLRF MOVLW MOVWF BCF CLRF MOVF STATUS,RP0 ; BANK 1 B'10111000' OPTION_REG,6 ; 1-11 1000 TRISB ; PORT B IS oUTPUT B'00011111' TRISA ; PORT A IS INPUT STATUS,RP0 ; BANK0 TMR0 TMR0,W

LOOP

BCD
SWAPF IORWF MOVWF GOTO END

TEMP,DIG0,DIG1,DIG2
DIG1,W DIG0,W PORTB LOOP

; file name is ECOM5315.INC BCD Macro Temp,DIG0,DIG1,DIG2 local 100, _10, __10, _1 MOVWF TEMP CLRF DIG1 CLRF DIG2 _100 MOVLW .100 ;EXTRACT 100'S NUMBER SUBWF TEMP,F ;TEMP=TEMP-100 BTFSS STATUS,C GOTO _10 INCF DIG2,F GOTO _100 _10 MOVLW AddWF MOVLW SUBWF BTFSS GOTO INCF GOTO MOVLW ADDWF MOVF MOVWF ENDM .100 TEMP,F .10 TEMP,F STATUS,C _1 DIG1,F __10 .10 TEMP,F TEMP,W DIG0 ;EXTRACT TEN'S NUMBER

__10

;TEMP=TEMP-10

_1

30

2.10ThehexadecimalobjectfileformatforPICMicrocontroller
GeneralRecordFormat: RecordMark LoadRecord ':' Length 1byte 1byte

Offset 2bytes

RecordType

1byte 1byte Record Mark: each record begins with a Record Mark field containing 03AH, the ASCII code for the colon ':' character. RecordLength:Thenumberofbytesofinformationordata. Offset:Bytheoffsetwecanarrivetotheaddress. Record Type: It is used to interpret the remaining information within the record. The encoding for all the current recordtypesis: RecordType Description InformationorDataDigits 00 DataRecord x 01 EndofFileRecord 0 02 ExtendedSegmentAddressRecord 4 03 StartSegmentAddressRecord 8 04 ExtendedLinearAddressRecord 4 05 StartLinearAddressRecord 8

Information orData nbytes

ChickSum

Information or Data: It consists of zero or more bytes encoded as pairs of hexadecimal digits. The interpretation of thisfielddependsontheRecordTypefield. ChickSum:ThisfieldcontainsthechecksumontheRecordlength,LoadOffset,RecordType,andInformationor Data.Therefore,thesumofalltheASCIIpairsinarecordafterconvertingtobinary,fromtheRecordlengthfieldto andincludingtheChickSumfield,iszero. .HEXFileofEx1 :020000040000FA :020000000528D1 :0800080009008316051006141F :0800100083120608850009288F :02400E00F13F80 :00000001FF

Record Record Record Offset Mark Length Type : 02 0000 04 : 02 0000 00 : 08 0008 00 : 08 0010 00 : 02 400E 00 : 00 0000 01

Info.orData 0000 0528 0900831605100614 8312060885000928 F13F

Chick Sum FA D1 1F 8F 80 FF

31

ModelingtheprogrammemoryinPICMicrocontrollers (Hexanotation)

(Binarynotation) content 1 0 1 0 0 0 0 0 0 0 0 1 0 1

Address content Address 0000 28 05 0001 0002 0003 0004 0005 0006 0007 0008 0009 000A 000B 1FFF 2007 xx xx xx xx xx xx

Address 0000000000000 0000000000001 0000000000010 0000000000011 0000000000100 0000000000101 0000000000110 0000000000111 0000000001000 0000000001001 0000000001010 0000000001011 1111111111111

x x x x x x x x x x x x x x x x x x 0 0 0 0 0 0 0 1 0 1 1 1 1 0 0 0 1 0 0 0 0 0 1 0 1 1 0 1 0 1 0 0 0 0 1 0 1 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 1

x x x x x x x x x x x x x x x x x x x x x x x x 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 1 0 1 1 1 0 0 0 1 1 1 0 1 0 1 1 1

00 09 16 83 10 05 14 06 12 83 08 06 00 85 28 09 xx xx

3F F1

10000000000111 1

1 1 1 1 0 0


32

4-1

Introduction to C language

The C programming language allows applications to be written using syntax whose meaning is a little easier to understand than assembly code. Programs in C are converted into assembly language by a compiler, and assembled into machine code, in a two-stage process. 1- Compile to assembly level code. 2- Assemble link to machine code. The process of compiling, along with the files used and generated, is illustrated in Figure 4-1 The main program, the C source file, is written in the C language, in a file with the extension .c.

Figure 4-1 Process of compiling the C source file C is the high-level language of choice for PIC microcontrollers. A range of different development systems and compilers are available, but most use the same basic syntax defined as ANSI (American National Standards Institute) C. Assembly language is syntax which is unique to each type of processor, while C provides a common language for all MCU(Microcontroller unit) types.

4-2

Introduction to mikroC

mikroC is a powerful, feature rich development tool for PICmicros. It is designed to provide the programmer with the easiest possible solution for developing applications for embedded systems, without compromising performance or control.

33

PIC and C fit together well: PIC is the most popular 8-bit chip in the world, used in a wide variety of applications, and C, prized for its efficiency, is the natural choice for developing embedded systems. mikroC provides a successful match featuring highly advanced IDE, ANSI compliant compiler, broad set of hardware libraries, comprehensive documentation, and plenty of ready-to-run examples. mikroC allows you to quickly develop and deploy complex applications: Write your C source code using the built-in Code Editor (Code and Parameter Assistants, Syntax Highlighting, Auto Correct, Code Templates, and more) Use the included mikroC libraries to dramatically speed up the development: data acquisition, memory, displays, conversions, communications Practically all P12, P16, and P18 chips are supported. Monitor your program structure, variables, and functions in the Code Explorer. Generate commented, human-readable assembly, and standard HEX compatible with all programmers. Inspect program flow and debug executable logic with the integrated Debugger. Get detailed reports and graphs: RAM and ROM map, code statistics, assembly listing, calling tree, and more We have provided plenty of examples for you to expand, develop, and use as building bricks in your projects. Copy them entirely if you deem fit thats why we included them with the compiler.

mikroC is a user-friendly and intuitive environment:

Figure 4-2 mikroC IDE

34

The Code Explorer (with Keyboard shortcut browser and Quick Help browser) is at your disposal for easier project management. The Error Window displays all errors detected during compiling and linking. The source-level Debugger lets you debug executable logic step-by-step by watching the program flow. The New Project Wizard is a fast, reliable, and easy way to create a project. Help files are syntax and context sensitive. As with any modern Windows application, you may customize the layout of mikroC to best suit your needs. See (Figure 4-2).

4-2

Building the First Program (Flasher)

Figure 4-3 Flasher on PORTB

/*This program is a simple program to make a flasher wave on PORTB of the PIC16F84A, using an infinite loop to make sure that the wave still blinking on PORTB, and using a delay of 0.5 sec between every flashing led*/ void main() { TRISB = 0; PORTB = 0;

while(1) { PORTB = ~PORTB; Delay_ms(1000); } }

35

Notes: In MicroC, we didn't need to initialize the banks. We can deal with the each ports directly. The line command PORTB = ~PORTB is used to get the complement status of the previous status in PORTB to apply the idea of the flasher. The function Delay_ms is used to make delay.

To make flasher on one bit only we can apply one of the following ways: 1PORTB = (~ PORTB & 0b00000001) | (PORTB & 0b11111110) Notes: This line is used to apply the XOR operation. | It is a bit wise operation, dealing with the number bit by bit. || It is dealing with the number as one unit. 2PORTB= PORTB & 0b11111110 Delay_ms(1000); PORTB= PORTB | 0b00000001 Delay_ms(1000);

The procedures to write this is program in mikroC program: 1-From project select New Project

Figure 4-4 New Project.

36

2- Enter Project Name, Project Path, Device, Clock and Configurations.

Figure 4-5 Project Name, Project Path, Device, Clock and Configurations. 3-Write the program in Code Editor

Figure 4-6 Program Writing.

37

4- From Project enter Build

Figure 4-7 Program Building. 5- After Build the following message well appears.

Figure 4-8 Message after Building.

4-3

IQAMA Application

The idea of this program to build an application to be used to display the time remaining to the Iqama after each Athan of the Muslim's fife pray times. This application can be implemented as shown in (Figure 4-8)

38

Figure 4-9 IQAMA application.


//Iqama Application int i, j; void interrupt() { INTCON=INTCON & 0b11111110; if ((PORTB & 0b00010000)==0b0) i=10; if ((PORTB & 0b00100000)==0b0) i=15; if ((PORTB & 0b01000000)==0b0) i=20; } void main() { INTCON = 0b10001000; TRISA = 0; PORTA = 0; TRISB = 0xF0; PORTB = 0; while(1) { while(i>0) { j = i % 10; PORTA = j; j = (i / 10) % 10; PORTB = j; Delay_us(995840); i-- ; } PORTA =0; PORTB =0; } }

39

Notes: The idea of the program is to determine the time interval between each Athan and Iqama. Each switch is used to determine the interval of a specific Athan. The time appeared on the two 7segment. In low level language, the counter is a memory location. But in high level language to make a counter we just need to declare variable. Port A was set to be output. B0 B3 output and B4 B7 were adjusted to be input. The line command if ((PORTB & 0b00010000)==0b0) i=10; is used to determine the time or the count of each switch to represent the interval of a specific Athan. The code inside the while is used to send the LSB and MSB on PORTA, PORTB respectively. In Micro C code, Retfie is not important to be written.
B B

40

EEPROM Library
EEPROM data memory is available with a number of PICmicros. mikroC includes library for comfortable work with EEPROM.

Library Routines

Eeprom_Read Eeprom_Write

Eeprom_Read

Prototype Returns Description

unsigned short Eeprom_Read(unsigned int address); Returns byte from specified address. Reads data from specified address. Parameter address is of integer type, which means it supports MCUs with more than 256 bytes of EEPROM.

Requires

Requires EEPROM module. Ensure minimum 20ms delay between successive use of routines Eeprom_Write and Eeprom_Read. Although PIC will write the correct value, Eeprom_Read might return an undefined result.

Example

unsigned short take; ... take = Eeprom_Read(0x3F);

Eeprom_Write

Prototype

void Eeprom_Write(unsigned int address, unsigned short data); Nothing. Writes data to specified address. PParameter address is of integer type, which means it supports MCUs with more than 256 bytes of

Returns Description

41

EEPROM. Be aware that all interrupts will be disabled during execution of Eeprom_Write routine (GIE bit of INTCON register will be cleared). Routine will restore previous state of this bit on exit. Requires Requires EEPROM module. Ensure minimum 20ms delay between successive use of routines Eeprom_Write and Eeprom_Read. Although PIC will write the correct value, Eeprom_Read might return an undefined result. Example
Eeprom_Write(0x32, 19);

Library Example
The example demonstrates using EEPROM Library.

unsigned short i = 0, j = 0; void main() { PORTB = 0; TRISB = 0; j = 4; for (i = 0; i < 20u; i++) EEprom_Write(i, j++); for (i = 0; i < 20u; i++) { PORTB = Eeprom_Read(i); Delay_ms(500); } }//~!

42

LCD Library
mikroC provides a library for communication with LCDs (with HD44780 compliant controllers) through the 4-bit interface. An example of LCD connections is given on the schematic at the bottom of this page. For creating a custom set of LCD characters use LCD Custom Character Tool. Note: mikroElektronika's development system based initialization routines are included in Code Templates. Note: Only Lcd_Config and Lcd_Init routines use the RW pin (RW pin is configured as output and set to zero). If the user needs this pin for other purposes, it can be reconfigured after Lcd_Config or Lcd_Init call.

Library Routines

Lcd_Config Lcd_Init Lcd_Out Lcd_Out_Cp Lcd_Chr Lcd_Chr_Cp Lcd_Cmd

Lcd_Config

Prototype

void Lcd_Config(unsigned short *port, unsigned short RS, unsigned short EN, unsigned short WR, unsigned short D7, unsigned short D6, unsigned short D5, unsigned short D4); Nothing. Initializes LCD at port with pin settings you specify: parameters RS, EN, WR, D7 .. D4 need to be a combination of values 07 (e.g. 3,6,0,7,2,1,4). Nothing.
Lcd_Config(&PORTD, 0, 1, 7, 5, 4, 3, 2);

Returns Description

Requires Example

Lcd_Init

Prototype Returns Description

void Lcd_Init(unsigned short *port); Nothing. Initializes LCD at port with default pin settings (see the connection scheme at the end of the chapter):
D7 D6 D5 D4 E port.7 port.6 port.5 port.4 port.3

43

RS port.2 RW port.0

Requires Example

Nothing.
Lcd_Init(&PORTB);

Lcd_Out

Prototype Returns Description

void Lcd_Out(unsigned short row, unsigned short col, char *text); Nothing. Prints text on LCD at specified row and column (parameters row and col). Both string variables and literals can be passed as text.

Requires Example

Port with LCD must be initialized. See Lcd_Config or Lcd_Init. Print Hello! on LCD at line 1, char 3:
Lcd_Out(1, 3, "Hello!");

Lcd_Out_Cp

Prototype Returns Description

void Lcd_Out_Cp(char *text); Nothing. Prints text on LCD at current cursor position. Both string variables and literals can be passed as text. Port with LCD must be initialized. See Lcd_Config or Lcd_Init. Print Here! at current cursor position:
Lcd_Out_Cp("Here!");

Requires Example

Lcd_Chr

Prototype Returns Description

void Lcd_Chr(unsigned short row, unsigned short col, char character); Nothing. Prints character on LCD at specified row and column (parameters row and col). Both variables and literals can be passed as character.

Requires Example

Port with LCD must be initialized. See Lcd_Config or Lcd_Init. Print i on LCD at line 2, char 3:
Lcd_Chr(2, 3, 'i');

44

Lcd_Chr_Cp

Prototype Returns Description

void Lcd_Chr_Cp(char character); Nothing. Prints character on LCD at current cursor position. Both variables and literals can be passed as character.

Requires Example

Port with LCD must be initialized. See Lcd_Config or Lcd_Init. Print e at current cursor position:
Lcd_Chr_Cp('e');

Lcd_Cmd

Prototype Returns Description

void Lcd_Cmd(unsigned short command); Nothing. Sends command to LCD. You can pass one of the predefined constants to the function. The complete list of available commands is below.

Requires Example

Port with LCD must be initialized. See Lcd_Config or Lcd_Init. Clear LCD display:
Lcd_Cmd(Lcd_Clear);

Available LCD Commands

LCD Command

Purpose Move cursor to 1st row Move cursor to 2nd row Move cursor to 3rd row Move cursor to 4th row Clear display Return cursor to home position, returns a shifted display to original position. Display data RAM is unaffected.

LCD_FIRST_ROW LCD_SECOND_ROW LCD_THIRD_ROW LCD_FOURTH_ROW LCD_CLEAR LCD_RETURN_HOME

LCD_CURSOR_OFF LCD_UNDERLINE_ON LCD_BLINK_CURSOR_ON LCD_MOVE_CURSOR_LEFT LCD_MOVE_CURSOR_RIGHT LCD_TURN_ON

Turn off cursor Underline cursor on Blink cursor on Move cursor left without changing display data RAM Move cursor right without changing display data RAM Turn LCD display on

45

LCD_TURN_OFF LCD_SHIFT_LEFT LCD_SHIFT_RIGHT

Turn LCD display off Shift display left without changing display data RAM Shift display right without changing display data RAM

Library Examples
Default Pin Configuration
Use Lcd_Init for default pin settings (see the first figure below).

char *text = "mikroElektronika"; void main() { TRISB = 0; Lcd_Init(&PORTB); Lcd_Cmd(Lcd_CLEAR); Lcd_Cmd(Lcd_CURSOR_OFF); Lcd_Out(1, 1, text); }//~!

// // // // //

PORTB is output Initialize LCD connected to PORTB Clear display Turn cursor off Print text to LCD, 2nd row, 1st column

LCD HW connection by default initialization (using Lcd_Init)

46

LCD8 (8-bit interface) Library


mikroC provides a library for communication with LCDs (with HD44780 compliant controllers) through the 8-bit interface. An example of LCD connections is given on the schematic at the bottom of this page. For creating a custom set of LCD characters use LCD Custom Character Tool. Note: mikroElektronika's development system based initialization routines are included in Code Templates. Note: Only Lcd8_Config and Lcd8_Init routines use the RW pin (RW pin is configured as output and set to zero). If the user needs this pin for other purposes, it can be reconfigured after the Lcd8_Config or Lcd8_Init call.

Library Routines

Lcd8_Config Lcd8_Init Lcd8_Out Lcd8_Out_Cp Lcd8_Chr Lcd8_Chr_Cp Lcd8_Cmd

Lcd8_Config

Prototype

void Lcd8_Config(unsigned short *ctrlport, unsigned short *dataport, unsigned short RS, unsigned short EN, unsigned short WR, unsigned short D7, unsigned short D6, unsigned short D5, unsigned short D4, unsigned short D3, unsigned short D2, unsigned short D1, unsigned short D0); Nothing. Initializes LCD at Control port (ctrlport) and Data port (dataport) with pin settings you specify. Parameters RS, EN, WR need to be in range 07; Parameters D7 .. D0 need to be a combination of values 07 (e.g. 3,6,5,0,7,2,1,4).

Returns Description

Requires Example

Nothing.
Lcd8_Config(&PORTC,&PORTD,0,1,2,6,5,4,3,7,1,2,0);

Lcd8_Init

Prototype Returns Description

void Lcd8_Init(unsigned short *portctrl, unsigned short *portdata); Nothing. Initializes LCD at Control port (portctrl) and Data port (portdata) with default pin settings (see the connection scheme at the end of the chapter):

47

E RS R/W D7 D6 D5 D4 D3 D2 D1 D0

ctrlport.6 ctrlport.4 ctrlport.5 dataport.7 dataport.6 dataport.5 dataport.4 dataport.3 dataport.2 dataport.1 dataport.0

Requires Example

Nothing.
Lcd8_Init(&PORTB, &PORTC);

Lcd8_Out

Prototype Returns Description

void Lcd8_Out(unsigned short row, unsigned short col, char *text); Nothing. Prints text on LCD at specified row and column (parameter row and col). Both string variables and literals can be passed as text.

Requires Example

Ports with LCD must be initialized. See Lcd8_Config or Lcd8_Init. Print Hello! on LCD at line 1, char 3:
Lcd8_Out(1, 3, "Hello!");

Lcd8_Out_Cp

Prototype Returns Description

void Lcd8_Out_Cp(char *text); Nothing. Prints text on LCD at current cursor position. Both string variables and literals can be passed as text. Ports with LCD must be initialized. See Lcd8_Config or Lcd8_Init. Print Here! at current cursor position:
Lcd8_Out_Cp("Here!");

Requires Example

Lcd8_Chr

Prototype Returns

void Lcd8_Chr(unsigned short row, unsigned short col, char character); Nothing.

48

Description

Prints character on LCD at specified row and column (parameter row and col). Both variables and literals can be passed as character.

Requires Example

Ports with LCD must be initialized. See Lcd8_Config or Lcd8_Init. Print i on LCD at line 2, char 3:
Lcd8_Out(2, 3, 'i');

Lcd8_Chr_Cp

Prototype Returns Description

void Lcd8_Chr_Cp(char character); Nothing. Prints character on LCD at current cursor position. Both variables and literals can be passed as character.

Requires Example

Ports with LCD must be initialized. See Lcd8_Config or Lcd8_Init. Print e at current cursor position:
Lcd8_Chr_Cp('e');

Lcd8_Cmd

Prototype Returns Description

void Lcd8_Cmd(unsigned short command); Nothing. Sends command to LCD. You can pass one of the predefined constants to the function. The complete list of available commands is below.

Requires Example

Ports with LCD must be initialized. See Lcd8_Config or Lcd8_Init. Clear LCD display:
Lcd8_Cmd(Lcd_Clear);

Available LCD Commands

LCD Command

Purpose Move cursor to 1st row Move cursor to 2nd row Move cursor to 3rd row Move cursor to 4th row Clear display Return cursor to home position, returns a shifted display to original position. Display data RAM is unaffected.

LCD_FIRST_ROW LCD_SECOND_ROW LCD_THIRD_ROW LCD_FOURTH_ROW LCD_CLEAR LCD_RETURN_HOME

49

LCD_CURSOR_OFF LCD_UNDERLINE_ON LCD_BLINK_CURSOR_ON LCD_MOVE_CURSOR_LEFT LCD_MOVE_CURSOR_RIGHT LCD_TURN_ON LCD_TURN_OFF LCD_SHIFT_LEFT LCD_SHIFT_RIGHT

Turn off cursor Underline cursor on Blink cursor on Move cursor left without changing display data RAM Move cursor right without changing display data RAM Turn LCD display on Turn LCD display off Shift display left without changing display data RAM Shift display right without changing display data RAM

Library Examples
Default Pin Configuration
Use Lcd8_Init for default pin settings (see the first figure below).

char *text = "mikroElektronika"; void main() { TRISB = 0; TRISC = 0; Lcd8_Init(&PORTB, &PORTC); Lcd8_Cmd(LCD_CURSOR_OFF); Lcd8_Out(1, 1, text); }

// // // // //

PORTB is output PORTC is output Initialize LCD at PORTB and PORTC Turn off cursor Print text on LCD

LCD HW connection by default initialization (using Lcd8_Init)

50

Keypad Library
mikroC provides library for working with 4x4 keypad; routines can also be used with 4x1, 4x2, or 4x3 keypad. Check the connection scheme at the end of the topic.

Library Routines

Keypad_Init Keypad_Read Keypad_Released

Keypad_Init

Prototype Returns Description

void Keypad_Init(unsigned *port); Nothing. Initializes port to work with keypad. The function needs to be called before using other routines from Keypad library.

Requires Example

Nothing.
Keypad_Init(&PORTB);

Keypad_Read

Prototype Returns Description

unsigned short Keypad_Read(void); 1..16, depending on the key pressed, or 0 if no key is pressed. Checks if any key is pressed. Function returns 1 to 16, depending on the key pressed, or 0 if no key is pressed.

Requires Example

Port needs to be appropriately initialized; see Keypad_Init.


kp = Keypad_Read();

51

Keypad_Released

Prototype Returns Description

unsigned short Keypad_Released(void); 1..16, depending on the key. Call to Keypad_Released is a blocking call: function waits until any key is pressed and released. When released, function returns 1 to 16, depending on the key.

Requires Example

Port needs to be appropriately initialized; see Keypad_Init.


kp = Keypad_Released();

Library Example
The following code can be used for testing the keypad. It supports keypads with 1 to 4 rows and 1 to 4 columns. The code returned by the keypad functions (1..16) is transformed into ASCII codes [0..9,A..F]. In addition, a small single-byte counter displays the total number of keys pressed in the second LCD row.

unsigned short kp, cnt; char txt[5]; void main() { cnt = 0; Keypad_Init(&PORTC); Lcd_Init(&PORTB); Lcd_Cmd(LCD_CLEAR); Lcd_Cmd(LCD_CURSOR_OFF); Lcd_Out(1, 1, "Key :"); Lcd_Out(2, 1, "Times:"); do { kp = 0; //--- Wait for key to be pressed do //--- un-comment one of the keypad reading functions kp = Keypad_Released(); //kp = Keypad_Read(); while (!kp); cnt++; //--- prepare value for output if (kp > 10)

// Initialize LCD on PORTC // Clear display // Cursor off

52

kp += 54; else kp += 47; //--- print it Lcd_Chr(1, 10, WordToStr(cnt, Lcd_Out(2, 10, } while (1); }//~! on LCD kp); txt); txt);

HW Connection

4x4 Keypad connection scheme

53

ADC Library
ADC (Analog to Digital Converter) module is available with a number of PIC MCU models. Library function Adc_Read is included to provide you comfortable work with the module.

Adc_Read

Prototype Returns Description

unsigned Adc_Read(unsigned short channel); 10-bit unsigned value read from the specified channel. Initializes PICs internal ADC module to work with RC clock. Clock determines the time period necessary for performing AD conversion (min 12TAD). Parameter channel represents the channel from which the analog value is to be acquired. Refer to the appropriate datasheet for channel-to-pin mapping.

Requires

PIC MCU with built-in ADC module. You should consult the Datasheet documentation for specific device (most of devices from the P16 and P18 family have it). Before using the function, be sure to configure the appropriate TRISA bits to designate the pins as input. Also, configure the desired pin as analog input, and set Vref (voltage reference value).

Example

unsigned tmp; ... tmp = Adc_Read(1);

/* read analog value from channel 1 */

Library Example
This code snippet reads analog value from channel 2 and displays it on PORTD (lower 8 bits) and PORTB (2 most significant bits).

unsigned int temp_res; void main() { ADCON1 = 0x80; TRISA = 0xFF;

// Configure analog inputs and Vref // PORTA is input

54

TRISB TRISD

= 0x3F; = 0;

// Pins RB7, RB6 are outputs // PORTD is output

do { temp_res = Adc_Read(2); // Get results of AD conversion PORTD = temp_res; // Send lower 8 bits to PORTD PORTB = temp_res >> 2; // Send 2 most significant bits to RB7, RB6 } while(1); }

HW Connection

ADC HW connection

55

PWM Library
CCP module is available with a number of PICmicros. mikroC provides library which simplifies using PWM HW Module. Note: Certain PICmicros with two or more CCP modules, such as P18F8520, require you to specify the module you want to use. Simply append the number 1 or 2 to a Pwm. For example, Pwm2_Start(); Also, for the sake of backward compabitility with previous compiler versions and easier code management, MCU's with multiple PWM modules have PWM library which is identical to PWM1 (i.e. you can use PWM_Init() instead of PWM1_Init
() to initialize CCP1).

Library Routines

Pwm_Init Pwm_Change_Duty Pwm_Start Pwm_Stop

Pwm_Init

Prototype Returns Description

void Pwm_Init(unsigned long freq); Nothing. Initializes the PWM module with duty ratio 0. Parameter freq is a desired PWM frequency in Hz (refer to device data sheet for correct values in respect with Fosc). This routine needs to be called before using other functions from PWM Library.

Requires Example

MCU must have CCP module. Initialize PWM module at 5KHz:


Pwm_Init(5000);

Pwm_Change_Duty

56

Prototype Returns Description

void Pwm_Change_Duty(unsigned short duty_ratio); Nothing. Changes PWM duty ratio. Parameter duty takes values from 0 to 255, where 0 is 0%, 127 is 50%, and 255 is 100% duty ratio. Other specific values for duty ratio can be calculated as (Percent*255)/100.

Requires

MCU must have CCP module. Pwm_Init must be called before using this routine.

Example

Set duty ratio to 75%:


Pwm_Change_Duty(192);

Pwm_Start

Prototype Returns Description Requires

void Pwm_Start(void); Nothing. Starts PWM. MCU must have CCP module. Pwm_Init must be called before using this routine.

Example

Pwm_Start();

Pwm_Stop

Prototype Returns Description Requires

void Pwm_Stop(void); Nothing. Stops PWM. MCU must have CCP module. Pwm_Init must be called before using this routine. Pwm_Start should be called before using this routine, otherwise it will have no effect as the PWM module is not running.

Example

Pwm_Stop();

57

Library Example
The example changes PWM duty ratio on pin RC2 continually. If LED is connected to RC2, you can observe the gradual change of emitted light.

// microcontroller : P16F877A // PWM module is set on RC2. unsigned short j, oj; void InitMain() { PORTB = 0; TRISB = 0; ADCON1 = 6; PORTA = 255; TRISA = 255; PORTC = 0xFF; TRISC = 0; Pwm_Init(5000); }//~ void main() { InitMain(); j = 80; oj = 0; Pwm_Start();

// Set PORTB to 0 // PORTB is output // All ADC pins to digital I/O // PORTA is input // Set PORTC to $FF // PORTC is output // Initialize PWM module

// Initial value for j // oj will keep the 'old j' value // Start PWM

// Endless loop while (1) { // button on RA0 pressed if (Button(&PORTA, 0,1,1)) j++ ; // increment j // button on RA1 pressed if (Button(&PORTA, 1,1,1)) j-- ; // decrement j if (oj != j) { Pwm_Change_Duty(j); oj = j; PORTB = oj; } Delay_ms(200); } } // If change in duty cycle requested, // set new duty ratio, // memorize it, // and display on PORTB // Slow down a bit

HW Connection

58

PWM demonstration

59

USART Library
USART hardware module is available with a number of PICmicros. mikroC USART Library provides comfortable work with the Asynchronous (full duplex) mode. You can easily communicate with other devices via RS232 protocol (for example with PC, see the figure at the end of the topic RS232 HW connection). You need a PIC MCU with hardware integrated USART, for example PIC16F877. Then, simply use the functions listed below.

Library Routines

Usart_Init Usart_Data_Ready Usart_Read Usart_Write

Certain PICmicros with two USART modules, such as P18F8520, require you to specify the module you want to use. Simply append the number 1 or 2 to a function name. For example, Usart_Write2(); Also, for the sake of backward compabitility with previous compiler versions and easier code management, MCU's with multiple USART modules have USART library which is identical to USART1 (i.e. you can use Usart_Init() instead of Usart_Init1() for Usart operations).

Usart_Init

Prototype Returns Description

void Usart_Init(const unsigned long baud_rate); Nothing. Initializes hardware USART module with the desired baud rate. Refer to the device data sheet for baud rates allowed for specific Fosc. If you specify the unsupported baud rate, compiler will report an error.

Requires

You need PIC MCU with hardware USART.


Usart_Init needs to be called before using other functions from

USART Library. Example This will initialize hardware USART and establish the communication at 2400 bps:

60

Usart_Init(2400);

Usart_Data_Ready

Prototype Returns Description Requires

unsigned short Usart_Data_Ready(void); Function returns 1 if data is ready or 0 if there is no data. Use the function to test if data in receive buffer is ready for reading. USART HW module must be initialized and communication established before using this function. See Usart_Init.

Example

If data is ready, read it:


int receive; ... if (Usart_Data_Ready()) receive = Usart_Read;

Usart_Read

Prototype Returns Description

unsigned short Usart_Read(void); Returns the received byte. If byte is not received, returns 0. Function receives a byte via USART. Use the function Usart_Data_Ready to test if data is ready first.

Requires

USART HW module must be initialized and communication established before using this function. See Usart_Init.

Example

If data is ready, read it:


int receive; ... if (Usart_Data_Ready()) receive = Usart_Read();

Usart_Write

Prototype

void Usart_Write(unsigned short data);

61

Returns Description Requires

Nothing. Function transmits a byte (data) via USART. USART HW module must be initialized and communication established before using this function. See Usart_Init.

Example

int chunk = 0x1E; Usart_Write(chunk);

/* send chunk via USART */

Library Example
The example demonstrates simple data exchange via USART. When PIC MCU receives data, it immediately sends the same data back. If PIC is connected to the PC (see the figure below), you can test the example from mikroC terminal for RS232 communication, menu choice Tools Terminal.
unsigned short i; void main() { // Initialize USART module (8 bit, 2400 baud rate, no parity bit..) Usart_Init(2400); do { if (Usart_Data_Ready()) { i = Usart_Read(); Usart_Write(i); } } while (1); }//~!

// If data is received // Read the received data // Send data via USART

HW Connection

62

RS232 HW connection

63

M. Abdelati, Fall 2007/8

Electrical & Computer Engineering Department Microcontrollers & Microprocessors Based Systems ECOM 4315 Midterm Exam Duration 80 min Name: .... Surname: .... ID: ... Phone or email contact: ..

Q 1 2 3 4 5 8 8 8 8 8

Grade

4 10 Bonus Total 50

Directions: Use your engineering judgment to assume/correct any missing/wrong information and don't interrupt the instructor for any reason. The exam is closed books and notes (instructions sheet is allowed). Be sure that you have a total of 6 questions. Attempt to solve all questions While extra correct information in your answers is discarded, you will lose a considerable amount of points if you provide wrong extra information. Bonus Policy: There is 2 point bonus for each student. You will lose the bonus if you 1. 2. 3. 4. 5. 6. 7. 8. ask any question of any type, barrow pencil, eraser, calculator ... etc., set in a wrong exam room, leave the room during the exam period, show up your mobile phone, delay the submission of your answer sheets, don't answer each question in its allocated space (separate page), or ask for paper revision and don't get extra points.

You are allowed to call the instructor once at most during the first 15 minutes. Therefore, if you want to sacrifice with the bonus and require more explanation about an exam problem then you are advised to read all exam problems and collect your questions before calling the instructor. Remember that while the instructor does not answer silly questions, you will lose the bonus for any question of any type. Your grade will be inversely proportional to the complexity of your approach. Your total grade has a saturation value of 100%. Any trial of cheating will trigger a disciplinary action which insures a fail in the course at least. Good luck!

64

M. Abdelati, Fall 2007/8

[1] Sketch a figure for a microcontroller system in which there are 2 LEDs and 2 push buttons and a 7segment display are interfaced to a PIC16F84A microcontroller (use minimum extra components).

[2] Refer to the following Simulator: (a) What is the value of FSR register?

(b) What is the content of the general purpose register whose address is 15h

(c) What is the address of the next instruction to be executed?

(d) What is the value of the zero flag?

(e) What will happen when you execute the next instruction?

65

M. Abdelati, Fall 2007/8

[3] Referring to PIC16F84A microcontroller, answer the following: (a) On reset, what will be the value of the program counter (PC)?

[4] convert the folowing assembly code to machine language and fill the resultant code in the memory model shown below. ORG 10h MOVF PORTA,W MOVWF PORTB GOTO LOOP END address 0000 content

LOOP

(b) On interrupt, what will be the value of the program counter (PC)?

(c) What is the width of the instruction bus?

0001 0002 0003

(d) What is the maximum program size?

0004 0005 0006 0007

(e) What is the difference between an instruction and a directive in assembly language?

0008 0009 000A 000B 000C 000D

(f) What are the registers involved during writing to the EEPROM?

000E 000F 0010 0011 0012

(g) Why the register TMR0 is also called Counter register?

0013 0014 0015 0016 0017

(h) What is the most probable execution time of PIC16F84A instructions. (given that its oscillator frequency is 4 MHz)

0018 0019 001A

66

M. Abdelati, Fall 2007/8

[5] The following program is described at class under the name "Ramadan2".
LIST P=PIC16F84A #INCLUDE <P16F84A.INC> __CONFIG _XT_OSC&_PWRTE_ON&_CP_OFF&_WDT_OFF ORG GOTO 0X000 START

(a) What is the function of this program?

(b) If the constant in the instruction pointed by the arrow is replaced by (.254), then the program will not function properly. However, if it is replaced by (.253) the program functions as required! What is the cause of this bug? Describe a method to resolve this bug?

ORG 0X004 RETFIE START BSF BCF BCF MOVLW XORWF CALL GOTO STATUS,RP0 TRISB,0 STATUS,RP0 01h PORTB, F DELAY LOOP ;BANK1 ;RB0 IS OUTPUT ;BANK0

LOOP

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DELAY MOVLW .255 MOVWF 0CH LOOP1 NOP MOVLW .255 MOVWF 0DH LOOP0 NOP DECFSZ 0DH GOTO LOOP0 DECFSZ 0CH GOTO LOOP1 RETURN ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; END

[6] Write assembly language instructions to clear the general purpose registers of the PIC16F84A microcontroller (dont write the whole program).

67

M. Abdelati, Fall 2007/8

Electrical & Computer Engineering Department Microcontrollers & Microprocessors Based Systems ECOM 4315 Final Exam Q Duration 120 min
1 2

Grade 10 10 10 20 2

Name: .... Surname: .... ID: ... Phone or email contact: ..

3 4

5 Bonus Total 50

Directions: Use your engineering judgment to assume/correct any missing/wrong information and don't interrupt the instructor for any reason. The exam is closed books and notes (instructions sheet is allowed). Be sure that you have a total of 5 questions. Attempt to solve all questions While extra correct information in your answers is discarded, you will lose a considerable amount of points if you provide wrong extra information. Bonus Policy: There is 2 point bonus for each student. You will lose the bonus if you 1. 2. 3. 4. 5. 6. 7. 8. ask any question of any type, barrow pencil, eraser, calculator ... etc., set in a wrong exam room, leave the room during the exam period, show up your mobile phone, delay the submission of your answer sheets, don't answer each question in its allocated space (separate page), or ask for paper revision and don't get extra points.

You are allowed to call the instructor once at most during the first 15 minutes. Therefore, if you want to sacrifice with the bonus and require more explanation about an exam problem then you are advised to read all exam problems and collect your questions before calling the instructor. Remember that while the instructor does not answer silly questions, you will lose the bonus for any question of any type. Your grade will be inversely proportional to the complexity of your approach. Your total grade has a saturation value of 100%. Any trial of cheating will trigger a disciplinary action which insures a fail in the course at least. Good luck!

68

M. Abdelati, Fall 2007/8

[1] a) Sketch the pin diagram of the PIC16F84A

b) Sketch a figure which illustrates the internal architecture of the PIC16F84A. Dont forget to indicate the size of busses.

c) Write down 5 tools we have used during the course and indicate the function of each tool.

d) Write an assembly language program to add the constant hAA to the contents of File h36 and store the result in File h40. Remember that File means data memory location.

69

M. Abdelati, Fall 2007/8

[2] Assuming that you have found a 1-second delay subroutine (OneSecond) for the PIC16F84 microcontroller, write a macro that would give a 1-minute delay.

[3] At class we discussed the program shown below. Modify the program so that the LED will flash for 1 minute after the termination of timer countdown.

70

M. Abdelati, Fall 2007/8

[4] In an open-loop speed control of a DC motor application it is desired to specify the set point using 8 dip switches so that the specified speed will cover the range [0-255]. Assume that the controller will be based on PIC16F84A and will utilize PWM with period equals 255 micro second. a) Sketch the system hardware. b) Sketch the PWM signal when the set speed = 150 . c) Write the necessary software.

71

M. Abdelati, Fall 2007/8

[5] a) Have you attended the department workshop last month.?

b) If you answered yes in part a, have you submitted a report?

c) If you answered yes in part b, write down 3 comments about the workshop.

d) Have you submitted a report summarizing the course material?

e) Who is your partner (if any)? What part of that assignment you have done by yourself and what part is done by your partner?

f) Have you submitted a CD?

g) If yes, describe how you organized it.

72

M. Abdelati, Fall 2007/8

This question is for computer engineering students. It is considered as part of question 1 and hence its grade will be included there. Below is a segment of code written in PIC16F84 assembly language:
movlw d20 movwf h3F movlw d250 addlw -1 btfss STATUS,Z goto LOOP2 decf h3F,f btfss STATUS,Z goto LOOP1 sleep

LOOP1 LOOP2

(i) Explain what this routine does and suggest its most likely purpose.

(ii) Determine the execution time of the complete program segment, assuming a clock rate of 4 MHz.

73

Prof. M. Abdelati, Fall 2008/9

Electrical & Computer Engineering Department Microcontrollers & Microprocessors Based Systems ECOM 4315 Midterm Exam Duration 80 min Name: ....
1 Q 10 2 2 30 Bonus Total 40 Grade

Surname: .... ID: ... Phone or email contact: ..

Directions: Use your engineering judgment to assume/correct any missing/wrong information and don't interrupt the instructor for any reason. The exam is closed books and notes (instructions sheet is allowed). Be sure that you have a total of 6 questions. Attempt to solve all questions While extra correct information in your answers is discarded, you will lose a considerable amount of points if you provide wrong extra information. Bonus Policy: There is 2 point bonus for each student. You will lose the bonus if you 1. 2. 3. 4. 5. 6. 7. 8. ask any question of any type, barrow pencil, eraser, calculator ... etc., set in a wrong exam room, leave the room during the exam period, show up your mobile phone, delay the submission of your answer sheets, don't answer each question in its allocated space (separate page), or ask for paper revision and don't get extra points.

You are allowed to call the instructor once at most during the first 15 minutes. Therefore, if you want to sacrifice with the bonus and require more explanation about an exam problem then you are advised to read all exam problems and collect your questions before calling the instructor. Remember that while the instructor does not answer silly questions, you will lose the bonus for any question of any type. Your grade will be inversely proportional to the complexity of your approach. Your total grade has a saturation value of 100%. Any trial of cheating will trigger a disciplinary action which insures a fail in the course at least. Good luck!

74

Prof. M. Abdelati, Fall 2008/9

[1] Sketch a figure for a simple circuit used to test a PIC16F84A microcontroller. Write the associated software program.

75

Prof. M. Abdelati, Fall 2008/9

[2] Referring to PIC16F84A, answer the following: 2.1. At what addresses are the Reset Vector and Interrupt Vector?

2.2.How many words of program memory are available in the PIC?

2.3.Which registers set the directions of the digital I/O pins?

2.4.How many registers are hard-wired across the two banks?

2.5.What does the following opcode do? 00 0000 0110 0000

2.6.How many different prescale assignments are available for Timer0?

2.7.Where are the bank select bits?

2.8.What is W and STATUS/Z after the following instruction sequence? MOVLW 1 SUBLW 1

2.9.What is the difference between a microprocessor and a microcontroller?

2.10. How many different interrupt sources does the PIC have?

2.11. What is the difference between machine code and assembly code?

2.12. Write a two-instruction sequence to take the twos complement of PortB.

76

Prof. M. Abdelati, Fall 2008/9

2.13. The following code has an infinite loop. Why? MOVLW 3 MOVWF PORTB LOOP: DECFSZ PORTB, W GOTO LOOP

2.14. What does RISC stand for?

2.15. The following code was written to copy PORTB to TRISA. Find the bug. MOVF MOVWF PORTB, W TRISA

2.16. The following routine toggles RB2 after an interrupt on RB0/INT. Find the bug. ORG MOVWF SWAPF MOVWF BCF MOVLW XORWF BCF SWAPF MOVWF SWAPF SWAPF RETURN 0X004 0Eh STATUS,W 0Fh STATUS,RP0 4 PORTB,F INTCON,INTF 0Fh,W STATUS 0EH,F 0EH,W

2.17. What is the Harvard architecture?

2.18. Suppose STATUS = 0x10. Which bank is selected?

2.19. Where is the configuration word stored?

2.20. What is the machine code for the instruction CLR PORTA, F? Give your answer in hex. What register will this clear if STATUS = 0011 1000?

77

Prof. M. Abdelati & Mr. M. Almobaied Fall 2008/9

Electrical Engineering Department Microcontrollers & Microprocessors Based Systems ECOM 4315 Final Exam Q Duration 120 min 1 7
2 7 6 10 10

Grade

Name: .... Surname: .... ID: ... Phone or email contact: ..

3 4 5

6 10 Bonus Total 50

Directions: Use your engineering judgment to assume/correct any missing/wrong information and don't interrupt the instructor for any reason. The exam is closed books and notes (instructions sheet is allowed). Be sure that you have a total of 6 questions. Attempt to solve all questions While extra correct information in your answers is discarded, you will lose a considerable amount of points if you provide wrong extra information. Bonus Policy: There is 2 point bonus for each student. You will lose the bonus if you 1. 2. 3. 4. 5. 6. 7. 8. ask any question of any type, barrow pencil, eraser, calculator ... etc., set in a wrong exam room, leave the room during the exam period, show up your mobile phone, delay the submission of your answer sheets, don't answer each question in its allocated space (separate page), or ask for paper revision and don't get extra points.

You are allowed to call the instructor once at most during the first 15 minutes. Therefore, if you want to sacrifice with the bonus and require more explanation about an exam problem then you are advised to read all exam problems and collect your questions before calling the instructor. Remember that while the instructor does not answer silly questions, you will lose the bonus for any question of any type. Your grade will be inversely proportional to the complexity of your approach. Your total grade has a saturation value of 100%. Any trial of cheating will trigger a disciplinary action which insures a fail in the course at least. Good luck!

78

Prof. M. Abdelati & Mr. M. Almobaied Fall 2008/9

[1] The following questions are True-False questions referred to PIC16F84A. If the statement is true, circle T, and go to the next question. If the statement is false, circle F, write the specific portion of the statement that makes it false in space A, and rewrite the incorrect portion so that it is true in space B. T F 1. The instruction bus consists of 14 bit . A_______________________________ B_______________________________

2. EECON2 is an existing register with 8 bits used in writing in the EEPROM. A_______________________________ B_______________________________

3. Disabling the GIE the pc will never reach the interrupt subroutine. A_______________________________ B_______________________________

4. To read from the EEPROM we need to use ( EEADR , EEDATA , EECON1, EECON2 ). A_______________________________ B_______________________________

5. we can write any code in assembly language in the microC without any restrictions. A_______________________________ B_______________________________

6. The addresses of EEPROM memory starts at location 0x00h & extend to 0x3f but consists of 64 byte. A_______________________________ B_______________________________

7. Using Macros are preferable than using subroutines. A_______________________________ B_______________________________

79

Prof. M. Abdelati & Mr. M. Almobaied Fall 2008/9

[2] Referring to PIC16F84A, choose the most suitable answer:

1. The external recourses of the interrupts are:


a. b. c. d. RB0 & RB4-7 TIMER ZERO Finishing writing on the EEPROM. All the above is true.

2. To disable all the interrupts we can


a. b. c. d. put 1 in the GIE . put 0 in the GIE . disable EEIE , T0IE , RBIE & INTIE a&c

3. To select the prescaler for the WDT we assign (PSA) to be :


a. b. c. d. 1 0 0xF h Don't care.

4. The instruction decfsz is . cycle instruction.


a. b. c. d. one two one or two depending on the result one or two depending on the initial value .

5. The indirect addressing is accomplished by using :


a. b. c. d. FSR register INDF register Both a &b None of the above.

6. Machine code is:


a. b. c. d. The Instruction decoder in the processor that interprets the operation code of the instruction. Assembly-level symbolic source code. The binary address of the cell in program memory an instruction lies. The binary code in Program memory that the processor executes.

7. A subroutine is:
a. b. c. d. A program that links software routines into one executable program. A program that allows you to enter the source program as a file on disc. A program module that performs a well defined function. A program that translates from assembly-level source to machine code.

80

Prof. M. Abdelati & Mr. M. Almobaied Fall 2008/9

[3] Write a PIC assembly-level code to compare the two numbers NUMBER1 in File h30 and NUMBER2 in File h31 and if these are equal add 6 onto DATUM in File h40, otherwise decrement it.

[4] Write a macro which fills the even bytes and the odd bytes of the General Purpose registers with the numbers 0x55h and 0xAAh respectively.

81

Prof. M. Abdelati & Mr. M. Almobaied Fall 2008/9

[5] DC servo motors are characterized by simplicity in speed and position control applications. They are classified into two categories depending on the feedback signal returned from the motor. One type has a tachometer which returns back a voltage signal depending on the rotation speed while the other type has an encoder which returns back pulses depending on the rotation angle. Show how you can interface each type (separately) to PIC16F84A. Show the hardware only and dont write any software.

82

Prof. M. Abdelati & Mr. M. Almobaied Fall 2008/9

[6] A simple alarm system has 4 zone inputs connected to PIC16F84A. If any one of these inputs is activated a bell will sound for 5 minutes and the zone number will be displayed on a 7-segment display. a. Provide a hardware design for the system. b. Write a C code to implement the required functionality of the system.

83

Prof. M. Abdelati, Summer 2008/9

Electrical Engineering Department Microcontrollers & Microprocessors Based Systems ECOM 4315
Midterm Exam Duration 90 min Q Grade 10 10 10 10 2 30 1 2

Name: .... Surname: .... ID: ... Phone or email contact: ..

3 4
Total

Bonus

Directions: Use your engineering judgment to assume/correct any missing/wrong information and don't interrupt the instructor for any reason. The exam is closed books and notes (instructions sheet is allowed). Be sure that you have a total of 4 questions. Attempt to solve all questions While extra correct information in your answers is discarded, you will lose a considerable amount of points if you provide wrong extra information. Bonus Policy: There is 2 point bonus for each student. You will lose the bonus if you 1. 2. 3. 4. 5. 6. 7. 8. ask any question of any type, barrow pencil, eraser, calculator ... etc., set in a wrong exam room, leave the room during the exam period, show up your mobile phone, delay the submission of your answer sheets, don't answer each question in its allocated space (separate page), or ask for paper revision and don't get extra points.

You are allowed to call the instructor once at most during the first 15 minutes. Therefore, if you want to sacrifice with the bonus and require more explanation about an exam problem then you are advised to read all exam problems and collect your questions before calling the instructor. Remember that while the instructor does not answer silly questions, you will lose the bonus for any question of any type. Your grade will be inversely proportional to the complexity of your approach. Your total grade has a saturation value of 100%. Any trial of cheating will trigger a disciplinary action which insures a fail in the course at least. Good luck!

84

Prof. M. Abdelati, Summer 2008/9

[1] Sketch the circuit diagram of a microcontroller system in which there are 2 LEDs and 2 push buttons and two 7-segment displays are interfaced to a PIC16F84A microcontroller.

[2] The following record exists is a hex file :0800080009008316B8308100E5 Extract the assembly language instructions from the record given that it has the following format Record Mark ':' 1-byte Machine Code (hexa) Load Record Length 1-byte Record Type 1-byte Information or Data n-bytes

Offset 2-bytes

Chick Sum 1-byte

Machine Code (binary)

Assembly code

85

Prof. M. Abdelati, Summer 2008/9

86

Prof. M. Abdelati, Summer 2008/9

[3] Write two macros called EEread and EEwrite that allows reading and writing from the EEPROM. The EEread macro takes the address as an argument and returns the data in the work register. The EEwrite macro takes the address and data as arguments.
; Ex7 (EE_a) EEPROM handling applica LIST P=PIC16F84A #INCLUDE <P16F84A.INC> __CONFIG _XT_OSC&_PWRTE_ ORG 0X000 GOTO START ORG 0X004 RETFIE START BSF CLRF BSF MOVLW MOVWF BCF MOVLW MOvWF LOOP0 BTFSS GOTO MOVF MOVWF BSF BCF BCF BSF MOVLW MOVWF MOVLW MOVWF BSF BSF LOOP1 BTFSS GOTO BCF CLRF LOOP2 BTFSC GOTO BSF BSF BCF BCF MOVF MOVWF LOOP3 GOTO END STATUS,RP0 TRISB TRISB,0 B'00011111' TRISA STATUS,RP0 07h EEADR PORTB,0 LOOP0 PORTA,W EEDATA STATUS,RP0 INTCON,GIE EECON1,EEIF EECON1,WREN 55h EECON2 0AAh EECON2 EECON1,WR INTCON,GIE EECON1,EEIF LOOP1 STATUS,RP0 EEDATA PORTB,0 LOOP2 STATUS,RP0 EECON1,RD TRISB,0 STATUS,RP0 EEDATA,W PORTB LOOP3

87

Prof. M. Abdelati, Summer 2008/9

[4]

; Ex5 (Counter a) Counter on RA4/T0CKI from 00-FF ; No Interrupt is used here LIST P=PIC16F84A #INCLUDE <P16F84A.INC> __CONFIG _XT_OSC&_PWRTE_ON&_CP_OFF&_WDT_OFF ORG 0X000 GOTO START ORG 0X004 RETFIE START BSF MOVLW MOVWF CLRF MOVLW MOVWF BCF CLRF MOVF MOVWF GOTO END STATUS,RP0 B'10111000' OPTION_REG TRISB B'00011111' TRISA STATUS,RP0 TMR0 TMR0,W PORTB LOOP ; BANK 1 ; xx11 1xxx ; PORT B IS OUTPUT ; PORT A IS INPUT ; BANK0

LOOP

Modify the hardware and software of the example shown above so that the same task is done using interrupt mechanism.

88

Prof. M. Abdelati, Summer 2008/9

Electrical Engineering Department Microcontrollers & Microprocessors Based Systems ECOM 4315
Final Exam Duration 120 min 1 2 3 Q 10 10 10 10 10 2 50 Grade

Name: .... Department: .... ID: ... Phone or email contact: ..

4 5
Total

Bonus

Directions: Use your engineering judgment to assume/correct any missing/wrong information and don't interrupt the instructor for any reason. The exam is closed books and notes (instructions sheet is allowed). Be sure that you have a total of 5 questions. Attempt to solve all questions While extra correct information in your answers is discarded, you will lose a considerable amount of points if you provide wrong extra information. Bonus Policy: There is 2 point bonus for each student. You will lose the bonus if you 1. 2. 3. 4. 5. 6. 7. 8. ask any question of any type, barrow pencil, eraser, calculator ... etc., set in a wrong exam room, leave the room during the exam period, show up your mobile phone, delay the submission of your answer sheets, don't answer each question in its allocated space (separate page), or ask for paper revision and don't get extra points.

You are allowed to call the instructor once at most during the first 15 minutes. Therefore, if you want to sacrifice with the bonus and require more explanation about an exam problem then you are advised to read all exam problems and collect your questions before calling the instructor. Remember that while the instructor does not answer silly questions, you will lose the bonus for any question of any type. Your grade will be inversely proportional to the complexity of your approach. Your total grade has a saturation value of 100%. Any trial of cheating will trigger a disciplinary action which insures a fail in the course at least. Good luck!

89

Prof. M. Abdelati, Summer 2008/9

[1] Sketch the circuit diagram of a PIC16F877A microcontroller system in which the microcontroller is interfaced to the following peripherals: sn 1 2 3 4 5 6 7 Item Hexadecimal keypad. Bidirectional DC motor 48 V LED Toggle switch LCD 4 Multiplexed Seven Segment Displays Temperature sensor

90

Prof. M. Abdelati, Summer 2008/9

[2] Write a subroutine which takes an 8-bit number in the work register. The input number has only one single non-zero bit. The subroutine should return a number from 0 to 7 indicating the position of the non zero bit. For example, if the input is 00010000 then the output is 4. The output is returned in the work register.

91

Prof. M. Abdelati, Summer 2008/9

[3]

a) A student has connected a dipswitch to RB like this: What are your comments?

b) Assume that you have a Mico C project files folder i) What are the extensions of the essential files?

ii) If you want to rename the project, can you rename those essential files only? If no, what must be done?

[4] What are the course headlines? And what are the contributions of the students?

[5] (For EE students only) You have 2 push buttons connected to A0 and A1 of a 16F84A microcontroller and they will be used to enter a number from 0 to 100 into a variable x. The input A1 is used for decreasing while A0 is used for increasing the input number. Show the Mico C code. [5] (For CE students only) Propose a method to test the serial port of PIC16F877 if your PC doesnt have a serial port. Show the circuit diagram and write the required program.

92

You might also like