Home

Lecture Notes

image

Contents

1. P4 Adjustment 5K i ERROR 8 Mhz LCD HW connection by default initialization using Lcd_Init 46 47 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 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 m Config Init m Lcd8 Out m cd8 Out Cp Lcd8 Chr cd8 Chr Lcd8 Config Prototype void Lcd8 Config unsigned short ctrlport unsigned short dataport unsigned short RS unsigned short EN unsigned short WR unsigned short 07 unsigned short D6 unsigned short D5 unsigned short D4 unsigned short D3 unsigned short D2 unsigned short 01 unsigned short D0 Returns Nothing Description Initializes LCD at Control port ctriport and Data port dataport with pin settings you specify Parameters RS EN WR need to be in range 0 7 Pa
2. 3 79 16 sk 4 15 OSC2 CLKOUT Wee 5 m 14 U 13 gt REE RE2 11 RES 5 10 RES FIGURE 1 1 PIC16F84A BLOCK DIAGRAM EEPROM Data Memory Memory 5 _ 1K x 14 dic gt Daah RAM Addr 0000 Program 13 bit C P U zi Data memory Address bus Address bus memory Sap Tier IFFF 14 bil 8 bit Instruction bus Data bus a 1 6 1 Data memory Address Address INDF INDF 80h TMRQ OPTION 81h 2 PCL PCL 82 STATUS STATUS 83h ESR FSR 84h O5h PORTA 85 06h 86h 07h 87h O8h EEDATA EECON1 88h 09h 89h OAh PCLATH PCLATH 8Ah 0Bh 8Bh och 8Ch 68 bytes RAM a memory General Purpose 4Fh z 50h DOh FFh BlankO Blank1 TABLE 2 1 SPECIAL FUNCTION REGISTER FILE SUMMARY Value on Details Name Bit 7 Bit amp Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Power on RESET Pag Bank ODh INDF Uses contents of FSR address Data Memory nat a physical register TMRO B bit Real Time Clock Counter PCL Low Order 8 bits of the Program Counter 00900 meme S Ez fom maroon me Fe
3. Addressing 0000 Program 10 U zm Data memory Address bus Address bus Memory FFF 14 bit 8 bit Instruction bus Data bus FIGURE 2 3 DIRECT INDIRECT ADDRESSING Direct Addressing Indirect Addressing From Opcode FSR Select Select m Select Select Data Memory Bank Bank 1 Note 1 For memory map detail see Figure 2 2 2 Maintain as clear for upward compatibility with future products 3 Not implemented 2 3 2 Status register REGISTER 2 1 bit 7 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit STATUS REGISTER ADDRESS 03h 83h R N RAN 0 R N D R 1 R 1 RANV x RAW x Unimplemented Maintain as o RPO Register Bank Select bits used for direct addressing 01 Bank 1 808 FFh oo Bank 0 00h 7Fh TO Time out bit 1 After power up CLEWDT instruction or SLEEF instruction A WDT time out occurred PD Power down bit 1 After power up or by the CLRWDT instruction 0 By execution of the SLEEP instruction Z Zero bit 1 The result af an anthmetic or logic operation is zero o The result af an arithmetic ar logic operation is nat zero DC Digit carry borrow bit ADDWF ADDLW 2UBLW 2UBWF instructions far borrow the polarity 15 reversed 1 Acarry out from the 4th low order bit of the result occurred o carry out from the 4th low order bit of the result C Carry barrow bit ADDWE ADDLW SUBLW
4. ing an infinite loop to make sure that che wave stifi bii kr usiog defay or G S sec every riashrng fed 7 pa pass 2 i idj i 1000 2 lt gt 2 lt gt Figure 4 7 Program Building 5 After Build the following message well appears xia Messages 32 Find EA GConvertor LineColurnn Message Message Text Unit 0 0 101 Used ROM 39 37 Used 16 237 0 0 Free ROM 884 97 Free 52 777 lt gt Figure 4 8 Message after Building Application The idea of this program build application to used to display 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 OSC1 CLKIN OSC2 CLKOLUT MCLR RA3 RAA TOCKI RBO NT RB1 PIZ16F84A Figure 4 9 IQAMA application Iqama Application int 1 J void interrupt 1 INTCON INTCON amp 0b11111110 if PORTB amp 0b00010000 0b0 1 10 if PORTB amp 0b00100000 0b0 1715 if PORTB amp 0b01000000 0b0 1220 void main INTCON 0610001000 0 PORTA 0 TRISB 0 0 0 while 1 1 while i gt 0 i 1 1 10 PORTA j 17 10 10 PORTB 7 Delay_us 995840 1556 0 50
5. eoo Ex7 EE a EEPROM handling application START LOOPO LOOP1 LOOP2 LOOP3 LIST 16 84 INCLUDE P16F84A INC CONFIG ORG 0x000 GOTO START ORG 0x004 RETFIE BSF STATUS RPO CLRF TRISB BSF 5 0 MOVLW B 00011111 MOVWF 5 STATUS RP0 MOVLW 07h MOvWF BTFSS GOTO LOOP 0 MOVF PORTA W MOVWF BSF STATUS RPO BCF INTCON GIE BCF EECON1 EEIF BSF EECON1 WREN MOVLW 55h MOVWF 2 MOVLW OAAh MOVWF 2 BSF EECON1 WR BSF INTCON GIE BTFSS 1 GOTO LOOP 1 BCF STATUS RPO CLRF EEDATA BTFSC PORTB O GOTO LOOP 2 BSF STATUS RPO BSF EECON1 RD BCF TRISB 0 BCF STATUS RPO EEDATA MOVWF LOOP3 END XT OSC amp PWRTE ON amp CP OFF amp WDT OFF BANK1 PORTB PINS ARE OUTPUT Except is input PORTA PINS ARE INPUT address 1 2 data 3 4 5 6 disable interrupts clear EEIF enable writing keys 7 8 initialize writing enable interrupts wait until writing is done EECON1 is at 88h Reading from EEPROM IS OUTPUT EEDATA is at 08h 26 Ex7 EE b EEPROM handling application LIST 16 84 INCLUDE lt P16F84A INC gt CONFIG OSC amp PWRTE ON amp CP OFF amp OFF ORG 0 000 START ORG 0 004 RETFIE START B
6. 00 PIR1 DODh PIR2 DOEh TMRIL 1 O10h TICON gt Chapter 2 Programming microcontrollers using Assembly language 2 1 Machine language and Assembly language Computer is a machine that can solve problems by carrying instructions given to it Program is a sequence of instructions describing how to perform a certain task Machine language is the computer primitive instructions consisting of O s 175 0000000000000 1 1 1 0 1 0000 0000000000000 0001 0000000000001 0002 0000000000001 0003 0000000000010 0004 00 09 0000000000010 0005 This program 0000000000011 0006 10 06 0000000000011 0007 copies AO to BO 0000000000100 0008 0000000000100 0009 08 05 0000000000101 000A 00 86 0000000000101 0008 28 0 0000000000110 000C 0000000000110 000D 1111111111111 1FFF 1000000000011 1111 1 1 1 1 1 2007 It is almost impossible write programs directly in machine language However they may written in a human readable form of the machine language which is called the Assembly language GOTO START GOTO START START BSF 0 03 0 5 BSF STATUS RPO 0 86 0 0 0 BSF 0 85 0 0 BSF 0 0 03 0 5 STATUS RPO LOOP MOVF 0x05 0 MOVF PORTA W MOVWF 0x06
7. 39 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 7 segment 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 Bo B3 output and B4 B were adjusted to be input The line command PORTB amp 0600010000 060 1 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 40 40 41 Library EEPROM data memory is available with a number of PICmicros mikroC includes library for comfortable work with EEPROM Library Routines _ m Eeprom Write Eeprom Read Prototype Returns Description Requires Example Eeprom Write 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 EEPROM module Ensure minimum 20ms delay between successive use of routines Eeprom Write and Eeprom Read Although PIC will
8. PORTB GOTO LOOP GOTO LOOP The P16F84a INC file allowed us to write identifiers for memory locations instead of their addresses 2 2 Assembler Statements Instructions Directives numbers Representation 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 decimal hexadecimal b 11110000 binary 2 3 Addressing Modes The 16F84A ucontroller has 35 machine language instructions each one is referred by 3 6 letters mnemonics in the assembly language The mnemonics may be followed by one or more operands The machine code of each instruction is divided into fields Operation code op code indicating what the processor is to do Operands indicating the information needed by the instruction datum or its location MOVLW Ox3F MOVF PORTA w MOVWF PORTB BCF PORTB 0x0 BCF 5 0 0 CLRF CLRF INDF The way in which an operand is specified is called its addressing mode There are 2 basic addressing modes 1 Immediate operand XORLW Ox5F 2 Memory operand Direct CLRF TMRO Indirect CLRF INDF 2 3 1 Expanding the address space through the idea of Banks while using Direct amp Indirect
9. 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 79 Prof M Abdelati amp Mr M Almobaied Fall 2008 9 1 The following questions are True False questions referred to PIC16F84A If the statement 15 true circle go to the next question If the statement 15 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 f T F T 1 The instruction bus consists of 14 A B 2 EECON2 15 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 read from the EEPROM we need to use EEADR EEDATA EECONI 2 A B 5 we can write any code in assembl
10. Prototype Returns Description Requires Example Usart Read Prototype Returns Description Requires Example Usart Write Prototype 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 If data is ready read it int receive if Usart Data Ready receive Usart Read unsigned short Usart Read void Returns the received byte If byte is not received returns Function receives a byte via USART Use the function Usart Data Ready to test if data is ready first USART HW module must be initialized and communication established before using this function See Usart Init If data is ready read it int receive if Usart Data Beady receive Usart Bead void Usart Write unsigned short data 61 62 Returns Nothing Description Function transmits a byte data via USART Requires USART HW module must be initialized and communication established before using this function See Usart Init Example int chunk OxlE 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 y
11. 000 b What 15 the content of the general Program Counter and w Register Instructions Counter y 4 urpose register whose address is 5 omg Cock Cycles Counter 24 155 e SPS Special Function Registers SFR General Purpose Registers BPRs Hex Binary Value Hex Addressand Mame 76543210 Add Value Addr Value c What is the address of the next masan Instruction to be executed 002 PCL STATUS TT gr DD4h FSR O05h PORTA PORTE 0081 EEDATA d What is the value of the zero flag TES CEI PCLATH 5 11 D Bh INTCON __ 08th OPTION REG IE ES ESTEST ESTEE ESTEE DB85h TRISA TT 8 TRISB EEFT 088h EECDN1 e What will happen when you aati Dosa r execute the next Instruction PO 65 66 M Abdelati Fall 2007 8 3 Referring to PIC16F84A microcontroller 4 convert the folowing assembly code to answer the following machine language and fill the resultant code in the memory model shown below a On reset what will be the value of the program counter PC ORG 10h MOVE PORTA W MOVWE PORTB GOTO LOOP b On interrupt what will be the value of END the program counter PC address content 0000 c What Is the width of the instruction bus 0001 0002 0003 0004 d What 15 the maximum program si
12. BTFSS STATUS Z GOTO Delay 2 6 2 Counter mode The PIC16F84A can be programmed so hat portRA4 TOCKI is used to count events or pulses by initializing the TimerO module as a counter Without interrupts the process requires the following preparatory steps Port A line4 RA4 TOCKI is defined for input The TimerO register TMRO is cleared The OPTION register bits PSA and PSO PS2 are initialized if the prescaler is to be used The OPTION register bit TOSE is set so as to increment the count on the high to low transition of the port pin if the port source is active low Otherwise the bit is cleared The OPTION register bit TOCS is set to select action on the RA4 TOCKI pin 20 1 R1 1 od 18 OSC1 CLKIN RAO CRYSTAL OSC2ICLKOUT RA2 L MCLR RA3 33pF RAA TOCKI 8 RB INT EE RA ag LE U gt p RB3 PIC18FBAA 5 Counter a Counter on RA4 TOCKI from 00 No Interrupt is used here LIST 16 84 INCLUDE lt P16F84A INC gt CONFIG XT OSC amp PWRTE ON amp CP OFF amp OFF ORG 0 000 5 ORG 0X004 RETFIE BSF STATUS RPO BANK 1 MOVLW B 10111000 MOVWF OPTION REG 11 lxxx CLRF TRISB PORT IS OUTPUT MOVLW 8 00011111 MOVWF TRISA PORT A IS INPUT BCF STATUS RPO BANKO CLRF MOVF TMRO W MOVWF PORTB LOOP END LIST _ CONF
13. b A program that allows you to enter the source program as a file on disc A program module that performs a well defined function d program that translates from assembly level source to machine code 80 3 Write PIC assembly level code to compare the two numbers NUMBERI in File h 30 and NUMBER2 in File h 31 and if these are equal add 6 onto DATUM in File h 40 otherwise decrement it 81 Prof Abdelati amp Mr M Almobaied Fall 2008 9 4 Write a macro which fills the even bytes and the odd bytes of the General Purpose registers with the numbers 0 55 and OxAAh respectively 81 82 Prof M Abdelati amp Mr M Almobaied Fall 2008 9 5 DC servo motors are characterized by simplicity in speed and position control applications They 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 don t write any software 82 83 Prof Abdelati amp Mr M Almobaied Fall 2008 9 6 A simple alarm system has 4 zone inputs connected to PICI6F84A 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 displa
14. void main TRISB 0 PORTB 0 while 1 PORTB PORTB Delay_ms 1000 35 36 Notes In MicroC we didn t need to initialize the banks We deal with the each ports directly The line command PORTB 15 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 PORTB PORTB amp 0600000001 PORTB amp 0b11111110 Notes This line 15 used to apply operation It is a bit wise operation dealing with the number bit by bit It is dealing with the number as one unit 2 amp 0b11111110 Delay_ms 1000 PORTB 0500000001 Delay_ms 1000 The procedures to write this is program in mikroC program 1 From project select New Project mikroC compiler for PIC Dk Dh D 3 5 F i j it eses pegation co POSTE sre i configurar ton C3 PICIGEET dua woriistgr SET T Ext at ama Ane e 58 i Wo La lt 85 lt gt P lt gt Figure 4 4 New Project
15. 36 2 Enter ProJect Name Project Path Device Clock and Configurations C New Project Project Narne Project Path Description Device Clock Device Flags Flasher C Ci 1 84 004 000000 OFF C WDT ON 3FF 3FFF 3FFB 3FFC 3FFD Save Remove Default Settings Click the checkbox on the left to select CONFIG word Default settings are as follows High Speed Oscillator HS enabled Watch Dog Timer wD T disabled Low Voltage Programming LVP disable Figure 4 5 Project Name Project Path Device Clock and Configurations 3 Write the program in Code Editor 3 mikroC compiler for PIC l aai dm l i LT void while 1 0 0 e deb oF jx m 31 LJ Tais program simpie program make Ciasher sve sling an infinice 1008 make sure Caat wave 36111 air L amd a deiay or 0 35 sec between every riashing dede BEG 13510 8 9 Figure 4 6 Program Writing 37 37 38 4 From Project enter Build mikroC compiler for PIC BR RAR o o program simpie program CO make fiasher eave
16. 9 por wer res mes me nes mer neam 75 Oh Unimplemented location read as D eS EEPROM Oia Resi EEPROM Address Register Bank 1 80h INDE Uses Contents of FSR to address Data a nat a physical register JR AEN Low ow order 8 bits of Program Counter 0000 00 ze s FSR Indirect data memory address pointer xxxx 11 TRISB PORTS Data Direction Register 18 JN Unimpamented location read as SN RN EECONZ EEPROM Control Register 2 not a physical register PCLATH Write buffer for upper 5 bits of the 0 0000 Legend x unknown u unchanged unimplemented read as D q value depends on condition Note 1 The upper byte of the program counter is not directly accessible PCLATH is a slave register for lt 12 2 gt The contents of PCLATH can be transferred to the upper byte of the program counter but the contents of PO lt 12 5 gt are never trans ferred to PCLATH The and PD status bits in the STATUS register are mot affected by MCLR Reset Other nan power up RESETS include external RESET through MCLR and the Watchdog Timer Reset On amy device RESET these pins are configured as inputs This is the value that will be in the port output latch 1 6 2 Pr
17. Chip Family Chip Select Load Save gt gt DATA Program Options 0000 2805 3FFF 3FFF 3FFF 1683 z Blank Erase 0008 1283 0805 0086 2809 3FFF 3FFF v Program And Verify EEPROM 0010 3FFF 3FFF 3FFF 3FFF 3FFF 3FFF Program And Verify ROM 0018 3FFF 3FFF 3FFF 3FFF White finish again verify once 0020 Program And Verify FUSE ID 0028 3FFF 3FFF 3FFF 3FFF 3FFF 3FFF 0030 3FFF 3FFF 3FFF 3FFF 3FFF Program Auto Program 0038 3FFF 3FFF 3FFF 3FFF 3FFF 3FFF 0040 3FFF 3FFF 3FFF 3FFF 0048 Checksum 0050 3FFF 3FFF 3FFF 3FFF 3FFF 3FFF 0058 3FFF 3FFF 3FFF 3FFF 3FFF Checksum 0060 3FFF 3FFF 3FFF 3FFF Configuration Word 0068 3FFF 3FFF 3FFF 3FFF 3FFF DsFFFF 0070 3FFF 3FFF 3FFF 3FFF 3FFF 0078 3FFF XFFFFFFFF 0080 3FFF 3FFF 3FFF 3FFF 3FFF 3FFF JSCCAL Dz3EFF gt APPR APPP ANPP APPI APPP Anor COM5 OL2006 Reset failed B Communication failed gt gt gt Statistics 3999 _ _ Fuses CALIB Program 2 QianLongsheng Copyright ShenZhen Gianlongsheng WEB www picl6 c
18. 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 34 PIC and fit together well PIC is the most popular 8 bit chip in the world used in a wide variety of applications and prized for its efficiency 15 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 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
19. PWM MCU must have CCP module Pwm Init must be called before using this routine Start should be called before using this routine otherwise it will have no effect as the PWM module is not running 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 ZZ microcontroller PI6F87VA module is set on RC2 unsigned short j void InitMain PORTB 0 Set to 0 TRISS 419 PORTB is output ADCON1 6 211 AUC pina digital 1 0 PORTA 255 TRISA 255 PORTA is input PORTC OxFF Set PORTC to SFF TRISC 0 ZZ PORTC is output Init 5000 Initialize PWM module void 1 InitMain j 80 Initial value for j oj 0 will keep the old j value Stare 7 Start PWM while 1 Endless loop af Button GPorTA 0 1 1 ZZ button on RAO pressed Jer 2 ZZ j if Button amp PORTA 1 1 1 button RAI pressed 27 decrement j if oj j If change in duty cycle requested Pwm Change Duty j set new duty ratio oj 1 ZZ memorize it PORTB oj and display Delay ans 200 5 Slow down a bit HW Connection VCC CSVA8LOId PWM demonstration 59 59 60 USART Library USART hardware module is available with a number of PICmicros mikr
20. as building bricks in your projects Copy them entirely if you deem fit that s why we included them with the compiler mikroC is a user friendly and intuitive environment r A E nnwssPsCTsitxrrrrY Ci Q Da Tag ene e he OF Watch E ei bass Eeid 5 4 Code gt Explorer E Dega pap py k Code ee Editor Tie Prcct Summary d Ermar Winde Code Assistant Figure 4 2 mikroC IDE 34 35 The Code Explorer with Keyboard shortcut browser and Help browser 15 at your disposal for easter 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 Building the First Program Flasher C1 Figure 4 3 Flasher on PORTB This program is a simple program to make a flasher wave on PORTB of the PICI6F84A 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
21. 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 AO and Al of a 16F84A microcontroller and they will be used to enter a number from 0 to 100 into a variable x The input Al is used for decreasing while AO 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 doesn t have a serial port Show the circuit diagram and write the required program 92 93 Data Bus 14 Addr Program Bus Indirect Addr Rad TOCE w A Direct Addr 120 Ports X REY RB X RBO MT X 2S M O8C2 CLEOUT WSs 94 TABLE 2 1 SPECIAL FUNCTION REGISTER FILE SUMMARY Value on Detail Addr Name i Bit 6 Bit 5 Bit 4 Bit 3 Bit 1 Power on ams Reser 0 INDF Llses contents of FSR to address Data Memory not a physical register TMRO 8 bit Real Time Clock Counter 021 PEE Low Order 8 bits of the Program Counter m mme elc jen Indirect Data Memory Address Pointer 0 aOR PORTB Res R82 RAT RBOINT xxx 18 _ caion asas
22. takes the address and data as arguments Ex7 EE_a EEPROM handling applica LIST P PIC16F84A INCLUDE lt P16F84A INC gt __ OSC amp PWRTE ORG 0 000 GOTO START ORG 0 004 RETFIE START BSF STATUS RPO CLRF TRISB BSF TRISB 0 MOVLW B 00011111 MOVWF BCF STATUS RPO 07h MOvWF EEADR LOOPO BTFSS GOTO MOVF PORTA W MOVWF EEDATA BSF STATUS RPO BCF INTCON BCF EECON1 EEIF BSF EECON1 WREN MOVLW 55h MOVWF 2 MOVLW MOVWF 2 BSF EECON1 WR BSF LOOP1 BTFSS 1 GOTO LOOP1 BCF STATUS RPO CLRF EEDATA LOOP2 BTFSC PORTB O GOTO LOOP2 BSF STATUS RPO BSF EECON1 RD BCF TRISB 0 BCF STATUS RPO MOVF EEDATA W MOVWF PORTB LOOP3 GOTO LOOP3 END 87 88 Prof M Abdelati Summer 2008 9 Ex5 Counter a Counter on RA4 TOCKI from 00 FF No Interrupt is used here LIST 16 84 INCLUDE lt 16 84 gt __CONFIG OSC amp PWRTE ON amp WDT OFF ORG 0X000 GOTO START ORG 0x004 RETFIE BSF STATUS RPO BANK 1 MOVLW B 10111000 MOVWF OPTION REG 11 1 CLRF TRISB PORT B IS OUTPUT MOVLW 00011111 MOVWF TRISA PORT A IS INPUT STATUS RPO BANKO MOVF 0 MOVWF PORTB GOTO LOOP END Modify the hardware and software of the example shown above so that the same task is done using interr
23. the predefined constants to the function The complete list of available commands is below Port with LCD must be initialized See Lcd Config or Lcd Init Clear LCD display Lcd Cmd Lcd Clear Available LCD Commands Purpose 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 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 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 46 LCD TURN OFF Turn LCD display off LCD SHIFT LEFT Shift display left without changing display data RAM LCD SEIPT RIGHT 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 PORTE is output Led Init sPORTB Initialize LCD connected to PORTB Lcd Cmd Lcd CLEAR Clear display Lod Omd Led CURSOR OFF 77 Turm cursor off bog Outil ly ZZ Print text to ICD 2nd row ist column Plc
24. write the correct value Eeprom Read might return an undefined result unsigned short take Lake Eeprom Read 0X3F 7 void Eeprom Write unsigned int address unsigned short deta 7 Nothing Writes data to specified address PParameter address is of integer type which means it supports MCUs with more than 256 bytes of 41 42 Be aware that all interrupts will be disabled during execution of Eeprom Write routine 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 Write and Eeprom Read Although PIC will write the correct value Feprom Read might return an undefined result Example Eeprom Write 0x32 19 Library Example The example demonstrates using EEPROM Library unsigned short i 0 0 void 1 PORTB 0 TRISB 0 j for i 0 i lt 20u 1 EBprom Writeil Jt for 1 Ds x lt 210 a 4 PORTB Eeprom Read i Delay 500 1 42 43 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
25. your mobile phone delay the submission of your answer sheets don t answer each question in its allocated space separate page or l 2 3 4 a 8 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 69 M Abdelati Fall 2007 8 1 a Sketch the pin diagram of the 6 84 b Sketch a figure which illustrates the internal architecture of the PICI6F84A Don t 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 to the contents of File h 36 and store the result in File h 40 Remember that File means data memory location 69 70 M Abdelati Fall 2007 8 2 Assuming that you have found a 1 second delay
26. 5 1 for a pin configured as input and is driven low by an external device the data will be written back with a 0 2 If this instruction is executed on the register and where applicable 1 the prescaler will be cleared if assigned to the Timer0 Module 3 Program Counter PC is modified or a conditional test is true the instruction requires two cycles The second cycle is executed as a NOP lI oce MON T rS Um eX o ND Table A 2 PIC 16Fxx Instruction Set
27. 6 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 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 Configure analog inputs and Vref TRISA OxFF PORTA is input 54 55 TRISB Ox3F Pins RB7 RB6 are outputs TRISD 07 PORTD 18 output do temp res Adc Read 2 Get results of AD conversion PORTD temp res Send lower 8 bits to PORID PORTB temp res gt gt 2 Send 2 most significant bits to RB7 RB6 while 1 HW Connection m 330 DO Y b 3B 330 lt 1 p H 330 102 330 LD3 CSVABLOId ADC HW connection 55 56 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
28. CFSZ LOOPO DECFSZ 0 TOOPI RETURN 7 7 IV I I P 6 Write assembly language instructions to clear general purpose registers of the PIC16F84A microcontroller don t write the whole program 6 68 M Abdelati Fall 2007 8 Electrical amp Computer Engineering Department Microcontrollers amp Microprocessors Based Systems ECOM 4315 Q Grade Duration 120 2o IK ra EE E news EAA 0 Surname 4 2 Ssi l 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 15 closed books and notes instructions sheet 15 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 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
29. E J ERE ME E J P Ue J J UE Le E BANK1 ALL PORTB PINS ARE OUTPUT PORTA PINS ARE INPUT CALLING A MACRO 29 2 9 2 Using Macros externally This is an example for using MACROS externally in the program LIST P PIC16F84A INCLUDE P16F84A INC INCLUDE MyLibrary INC _ OSC amp PWRTE ON amp CP OFF amp WDT OFF ORG 0 000 START ORG 0X004 RETFIE BSF STATUS RPO BANK1 CLRF TRISB ALL PORTB PINS ARE OUTPUT MOVLW B 00011111 MOVWF TRISA PORTA PINS ARE INPUT BCF STATUS RPO BCDto7segTable CALLING A MACRO MOVLW OFh ANDWF PORTA ADDLW OCh MOVWE FSR MOVWE PORTB GOTO LOOP END Mylibrary INC BCDto7segTable Macro MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF ENDM Ex8 Macro Decimal Counter on RA5 TOCKI as Ex5d LIST P PIC16F84A INCLUDE lt P16F84A INC gt INCLUDE lt ECOM4315 INC gt __CONFIG OSC amp PWRTE ON amp OFF amp WDT OFF CBLOCK 0X20 file name BCD TEMP DIGO DIG1 DIG2 ENDC ORG GOTO ORG RETFIE BSF MOVLW BCF CLRF MOVLW MOVWF BCF CLRF SWAPF IORWF MOVWF GOTO END OSC1 CLKIN OSC2 CLKOUT MCLR 0 000 START 0 004 PIC16F84A STATUS RP0 B 10111000 OPTION_REG 6 TRISB B 00011111 TRISA STATUS RPO BANK 1 1 11 1000 PORT A IS INPUT BANKO
30. EEDATA EEPROM Data Register 13 14 EEADR EEPROM Address Register 13 14 PCLATH Write Buffer for upper 5 bits of the PC 1 pen GE Toe me Tor WTF RBI coos 30 _ Bank 1 INDF Uses Contents of FSR to address Data Memory not a physical register 11 En Low order 5 bis of Program Ti Ev mum De m WI ET 5 Indirect data memory address pointer XXXX XXXX XXXX T E Bm TRIB PORTBDauDmecnRegser panem Unimplemented location read as 0 eed ere ee E 8h 1 WRERR WREN WR 0 Er WREN WR RD 13 EECON2 EEPROM Control Register 2 n physical pe moon GE ABE TOF ITF vemx 10 Legend unknown u unchanged unimplemented read value depends condition Note 1 The upper byte of the program counter is not directly accessible PCLATH is a slave register lt 12 8 gt The contents of PCLATH be transferred to the upper byte of the program counter but the contents of lt 12 8 gt are never trans ferred to PCLATH The TO and PD status bits in the STATUS register are not affected by a MCLR Reset Other non power up RESETS include external RESET thro
31. F SWAPF RETURN 2 17 What Is the Harvard architecture 2 18 Suppose STATUS 0x10 Which bank 15 selected 2 19 Where 15 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 78 Prof M Abdelati amp Mr M Almobaied Fall 2008 9 Electrical Engineering Department Microcontrollers amp Microprocessors Based Systems ECOM 4315 Final Exam Duration 120 min Phone or email contact SO 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 ask any question of any type barrow pencil eraser calculator etc set In a wrong exam room leave the room during the exam period delay the submission of your answer sheets don t answer each question in its allocated space separate page or 1 2 3 4 5 show up your mobile phone 6 7 8 ask for paper revision
32. IG ORG ORG RETFIE BSF CLRF MOVLW MOVWF BCF CLRF BTFSS GOTO INCF GOTO END LIST CONF IG ORG GOTO ORG RETFIE BSF CLRF MOVLW MOVWF BCF CLRF BTFSS GOTO BTFSC GOTO GOTO END Bad implementation 21 5 Counter b Counter on RA5 TOCKI Using Poling P PIC16F84A INCLUDE lt P16F84A INC gt 0 000 5 0 004 STATUS RP0 TRISB XT OSC amp PWRTE ON amp OFF amp WDT OFF BANK 1 PORT B IS OUTPUT B 00011111 TRISA STATUS RPO PORTB PORTA LOOP PORTB LOOP Good implementation PORT A IS INPUT BANKO 4 5 Counter c Counter on RA5 TOCKI Using Poling P PIC16F84A INCLUDE lt P16F84A INC gt 0 000 5 0 004 STATUS RPO TRISB XT OSC amp PWRTE ON amp CP OFF amp WDT OFF BANK 1 PORT B IS oUTPUT B 00011111 TRISA STATUS RPO PORTB PORTA LOOP PORTB PORTA LOOP 1 LOOP PORT A IS INPUT BANKO 4 Key is pressed 4 Key is released 22 5 Counter d Counter on RA5 TOCKI 0 99 twice 0 55 and restart START LOOP BCD _100 _10 10 LIST 16 84 INCLUDE lt P16F84A INC gt __ XT OSC amp PWRTE ON amp OFF amp WDT OFF CBLOCK 0X20 TEMP DIGO DIG1 DIG2 ENDC ORG 0 000 START ORG 0 004 RETFIE BSF STATUS RPO BANK 1 MOVLW B 10111000 OPTION REG 6 1 11 1000 CLRF TRISB PO
33. NK 1 BCF OPTION REG 6 0 FOR Edge programmig BSF TRISB O IS INPUT MOVLW 10010000 MOVWF INTCON l 1 0 CLEAR EXTERNAL INT FLAG BCF TRISB 1 B1 is output BCF TRISB 2 B2 is output BCF STATUS RPO BANKO LOOP MOVLW 02h XORWF PORTB F CALL DELAY GOTO LOOP FF I f J J V Y Y 7 7 DELAY MOVLW 255 MOVWF OCH LOOP 1 NOP MOVLW 255 PAROS Amr 16 Interrupts are a mechanism of a microcontroller which enables it to respond to some events at the moment they occur regardless of what microcontroller is doing at the time Each interrupt changes the program flow interrupts it and after executing an interrupt subroutine it continues from that same point on 2 5 1 Sources of interrupt for PIC16F84A 1 Termination of writing data to EEPROM 2 TMRO interrupt caused by timer overflow 3 Interrupt during alteration on RB5 RB6 pins of 4 External interrupt from RBO INT pin of microcontroller 2 5 2 Registers used with interrupt 1 Control interrupt register INTCON at OBh address 2 Option register at 81h address 3 Control EEPROM register EECON 1 at 88h address R W 0 R W 0 R W 0 R W 0 R W 0 R W 0 R W 0 R W x bit 7 bit O GIE Global Interrupt Enable bit 1 Enables all unmasked interrupts 0 Disables all interrupts EEIE EE Write C
34. RT B IS OUTPUT MOVLW B 00011111 MOVWF TRISA PORT A IS INPUT BCF STATUS RPO BANKO TMRO MOVF TMRO W Call BCD SWAPF DIG1 W IORWF DIGO W MOVWF PORTB GOTO LOOP MOVWF TEMP DIG1 CLRF DIG2 MOVLW 100 EXTRACT 100 S NUMBER SUBWF TEMP F TEMP TEMP 100 BTFSS STATUS C GOTO 210 DIG2 F GOTO 100 MOVLW 100 EXTRACT TEN S NUMBER AddWF TEMP F MOVLW 10 SUBWF TEMP F TEMP TEMP 10 BTFSS STATUS C GOTO B INCF DIG1 F GOTO __10 MOVLW 10 ADDWF TEMP F TEMP W MOVWF DIGO RETURN END 2 7 Look Up Tables OSC1 CLKIN OSC2 CLKOUT MCLR Ex6 LUT An application for Luok up tables START LOOP LIST P PIC16F84A INCLUDE lt P16F84A INC gt J CONFIG XT OSC amp PWRTE_ON amp CP OFF amp WDT OFF ORG GOTO START ORG 0X004 RETFIE BSF CLRF MOVLW MOVWF BCF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW ANDWF ADDLW MOVWF MOVF MOVWF STATUS RPO TRISB B 00011111 TRISA STATUS RPO COh OCh OF9h ODh 4 OBOh OFh 99h 10h 92h 11h 82h 12h OF8h 13h 14h 90h 15h OFh PORTA W OCh FSR INDF W PORTB GOTO LOOP END BANK1 PORTB PINS ARE OUTPUT PORTA PINS ARE INPUT 23 24 2 8 EEPROM utilization EEDATA 8 Addes EEPROM for bb 8h data EX OT T T T _ 10ih Ad
35. SF STATUS RPO MOVLW 00000001 ALL PORTB PINS ARE OUTPUT MOVWF TRISB Except BO is input 8 00011111 MOVWF TRISA PORTA PINS ARE INPUT BCF STATUS RPO MOVLW 07h MOvWF EEADR 1 address LOOPO BTFSS PORTB O LOOPO MOVF PORTA W MOVWF EEDATA 2 data BSF STATUS RPO BCF INTCON GIE 3 disable interrupts BCF EECON1 EEIF 4 clear EEIF BSF 1 WREN 5 enable writing MOVLW 0X55 6 keys MOVWF EECON2 MOVLW OXAA MOVWF EECON2 BSF EECON1 WR 7 initialize writing BSF INTCON GIE 8 enable interrupts LOOP 1 BTFSS EEIF wait until writing is done GOTO LOOP1 BCF EECON1 WREN BCF STATUS RPO CLRE EEDATA LOOP 2 BTFSC PORTB 0 GOTO LOOP 2 BSF STATUS RPO EECON1 is at 88h BSF EECON1 RD Reading from EEPROM BCF STATUS RPO EEDATA is at 08h RLF EEDATA W MOVWE PORTB GOTO LOOPO END 27 2 9 5 Macros are a very useful element in assembly language They could briefly be described as user defined group of instructions which will enter assembler program where macro was called It is possible to write a program even without using macros But with their use written program is much more readable especially if more programmers are working on the same program together Macros have the same purpose as functions of higher program languages What s the difference between macro and subroutine 1 In execution stage the subroutine puts the address of the c
36. SUEWF instructions for borrow the polarity is reversed 1 Acarry out the Most Significant bit of the result occurred o carry out from the Most Significant bit of the result occurred Note subtraction is executed by adding the two s complement of the second operand For rotate RLF instructions this bit is loaded with either the high or low order bit of the source register Legend R Readable bit W Writable bit Unimplemented bit read as 0 n Value at POR T Bit is set Bit is cleared x Bit is unknown 2 3 3 PORTA TRISA PORTB TRISB registers Ex1 Buffer LIST P PIC16F84A INCLUDE lt P16F84A INC gt CONFIG XT OSC amp PWRTE_ON amp CP OFF amp WDT OFF ORG 0 000 GOTO START ORG 0 004 RETFIE BSF STATUS RPO BCF TRISB O BSF TRISA O BCF STATUS RPO MOVF PORTA W MOVWE PORTB GOTO LOOP END BANK1 RBO IS OUTPUT IS INPUT BANKO SFR GPR Unimplemented Address INDF INDF 80h 01h TMRQ OPTION 81h Oh PCL 82h 03h STATUS STATUS 83h 04h LR 84h ash 85h 06h 86h 078 T 87h 08h 09h 89h OAh 1 PCLATH 8Ah 8Bh OCh 8Ch 68 bytes RAM memory General Purpose AFh Registers CFh 50h DOh 7Fh FFh BlankO Blank1 Address 2 4 Using loops 2 4 1 to generate delays OSC 14 gt LHH Os C LEO UT MCLR R1 120 01 LED GREEN 2 Flas
37. 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 e 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 Course Outline Statement of course objectives contents methods and evaluation Basic Computer Architectures Instruction execution and pipelining Microcontrollers versus microprocessors Harvard versus Von Neumann s Architecture RISC CISC PIC16F84A Microcontroller Implementing first Application Software amp Hardware Development Tools PIC Microcontrollers Families Source Code Format Addressing modes Delay Loops Interrupts Lockup tables EEPROM utilization Midterm Programming PIC microcontrollers in C Flasher Application in C Simple Iqama Application in C Using interrupts 9 10 Keypad and LCD Interface Analog interface 11 12 Serial Communication DC motor control Stepper Motor Control 13 15 Selected Projects Chapter 1 Microcontroller Basics 1 1 Simple Computer Architecture CPU Microprocessor Memo
38. TMRO TMRO W TEMP DIGO DIG1 DIG2 DIG1 W DIGO W PORTB LOOP is ECOM5315 INC Macro local MOVWF MOVLW SUBWF BTFSS GOTO INCF GOTO MOVLW AddWF MOVLW SUBWF BTFSS GOTO INCF GOTO MOVLW ADDWF MOVF MOVWF ENDM Temp DIGO DIG1 DIG2 _ 100 10 _ 10 1 DIG1 DIG2 100 STATUS 10 DIG2 F 100 EXTRACT 100 S NUMBER 100 100 TEMP F TEN S NUMBER 10 TEMP F STATUS C _1 DIG1 F 10 10 10 TEMP F TEMP W DIGO PORT B IS oUTPUT 31 2 10 The hexadecimal object file format for PIC Microcontroller General Record Format Inf i Mark Load Record Offset Recon Type nformation Chick Sum I Length or Data 1 byte 1 byte 2 bytes 1 byte n bytes 1 byte Record Mark each record begins with a Record Mark field containing the ASCII code for the colon character Record Length The number of bytes of information or data Offset By the offset we can arrive to the address Record Type It is used to interpret the remaining information within the record The encoding for all the current record types is Record Type Description Information or Data Digits Data Record End of File Record Extended Segment Address Record Extended Linear Address Record Start Linear Address Record Information or Data It consists of zero or more bytes encoded as pairs of hexadecimal digits The int
39. The Islamic University of Gaza Electrical Engineering Department 2013 2014 Fall semester Instructor Prof Dr Muhammed ABDELATI Tel 2878 E mail muhammet iugaza edu ps E mail ahafifi iugaza edu Prerequisites This course is dedicated to 4 year electrical engineering students who completed successfully the Computer Programming and Logic Design courses Office Hours Saturday 08 30 11 00 9 Monday 08 30 11 00 These office hours are tentative Official ones used to be announced on my office door Course Objectives The course provides a thorough description of the design and implementation of microcontrollers Text Books J Sanchez and M Canton Microcontroller Programming The Microchip 2007 Nebojsa Matic The PIC Microcontrollers 2000 Dogan Ibrahim Advanced PIC Microcontroller Projects in C 2008 Recommended PIC16F84A Datasheet References MicroC User s Manual Grading Tentative Midterm Examination on Sunday 27 10 2013 at class time Attendance amp Participation Final Examination Exams Dates 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 22 09 2013 Grading Policy e Cheating and late submissions are severely penalized You will lose at least 25 per day for late submissions of your homework and projects e The Attendance and Participation grade is calculated according to the Second Chance
40. alized See Lcd8 Config or Init Print at current cursor position Ledo Out 12 void Lcd8 Chr unsigned short row unsigned short col char character Nothing 48 49 Description Prints character on LCD at specified row and column parameter row and col Both variables and literals can be passed aS character Requires Ports with LCD must be initialized See Lcd8_Config or Lcd8_ Init Example Print 4 on LCD at line 2 char 3 QuE 2 3 Lcd8 Chr Cp Prototype void Lcd5 Chr Cp char character Returns Nothing Description Prints character on LCD at current cursor position Both variables and literals can be passed aS character Description Requires Example Requires Ports with LCD must be initialized See Lcd8 Config or Init Example Print e at current cursor position Leds Chr Gp ets Lcd8 Cmd Prototype void Lcd8 Cmd unsigned short command Returns Nothing Sends command to LCD You can pass one of the predefined constants to the function The complete list of available commands is below Ports with LCD must be initialized See Lcd8 Config or Init Clear LCD display led Clear Available LCD Commands LCD Command Purpose LCD FIRST ROW Move cursor to 1st row LCD SECOND ROW Move cursor to 2nd row LCD THIRD ROW Move cursor to 3rd row LCD FOURTH ROW Move cursor to 4th row LCD CLEAR Clear display Retur
41. alled function in PC and hides the original value of PC before calling in the stack 2 The macro in compilation process not in execution copies the macro in the place where it is called It doesn t put address on stack 3 The subroutine can be written or called in any place but the macro must be declared before calling 4 The subroutine takes more time in execution but usually compiles to shorter programs 2 9 1 Using Macros internally OSC1 CLKIN OSC2 CLKOUT MCLR 5V gt PIC16F84A 28 This is an example for using MACROS internally in the program LIST P PICI6F84A INCLUDE lt P16F84A INC gt XT OSC amp PWRTE ON amp CP OFF amp WDT OFF LL YA EAE E IUE E WEE HE EE EU EE WE E ME EE UE AE UE RP EHE ILE UE e E dE FP F TE J jJ J AA P J Vf 4 BCDto7segTable BEGINES HERE A ME E START LOOP __CONFIG ORG 0 000 START ORG 0X004 RETFIE Macro MOVLW COh MOVWE 0Ch MOVLW 9 MOVWE ODh MOVLW 0A4h MOVWE OEh MOVLW OBOh MOVWE OFh MOVLW 99h MOVWE 10h MOVLW 92h MOVWE 11 MOVLW 82h MOVWE 12h MOVLW OF8h MOVWE 13h MOVLW 00h MOVWE 14h MOVLW 90h MOVWE 15h ENDM BSF STATUS RPO CLRF TRISB MOVLW 8 00011111 MOVWF TRISA BCF STATUS RPO BCDto7segTable MOVLW OFh ANDWF PORTA W ADDLW OCh MOVWF FSR INDF W MOVWF PORTB GOTO LOOP END le dE f f
42. dress Address Oth POL Uzh dich 82h a3h D4h 84h Goh Accessing ooh these locations EEDATA 2 22 9 685 AP of the bank from which We are 68 bytes RAM memory makina gn GPR access registers ad Linirn D e ne p locations by reading them Wwe always a Bank The PIC16F84 and PIC16F84A contain 64 bytes of EEPROM data memory This memory is both readable 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 the maximum contained in the PIC in this case Ox3f The following registers relate to EEPROM operations 1 EEDATA holds the data byte to be read or written 2 EEADR contains the EEPROM address to be accessed by the read or write operation 3 EECON1 contains the control bits for EEPROM operations 4 EECON2 protects EEPROM memory from accidental access This is not a physical register Register WRERR WREN WR RD 25
43. e Programs in C are converted into assembly language by compiler and assembled into machine code 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 28 n f btfsc STATUS Z qoto L41 while n 0 movf _n f addwf _sum f btfsc STATUS C incf _sum 1 f sun sun n n decf _n f goto 128 41 First compile to assembly level code 28 movf btfsc STATUS Z 0000100010010011 0001100100000011 ce Assemble 0010100000001111 addwf sum f 0000100000010011 btfsc STATUS C 0000100000010011 incf sume 1 f 0000011110010100 decf _n f 0001100000000011 goto 128 0000101010010101 L41 0111100000000111 b Second assemble link to machine code Figure 4 1 Process of compiling the C source file 1s 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 15 unique to each type of processor while C provides a common language for all MCU Microcontroller unit types Introduction to mikroC mikroC is a powerful feature rich development tool for
44. e it started from it has to return the value of a program counter from a stack When moving from a program to a subprogram program counter is being pushed onto a stack When executing instructions such as RETURN RETLW or RETFIE which were executed at the end of a subprogram program counter was taken from a stack so that program could continue from where it stopped before the interrupt These operations of placing on and taking off from a program counter stack are called PUSH and POP However the programmer has to keep the value of other registers used in the main program such as the status and work registers This may be done as follows OEh push W and Status STATUS W OFh ISR interrupt service routine OFh W pop W and Status MOVWF STATUS SWAPF OEH F SWAPF OEH W 2 6 TIMER0 TMRO module FIGURE 5 1 TIMER0 BLOCK DIAGRAM Data Bus 8 Sync with 3b Internal RAAITOCKI Programmable PSOUT Prescaler 3 2 Cycle Delay set Interrupt P52 P51 PSO PSA Flag bit TOIF TOCS on Overflow Note 1 TOCS TOSE PSA 52 50 OPTION REG lt 5 0 2 The prescaler is shared with Watchdog Timer refer to Figure 5 2 for detailed block diagram TABLE 5 1 REGISTERS ASSOCIATED WITH TIMERO Value on Value on all Address Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 0 POR other Le RESETS TMRO TimerQ Module Register ook xxxx XXXX uuuu uuuu Legend x unknown u
45. erpretation of this field depends on the Record Type field X _____ Start Segment Address Record B x 8 O Chick Sum This field contains the check sum on the Record length Load Offset Record Type and Information or Data Therefore the sum of all the ASCII pairs in a record after converting to binary from the Record length field to and including the Chick Sum field is zero HEX File of Ex1 020000040000FA 020000000528D1 0800080009008316051006141F 0800100083120608850009288F 02400E00F13F80 00000001FF Record Record Record Chick Mark Length Offset Type Info or Data Sum 02 0000 04 00 02 000 00 5 8 DI 08 0008 00 0900831605100614 1 08 0010 00 8312060885008 amp 8F 02 40E 00 80 0 1000 o F _ Modeling the program memory in PIC Microcontrollers Address Address 0007 0008 0009 000A 000B 1FFF Hexa notation content Address 0000000000000 0000000000001 0000000000010 0000000000011 0000000000100 0000000000101 0000000000110 0000000000111 0000000001000 0000000001001 0000000001010 0000000001011 1111111111111 32 Binary notation content 10000000000111 1114 11 111 1212100 0 1 33 Introduction to language The programming language allows applications to be written using syntax whose 15 little easier to understand than assembly cod
46. estions 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 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 l 2 3 4 a 8 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 75 Prof M Abdelati Fall 2008 9 1 Sketch figure for a simple circuit used to testa PIC16F84A microcontroller Write the associated software p
47. her on BO DISI P PIC16F84A INCLUDE lt P16F84A INC gt CONFIG XT OSC amp ON amp CP OFF amp OFF ORG 0 000 GOTO STARI ORG 0x004 RETELE BSF STATUS REQ BANK1 Ber REO IS QUEPUT STATUS MOVLW Olh XORWE E CALL DELAY GOTO LOOP F f f DELAY MOVLW 255 OCH LOOP L NOP MOVLW 255 MOVWF ODH NOP DECFSZ GOTO LOOP O DECFSZ OCH GOTO LOOP RETURN F f JJ 2 4 2 to process memory arrays Memory Block Processing indirect Addressing application Filling All GPR registers with OOh LIST P PICIOF84A INCLUDE P16F84A INC CONFIG XT OSC amp PWRTE ON amp CP OFF amp WDT OFF ORG 0X000 GOTO START ORG 0 004 MOVLW MOVWF FSR CLRF INDF INCF FSR MOVLW 50h SUBWF FSR w BTFSS STATUS 7 GOTO GOTO LOOPZ END PIC Simulator IDE Evaluation Copy File Simulation Rate Tools Options Help STEP Program Location s2009 E 23 A SEx3 Microcontroller PICT BF E44 Clock Frequency 4 0 MHz Last Instructiaa In
48. 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 Config Lcd Init call Library Routines m cd Config m cd Init m Out m cd Out Cp m Lcd Chr cd Chr Cp Lcd Lcd Config Prototype void Lcd Config unsigned short port unsigned short RS unsigned short EN unsigned short WR unsigned short 07 unsigned short 00 unsigned short D5 unsigned short D4 Returns Nothing Description Initializes LCD at port with pin settings you specify parameters RS EN WR D7 D4 need to be a combination of values 0 7 e g 3 6 0 7 2 1 4 Requires Nothing Example Lcd Config amp PORTD 0 1 7 5 4 3 2 Lcd Init Prototype void Lcd Init unsigned short port Returns Nothing Description Initializes LCD at port with default pin settings see the connection scheme at the end of the chapter D7 gt port 7 D6 port 65 Do port D4 port 4 E port 3 43 Requires Example Lcd_Out Prototype Returns Description Requires Example Lcd Out Cp Prototype Returns Description Requires Example Lcd Chr Prototype Returns Description Requires Example 44 BO Dort RW gt port Nothing Lcd Init amp PORTB void Lcd Out unsigned short row unsigned sho
49. is your partner if any What part of that assignment you have done by yourself and what part is done by your partner Have you submitted a CD If yes describe how you organized it 72 73 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 15 a segment of code written in 16 84 assembly language movlw d 20 movwf h 3F movlw d 250 addlw 1 btfss STATUS Z goto LOOP2 decf h 3F f btfss STATUS Z goto LOOP 1 sleep 1 Explain what this routine does and suggest its most likely purpose 11 Determine the execution time of the complete program segment assuming a clock rate of 4 MHz 73 74 Prof M Abdelati Fall 2008 9 Electrical amp Computer Engineering Department Microcontrollers amp Microprocessors Based Systems ECOM 4315 Midterm Exam Duration 80 min Grde fo Surname 4 4 2 202 2 2042 222 ES 30 n P n 40 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 15 closed books and notes instructions sheet 15 allowed Be sure that you have a total of 6 qu
50. n cursor to home position returns a shifted display to original position Display data RAM is unaffected 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 Library Examples Default Pin Configuration 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 Use Lcd8 Init for default pin settings see the first figure below char text mikroElektronika void main TRISB 0 0 PORTE is output TRISC 0 PORTC is output Leds Init amp PORTB amp PORTCO Initialize LCD at PORTB and PORTC Leds LCD CURSOR OFF ZZ Turn cursor Ledo Outil 1 Text L LI 8 Bg VEC Contrast P3 Adjustment 5K i ZZ Print text on LCD 50 XXXXO d LCD HW connection by default initialization using Lcd8 Init 50 51 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 m Keypad Init m Keypad Read Keypad Released Keypad Init Prototype Ret
51. n 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 90 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 Toggle switch 6 4 Multiplexed Seven Segment Displays Temperature sensor 90 91 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 1s 00010000 then the output is 4 The output is returned in the work register 91 92 Prof M Abdelati Summer 2008 9 3 A student has connected dipswitch to RB like this What are your comments b Assume that you have a Mico C project files folder 1 What are the extensions of the essential files 11 If you want to rename the project can you rename those essential files only If no what
52. oC 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 void Usart Init const unsigned long baud rate Returns Nothing Description 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 61 Usart Init 2400 Usart Data Ready
53. ogram Memory RESET Vector 0000h Peripheral Interrupt Vector 0004h User Memory Space 3FFh 1 7 Implementing Your First Application 1 7 1 Hardware connection C1 CRYSTAL DISC C LEN e C2 15 9 30 HOUT R3 L E t WEIR 10 Hw x n R1 im f PIC TEFE AA D1 LED G REEN 1 7 2 Software program LIST P PIC16F84A INCLUDE lt P16F84A INC gt CONFIG XT OSC amp PWRTE ON amp OFF amp WDT OFF ORG 0X000 GOTO START ORG 0X004 RETFIE BSF STATUS RPO BANK1 BCF TRISB O RBO IS OUTPUT BSF TRISA O IS INPUT BCF STATUS RPO BANKO MOVF PORTA W MOVWEF PORTB GOTO LOOP END 1 7 3 Program compilation Tools MPLAB MPASM MPASM v03 20 02 Microchip Technology Inc Source File Name F ECOM4315 MyExamples2009 Ex1 Ex1 Browse Options MICROCHIP Radix Warning Level Hex Output Generated Files Default Default Default I7 ErorFile Hexadecimal All Messages C INHX8M List File Decimal Warnings and Errors NHX8S Cross Reference File Octal Errors Only C NHX32 Object File Macro Expansion Case Sensitive Default Default M On Tab Size 8 Extra Options X Exit Save Settings on Exit 1 7 4 Program Loading Tools WINPIC800 QL PROG ui QL PROG V2 34 F ECOM431 5 MyExamples2009 Ex1 Ext HEX DER File Program Option Port Selector
54. om www c qmcu com E mail pic1 1 6 com 1 7 5 Simulation tools Proteus PIC Simulator IDE 55 Ex1 ISIS Professional File View Edit Tools Design Graph Source Debug Library Template System Help CRYSTAL LED GREEN LED RED MINRES12R PICIBF844 RES D1 LED GREEN TEXT m gI OEN QS SORRY Ti No Messages Root sheet 1 start Google T Lecture1 Microsoft 5 PIC Simulator IDE Evaluation Copy File Simulation Rate Tools Options Help Program Location F ECOM4315 MyE xamples20095E x1 Ex1 HEX Microcontroller 8 Clock Frequency 4 0 MHz Last Instruction Next Instruction GOTO 0 009 x PORTA W Program Counter and W Register Instructions Counter 320 Pc Counter 1708 w Register og Real Time Duration 427 0 igs Special Function Registers SFRis General Purpose Registers Hex Binary Value Address andName Value 76543210 Add Value Addr Value O0ih R 0028 PCL 003h STATUS TT FSR 005h PORTA EELLLLLL 00 PORTB 0071 PORTC 008 PORTD 009 PORTE Ol h PCLATH rFrrrrrrr O0Bh INTCON
55. omplete Interrupt Enable bit 1 Enables the EE Write Complete interrupts 0 Disables the EE Write Complete interrupt TOIE TMRO Overflow Interrupt Enable bit 1 Enables the TMRO interrupt 0 Disables the TMRO interrupt INTE RBO INT External Interrupt Enable bit 1 Enables the RBO INT external interrupt 0 Disables the RBO INT external interrupt RBIE RB Port Change Interrupt Enable bit 1 Enables the RB port change interrupt 0 Disables the RB port change interrupt TOIF TMRO Overflow Interrupt Flag bit 1 TMRO register has overflowed must be cleared in software TMRO register did not overflow INTF RBO INT External Interrupt Flag bit 1 The RBO INT external interrupt occurred must be cleared in software The RBO INT external interrupt did not occur RBIF RB Port Change Interrupt Flag bit 1 At least one of the RB7 RB4 pins changed state must be cleared in software None of the RB7 RB4 pins have changed state Option Register EECONTRegister WRERR WREN WR RD INTFRRUPT When an interrupt occurs its corresponding flag bit is set It must be cleared in software in order to allow repeating interrupt events 2 5 3 Keeping the contents of important registers An important part of the interrupt process is the stack Its basic role is to keep the value of program counter after a jump from the main program to an address of a subprogram In order for a program to know how to go back to the point wher
56. ou can test the example from mikroC terminal 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 UsSart Data Ready 1 If data is received i Usart pesdi Read the received data Usart ZZ Send data vie USART while 1 r HW Connection 62 63 5 232 CN3 CON SUB D 9p CONNECT Receive MCU TO PC data Rx SERIAL CABLE CONNECT PC TO MCU send RS232 HW connection 63 64 M Abdelati Fall 2007 8 Electrical amp Computer Engineering Department Microcontrollers amp Microprocessors Based Systems ECOM 4315 Midterm Exam Duration 80 min 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 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 dela
57. rameters p7 po need to be a combination of values 0 7 e g 3 6 5 0 7 2 1 4 Requires Nothing Example Config amp PORTC amp PORTD 0 1 2 6 5 4 3 7 1 2 0 Lcd8 Init Prototype void Lcd8 Init unsigned short portctrl unsigned short portdata Returns Nothing Description Initializes LCD at Control port portctr1 and Data port portdata with default pin settings see the connection scheme at the end of the chapter 47 Requires Example Lcd8 Out Prototype Returns Description Requires Example Lcd8 Out_Cp Prototype Returns Description Requires Example Lcd8 Chr Prototype Returns 48 E c RS dSLEIDOEL 4 R W gt ctriport 5 D7 dataport D6 dataport ib DS gt delaport D4 dataport 4 D3 dataport dataport 2 D1 gt 1 DO diatabport iu Nothing Leds Init amp PORTB 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 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 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 initi
58. rogram 75 76 Prof M Abdelati Fall 2008 9 2 Referring to PICI6F84A answer the following 2 1 At what addresses 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 two s complement of PortB 76 77 Prof Abdelati Fall 2008 9 2 13 The following code has an Infinite loop Why MOVLW 3 MOVWF PORTB LOOP DECFSZ 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 PORTB W TRISA 2 16 The following routine toggles RB2 after an interrupt on RBO INT Find the bug ORG 0X004 MOVWF OEh SWAPF STATUS W MOVWF O0Fh STATUS RPO MOVLW 4 XORWF PORTB F BCF INTCON INTF SWAPF OFh W MOVWF STATUS SWAPF OEH
59. rt 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 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 void Lcd Out Cp char text Nothing Prints text on LCD at current cursor position Both string variables and literals can be passed dS text Port with LCD must be initialized See Lcd Config or Lcd Init Print Here at current cursor position Led Out Cp Herel 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 cnaracter Port with LCD must be initialized See Lcd Config or Lcd Init Print 4 LCD at line 2 char 3 Log Che Tit 44 Lcd_Chr_Cp Prototype Returns Description Description Requires Example LCD Command 45 void Lcd Chr Cp char character Nothing Prints character on LCD at current cursor position Both variables and literals can be passed aS character Port with LCD must be initialized See Lcd Config or Lcd Init Print at current cursor position void Lcd unsigned short command Requires Example Led Chr Cp s Lcd Cmd Prototype Returns Nothing Sends command to LCD You can pass one of
60. ry Device Device Key board Monitor 4 AIL 11 ll ___ Address Bus Control Bus 1 2 Instruction Handling Sequence Fetch Execute Control Bus WRITE J READY CPU Control Unit N Address Bus R Register L Mem U N y I ALU Data Bus 1 3 Pipelinin p 5 191 162 163 24 161 152 23 24 lai 152 l 23 24 PTI TI r1 52 33 ud PC Clockinsruction Cycle MOvLW 55h Fetch MDWWF PORTE Fetch BSF PORTA BITS Forced Instruction address SUB 1 Fetch amp UB 1 IExecute SUB 1 FetchSLIB 1 4 All instructions are single cycle exept for any program branches These take two cycles since the fetch instructions is flushed fram the pipeline while the new instruction is being fetched and then executed Instruction Pipeline Flow 1 4 Microcontrollers versus microprocessors 1 5 Harvard versus Von Neumann s Architecture RISC CISC Program Program U Data C P U 11 memory Address bus Address bus memory Address bus memory Instruction bus Data bus Data bus 1 6 PIC 16F84A 1 U RAT AAS a L 2 17
61. s with multiple PWM modules have PWM library which is identical to PWM1 i e you can use Init instead of PwM1 Init to initialize CCP1 Library Routines Pwm Init Pwm Change Duty Start Stop Init Prototype void Init unsigned long freq Returns Nothing Description 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 MCU must have CCP module Example Initialize PWM module at 5KHz Pwm Init 5000 Pwm Change Duty 56 Prototype Returns Description Requires Example Pwm_Start Prototype Returns Description Requires Example Pwm_Stop Prototype Returns Description Requires Example 57 void Pwm Change Duty unsigned short duty ratio Nothing Changes PWM duty ratio Parameter duty takes values from 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 MCU must have CCP module Pwm Init must be called before using this routine Set duty ratio to 759 Pwm Change Duty 192 void Pwm Start void Nothing Starts PWM MCU must have CCP module Pwm Init must be called before using this routine Pwm Start void Stop void Nothing Stops
62. structian 0 0 HOWE FSR Program Counter and Register Instructions Counter 2 FC omg FITTTTTTTTT Clock Cycles Counter 15 w Register p TTT r Real Time Duration 4 0 fas Special Function Registers General Purpose Registers GPAs Hex Binary Value Hex Hex Address 76543210 Add Addr Value 00th THRO DD2h PCL NBI STATUS TT 004 FSA TT 05 PORTA DOBh LLLI LL I 008 EEDATA ITTTTTTT 009h EEADR PCLATH DOBh INTCON D81h OPTION REG esp TTT 1 11 BEh TRISB 1 BEN mm Prescaler misis IL ILI I OL 14 C1 120R 2 5 Interrupts 33pF xa T OSC1 CLKIN OSC2 CLKOUT C2 CRYSTAL MCLR RA3 RA4 TOCKI 33pF R4 10k A LED GREEN PIC16F84A D2 L x 120R LED RED Ex4 Interrupt application LIST P PIC16F84A INCLUDE lt P16F84A INC gt _ CONFIG XT OSC amp PWRTE ON amp OFF amp WDT OFF ORG 0 000 GOTO START ORG 0x004 MOVWF OEh push W and Status MOVF STATUS MOVWF OFh STATUS RP0 MOVLW 4 XORWF PORTB F BCF INTCON INTF Reset the Interrupt Flag MOVF OFh W pop W and Status MOVWF STATUS SWAPF OEH F SWAPF OEH W RETFIE START BSF STATUS RPO BA
63. 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 7 Timers int 1 void interrupt INICON INICOUNH 05111111102 LE porth bDDDIDODO Db0 1 102 if porth 0600100000 0b0 1 15 if porth 0b01000000 0b0 1 202 0610001000 D 0 0 WFD whi 1 1 gt 0 J i 10 1 J F 10 10 PORTE 1 Delay 15 995 840 2 1 portami 02 70 71 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 PICI6F84A 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 5 b d e g 72 M Abdelati Fall 2007 8 Have you attended the department workshop last month If you answered yes in part a have you submitted a report If you answered yes in part b write down 3 comments about the workshop Have you submitted a report summarizing the course material Who
64. t sPORTB JInsterelsse LCD on JORTU Lcd Cmd LCD CLEAR J Clear display Lod Cmd TCD CURSOR OFE s 77 Cursor off Led 1 Key 37729 hed Outi 2 1 do kp 0 Wait for key to pressed do un comment one of the keypad reading functions kp Keypad Released kp Keypad Read while kp Crier prepare value for output if kp gt 10 52 54 else kp 47 J 1 om LCD Led Chr l 10 Kp WNOFrJGTOSLE ONE EXE Led 20 while 1 HW Connection VOC CSVABLOld 4x4 Keypad connection scheme 53 53 54 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 unsigned Read unsigned short channel Returns 10 bit unsigned value read from the specified channel Description Initializes PIC s 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 P1
65. 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 85 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 0800080009008 31688308 100 5 Extract the assembly language instructions from the record given that it has the following format Record Information I Mark Offset pa ee Chick Sum 1 byte 1 byte 2 bytes 1 byte 1 Machine Code Machine Code binary Assembly code 85 86 Prof M Abdelati Summer 2008 9 86 87 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 the work register The EEwrite macro
66. ugh MCLR and the Watchdog Timer Reset On any device RESET these pins are configured as inputs This is the value that wil be in the port output latch 95 2 PIC 16Fxx Instruction Set Mnemonic 14 Bit Opcode Status Operands p yc MSb LSb Affected _ BYTE ORIENTED FILE REGISTER OPERATIONS ADDWF Add W and f ANDWF AND W with f CLRF Clear f CLRW Clear W COMF Complement f DECF Decrement f DECFSZ Decrement f Skip if 0 INCF Increment f INCFSZ Increment f Skip if 0 IORWF Inclusive OR W with f MOVF Move f MOVWF Move W to f No Operation Rotate Left f through Carry Rotate Right f through Carry Subtract W from f Swap nibbles in f Exclusive OR W with f BIT ORIENTED FILE REGISTER OPERATIONS Bit Clear f 01 0050 bfff Bit Set f 01 Olbb bfff Bit Test f Skip if Clear 01 10bb bfff Bit Test f Skip if Set 01 libb bite LITERAL AND CONTROL OPERATIONS DDLW Add literal and W ANDLW AND literal with W CALL Call subroutine CLRWDT Clear Watchdog Timer GOTO Go to address IORLW Inclusive OR literal with W MOVLW Move literal to W RETFIE Return from interrupt RETLW Return with literal in W RETURN Return from Subroutine SLEEP Go into standby mode SUBLW k Subtract W from literal XORLW k Exclusive OR literal with W Note 1 When an I O register is modified as a function of itself e g MOVF PORTB 1 value used will be that value present on the pins themselves For example if the data latch 1
67. unchanged unimplemented locations read as 0 Shaded cells are not used by REGISTER 2 2 OPTION REGISTER ADDRESS 81h RW 1 RAN 1 RAN 1 RW 1 RAN 1 RAN 1 RAN 1 R W 1 bit 7 bit bit RBPU PORTB Pull up Enable bit 1 PORTB pull ups are disabled PORTB pull ups are enabled by individual port latch values bit 6 INTEDG Interrupt Edge Select bit 1 Interrupt on rising edge of pin Interrupt on falling edge of RBO INT pin bit 5 TOCS TMRO Clock Source Select bit 1 Transition on 4 pin Internal instruction cycle clock CLKOUT bit 4 TOSE Source Edge Select bit 1 Increment on high to low transition on RA4 TOCKI pin Increment on low to high transition on RAA TOCKI pin bit 3 PSA Prescaler Assignment bit 1 Prescaler is assigned to the WDT Prescaler is assigned to the Timer0 module bit 2 0 PS2 PS0 Prescaler Rate Select bits Bit Value TMRO Rate WDT Rate 000 1 2 1 1 001 1 4 1 2 010 1 8 1 4 011 1 16 1 8 100 1 32 1 16 101 1 64 1 32 110 1 128 1 64 111 1 256 1 128 2 6 1 Delay with TIMERO A general formula for calculating the number of timer beats per second is as follows 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 theTMRO register The range of both P and R in this formula is 1 to 256 Delay TMRO W
68. upt mechanism 88 89 Prof M Abdelati Summer 2008 9 Electrical Engineering Department Microcontrollers amp Microprocessors Based Systems ECOM 4315 Final Exam Duration 120 min Q Grade IN _2 jo sof Benare u eare ID ps _ M Phone or email contact Tw 50 Directions Use your engineering judgment to assume correct any missing wrong information and don t interrupt the instructor for any reason The exam 15 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 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 l 2 3 4 5 6 7 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 a
69. urns Description Requires Example Keypad Read Prototype Returns Description Requires Example 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 Nothing Keypad Init amp PORTB unsigned short Keypad Read 1 16 depending on the key pressed or if no key is pressed Checks if any key is pressed Function returns 1 to 16 depending on the key pressed or if no key is pressed Port needs to be appropriately initialized see Keypad Init kp Keypad Read 51 52 Keypad_Released Prototype unsigned short Keypad Released Returns 1 16 depending on the key Description 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 Port needs to be appropriately initialized see Keypad Init Example kp Keypad Released 7 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 amp PORTC Led Ini
70. y a Provide a hardware design for the system b Write a C code to implement the required functionality of the system 83 84 Prof M Abdelati Summer 2008 9 Electrical Engineering Department Microcontrollers amp Microprocessors Based Systems ECOM 4315 Midterm Exam Duration 90 min Gue I lli 2 am afwo SE eaer __ ano H Phone or email contact Tu 30 Directions Use your engineering judgment to assume correct any missing wrong information and don t interrupt the instructor for any reason The exam 15 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 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 l 2 3 4 5 6 7 ask for paper revision and don t get extra points You are allowed to call the instructor once at most during
71. y language in the microC without any restrictions A B 6 The addresses of EEPROM memory starts at location 0x00h amp extend to 0x3f but consists of 64 byte A B 7 Using Macros are preferable than using subroutines A B 19 80 Prof M Abdelati amp Mr Almobaied Fall 2008 9 2 Referring to PIC16F84A choose the most suitable answer I The external recourses of the interrupts RB0 amp RB4 7 TIMER ZERO Finishing writing on the EEPROM All the above 15 true ao of To disable all the interrupts we can a put 1 in the GIE b putO in the GIE c disable EEIE TOIE RBIE amp INTIE d a amp c To select the prescaler for the WDT we assign PSA to be a b 0 c d Don t care The instruction 52 is cycle instruction a one b two c oneor two depending on the result d or two depending on the initial value The indirect addressing 15 accomplished by using P FSR register b INDF register c Botha amp b d None of the above Machine code 15 a The Instruction decoder in the processor that interprets the operation code of the instruction b Assembly level symbolic source code c The binary address of the cell in program memory an instruction lies d The binary code in Program memory that the processor executes A subroutine 1s a program that links software routines into one executable program
72. y the submission of your answer sheets don t answer each question in its allocated space separate page or pu S x qnc 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 1n the course at least Good luck 64 65 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 7 segment display are interfaced to a PIC16F84A microcontroller use minimum extra components 2 Refer to the followine Simulator Ss PIC Simulator IDE The Hive File Simulation Rate Tools Options Help STEP a What is the value of FSR register Program Location traPICasm MvyE xamplessM T HE Microcontroller PICT BF EAA Clock Frequency 40 MHz Last Instruction Next Instruction 0255
73. ze 0005 0006 0007 e What 1s the difference between an instruction and a directive in assembly language 0009 0008 000A 0008 000 OO I g Why the register TMRO is also called 0013 Counter register 0014 0015 0016 0017 h What 1s the most probable execution time of PIC16F84A instructions given 0018 that its oscillator frequency 15 4 0019 001A 0000 f What are the registers involved during 0006 writing to the EEPROM 000F 0010 66 67 M Abdelati Fall 2007 8 5 The following program is described at class under the name 2 LIST 16 84 INCLUDE P16F84A INC What 15 the function of this __CONFIG OSC amp PWRTE ON amp OFF amp WDT OFF program ORG 0 000 GOTO START ORG 0 004 b If the constant in the instruction RETFIE pointed by the arrow is replaced by BSF STATUS RPO BANK1 254 then the program will not BCF TRISB 0 RBO IS OUTPUT function properly However if it is STATUS RPO BANKO MOVLW 01h replaced by 253 the program XORWF PORTB F functions as required CALL DELAY What 1s the cause of this bug 7 7 II s s Describe a method to resolve this DELAY MOVLW 255 bue MOVWF OCH LOOP1 NOP MOVLW 25 MOVWF NOP DE

Download Pdf Manuals

image

Related Search

Related Contents

  取扱説明書・追加分 (MacOS Xでの利用方法)    Ozeri OZF6 Use and Care Manual  Newstar FPMA-D050DBLACK flat panel desk mount  ETA/BSE-in-NX User`s Manual  Descargar Información  La location de camping-cars - Motorhome Rent Motorhome Rent  

Copyright © All rights reserved.
Failed to retrieve file