You are on page 1of 45

3.

PIC16F877 Microcontroller In this section, properties of PIC16F877 microcontroller,CCS compiler, ICD-S, the reference book Embedded C programming and the microchip PIC are briefly explained to give a general idea; it may seem confusing for a first time reader who is not familiar to microcontrollers technology or C programming. However, as the funtionality of the components such as timers, A/D converters, I/O Ports are explained in detail in Section 3 as they are being used in the experiments, the fundemental concepts would be better understood and, the reader can flashback to this section to view the schematics and the specifications. PIC16F877 is one of the most commonly used microcontroller especially in automotive, industrial, appliances and consumer applications. In Figure 1, the block diagram of the PIC16F877 is illustrated. The core features of PIC16F877 are:
High

performance RISC CPU

Only 35 single word instructions to learn All single cycle instructions except for program branches which are two cycle Operating speed: DC - 20 MHz clock input DC - 200 ns instruction cycle Up to 8K x 14 words of FLASH Program Memory,Up to 368 x 8 bytes of Data Memory (RAM) Up to 256 x 8 bytes of EEPROM Data Memory Pinout compatible to the PIC16C73B/74B/76/77 Interrupt capability (up to 14 sources) Eight level deep hardware stack Direct, indirect and relative addressing modes Power-on Reset (POR) Power-up Timer (PWRT) and Oscillator Start-up Timer (OST) Watchdog Timer (WDT) with its own on-chip RC oscillator for reliable operation Programmable code protection Power saving SLEEP mode

Selectable oscillator options Low power, high speed CMOS FLASH/EEPROM technology Fully static design In-Circuit Serial Programming. (ICSP) via two pins Single 5V In-Circuit Serial Programming capability In-Circuit Debugging via two pins Processor read/write access to program memory Wide operating voltage range: 2.0V to 5.5V High Sink/Source Current: 25 mA Commercial, Industrial and Extended temperature ranges Low-power consumption: - < 0.6 mA typical @ 3V, 4 MHz - 20 A typical @ 3V, 32 kHz < 1 A typical standby current

The peripheral features of the PIC16F877 are: Timer0: 8-bit timer/counter with 8-bit prescaler Timer1: 16-bit timer/counter with prescaler, can be incremented during SLEEP via external crystal/clock Timer2: 8-bit timer/counter with 8-bit period register, prescaler and postscaler Two Capture, Compare, PWM modules Capture is 16-bit, max. resolution is 12.5 ns - Compare is 16-bit, max. resolution is 200 ns - PWM max. resolution is 10-bit 10-bit multi-channel Analog-to-Digital converter Synchronous Serial Port (SSP) with SPI. (Master

mode) and I2C. (Master/Slave) Universal Synchronous Asynchronous Receiver Transmitter (USART/SCI) with 9-bit address detection Parallel Slave Port (PSP) 8-bits wide, with external RD, WR and CS controls (40/44-pin only) Brown-out detection circuitry for Brown-out Reset (BOR) The Pinouts of the PIC16F877 is given in Figure 3.0-2

Figure-3.0-1 PIC16F877 Block Diagram

Figure 3.0-2 Pin diagram of PIC16F877 3.1. Flash PIC development board Usually, a microcontroller by itself is not sufficient to perform the intended tasks. For instance, an oscillator chip is necessary to time the programmed instructions. In order to investigate the capabilities or to test a given microcontroller, obviously it is vital to build the proper circuitary. Example: potentiometer and a power supply to simulate analog inputs or LEDs to simulate the digital outputs. Hence, some hardware and sofware vendors provide the microcontroller with the supplemantary circuit elements on the same breadboard. These boards are called Development Boards. One can also build a development board himself/herself if he/she is willing to go through the painsaking process of building the circuit.

Figure-3.1-1 FlashPIC Development Board The development board used in the series of experiments is Flash PIC development board. (Figure3.1-1) It has the following features: - RS232 through a 9-Pin D-Shell as well as screw terminals and a jumper header. - Up to 32K words of In-System Programmable FLASH memory with up to 256 bytes of EEPROM and up to 1.5K of Internal RAM (depending on processor selection). - Up to 8, 10 bit, Analog Inputs, using either internal or user supplied reference. - 9 I/O controlled LEDs, 8 of which are jumper selectable. - 32KHz watch crystal for on-board Real-Time operations. - A universal clock socket allows for canned oscillators, as well as a variety of crystals, ceramic resonators, and passive terminations. - 0.1 centered headers provide for simple connection to the processor special

function pins and I/O. - A 6-pin, ICD connection is provided for in-system programming and debugging. This connection is directly compatible with the Microchip ICD, ICD2 and CCS ICD-S programming hardware. Flash PICs can also be programmed through RS232 using an appropriate boot loader application. - On-board regulation allows for power inputs from 8-38VDC with an LED power indicator. - Termination is provided for 5VDC output at 250ma 3.2. CCS PIC-C compiler The CCS PCW compiler is specially designed to meet the special needs of the PICmicro MCU controllers. These tools allow developers to quickly design application software for these controllers in a highly readable, highlevel language. The compilers has some limitations when compared to a more traditional C compiler. The hardware limitations make many traditional C compilers ineffective. As an example of the limitations, the compilers will not permit pointers to constant arrays. This is due to the separate code/data segments in the PICmicro MCU hardware and the inability to treat ROM areas as data. On the other hand, the compilers have knowledge about the hardware limitations and do the work of deciding how to best implement your algorithms. The compilers can efficiently implement normal C constructs, input/output operations and bit twiddling operations. The compiler can output 8 bit hex, 16 bit hex, and binary files. Two listing formats

are available. Standard format resembles the Microchip tools and may be required by some third-party tools. The simple format is easier to read. The debug file may either be a Microchip .COD file or Advanced Transdata .MAP file. All file formats and extensions are selected via the Options|File Formats menu option in the Windows IDE. The usage of the copiler is explained in Section 2.0 Getting started. The reference book Embedded C Programming and the Microchip PIC comes with a demo version of the compiler. 3.3. ICD-S Debugger/Programmer The ICD-S programmer is the hardware/firmware interface to burn the .hex files to the Microchip PIC. The ICD unit works with CCS's PCW debugger or CCS's stand-alone ICD control software. CCS's PCW debugger is a very robust debugger integrated with PCW, and provides very detailed debugging information at the C level. The stand-alone control software allows you to quickly program target chips using ICD's ICSP. The control software also lets you update the ICD unit's firmware without having to remove the chip from the ICD unit. (Using these software tools requires you to have loaded the CCS-ICD firmware onto the ICD unit, which is loaded by default). Authors note 01/22/04 : I found it odd that prllc.com does not provide a freeware program like AVR bootloader.exe for FlashPIC Development board as they do for Atmel AVR development board, that would enable programming the chip via serial communication connector P1 in-built to the development board. I don`t think that Development board and Compiler vendors should force the costumers to buy products like ICD-S where an option like programming via serial link exists. I have seen a program in http://sjeffroy.free.fr/Prog__PIC/BootLoader/bootloader.html which seems like it might work given the fact that bootloader file loader.hex pre-exists on the chip. Personally, I did not try running this program and programming the chip via RS-232.

Figure-3.3-1 FlashPIC Development Board 3.4. The Reference Book: Embedded C Programming and the Microchip PIC by Barnett, Cox and OCull This book is a good guide for introducing the microcontroller technology. First chapter is dedicated to teaching basic C programming however, this book shouldnt be considered a C programming handbook. One should always have a book like: Teach yourself C by Zhang ISBN 0-672-31861 as a C programming reference guide for beginners. This book is designed to teach C language programming as it applies to embedded microcontrollers and to fuel knowledge in the application of the Microchip family of PIC microcontrollers. Coverage begins with a step-bystep exploration of the C language showing readers how to create C language programs to solve problems. PIC processors are then studied, from basic architecture to all of the standard peripheral devices included in the microcontrollers. Numerous worked-out example programs demonstrate common uses for each of the peripherals. Readers are subsequently introduced to the built-in functions available in C, to speed their programming and problem solving. Finally, readers are taken through use of the C Compiler, and to help custom learn to efficiently develop projects.

Figure-3.4-1 Embedded C Programming and the Microchip PIC Included with the book is a CDROM containing samples all of the example programs from the book as well as an evaluation version of the CCS-PICC Compiler. Author`s note 01/22/04 : In the first examples and projects in chapter 1, functions like scanf and printf are used that require prior knowledge to interface the board through RS-232 which is introduced in the late chapters of the book. It might be discouraging for the student not being able to do the first project of the book, hands-on. Although I was able to find answers to most of my questions about using the C compiler and the hardware however, I had to do a lot of skipping between chapters and Appendixes to find these answers which was time consuming. In general it is a nice and descriptive text book. 4. Experiments The most quick and effective way of learning a new topic is, having hands on experience. In this section we will conduct some experiments using the FlashPIC Development board to which would give us a jump start on in PIC usage. 4.1. LED Experiment The digital I/O and the timers will be discussed with this experiment. The program will count from 0 to 255 and output the binary equivalent of this number to PortD every 2 seconds. The digital I/O peripherals are discussed in detail in the next experiment Dipswitch. In this experiment we will focus on the usage timers.

Timers and counters are one of the most commonly used perpheral in a microcontroller. They can be used to measure time periods, speed and provide output signals in a specified rate. The PIC16F877 has 4 timers timer0, timer1, timer2 and watch dog timer. Timer0 and timer2 are 8 bit timers and timer1 is a 16bit timer. The inportant issue is to know when the counter reaches the maximum value (255 in 8 bit timers and 65,535 is 16bit timers) and rolls over. The watch dog timer is a safety device. When an unepected event occurs, the watch dog timer resets the microcontroller. In this experiment we will use the watch dog timer as our timer to time the digital output. #use delay(clock=10000000, RESTART_WDT) The command line above, is used to tell the compiler to insert an appropriate code to automatically reload the WDT during delay functions. delay_ms(2000) command line is used to place a delay the event 2000ms in every cycle of the while loop. output_d(z) command line is used to output the digital number through portD. Instructions: 1. We type the code in Figure4.1-1, compile it and program the chip as explained in Section 2. The code can also be downloaded from here ledwdt.c.

Figure4.1-1 The source code for the LED experiment 2. We can unplug the ICD-S and run the experiment and observe the progress of the count every 2 seconds. ] 4.2. Dip switch Experiment The goal of this experiment is to illustrate digital inputs and outputs. An 8 bit binary number is introduced using an 8-position dip switch. The input representing the 8 bit digital number is given through the PIC16F877 through portB using the dipswitch circuit. The software outputs this binary number via portD LEDs. There are 5 I/O ports in the in the PIC16F877. The individual bits and the whole channel can set to digital inputs or outputs. The following commands are used to set the ports to output: set_tris_d( 0x00 )

set_tris_b( 0xFF ) With these command lines, port D and port B is set to output and input respectively. The following commands to read and input from port B and write it to port D respectively. z=input_b() output_d(z) The following command is also used to activate the port B pullups. port_b_pullups(TRUE) The procedure for the experiment: 1. Place the dipswitch, (4.2-1) 8 pin header and single pin header as illustrated in Figure4.2-2 on the component side of the board and solder them on the solder side of the board. Only the holes which have been used are illustrated in Figure 4.2-2.

Figure-4.2-1 The 8 Position Dip Switch

Figure-4.2-2 The layout of the dipswitch breadboard 2. One side of the switch is jumped together and tied to common ground. The single pin header is jumped to the common ground of the development board using an alligotor clip. The other side of the switch is tied to Port B using a ribbon cable. See Figure-4.2-3 and Figure-4.2-4.

Figure-4.2-3 Schematics of the Dip Switch Circuit

4.2-4 Connection details of the dip switch circuit to the Development Board

4.2-5 The experiment setup 3. We type the code in Figure4.2-6, compile it and program the chip as explained in Section 2. The code can also be downloaded from here dip.c. Note that the I/O process is located in an infinite loop with the while(1) command line. Hence, the program is constantly reading from port B and writing to Port D.

4.2-6 The source code for the dip experiment 4. We can unplug the ICD-S and run the experiment and observe the binary numbers change as we change the dip switch positions. 4.3. ADC Temperature Measurement In this experiment, the usage of the in built 10-bit Analog to Digital Converter will be demonstrated. The temperature sensor LM35 is wired to channel 1 of the ADC port; portA. Then this temperature sensor is dropped in boiling water which is left in room temperature to cool down and the temperature is read and recorded by the PIC16F877 every 5 minutes. Since the LM35 is not water proof, the chip is placed in a container and the container shall be sealed.

The procedure for the experiment: 1. Wire the LM35 to channel 1 of PortA and the power supply (9V battery) The pin out of the LM35 is given in Figure 4.3-1. The wiring shematic is given in Figure 4.3-2. Jumpers are placed on the unused analog channels to prevent the cross talk between channels and noise.

Figure 4.3-1 Pin out of the LM35 Temperature Sensor

Figure 4.3-2 The wiring schematics for the temperature sensor experiment

2. Type the following code (Figure 4.3-3) and burn it on the chip after compiling it. By implementing the line #device ADC=10, the analog to digital conversion is set to 10bit resolution. The LM35 outputs the temperature with the sensitivity of 10mv/oC (Example: 25 oC corresponds to 250mv). The range of the ADC of the PIC Development Board is 0 to 5V and the ADC conversion is 10bits. Hence, the resolution is 210-1=1023. So the formula for analog to digital conversion would be;
Temperature in Celsius = 5.00 * Voltage read from LM35 * 100.00/1023.00

Figure 4.3-3 Source code for the temperature sensor experiment 3. The LM35 is not waterproof. Hence, we need to place it in a plastic sphere (like the ones in the bubblegum machines) and epoxy the hole to seal the sphere. Before sealing the sphere for good, we need to put some weight (Example: coins nuts and bolts) in the sphere to prevent the sphere from floating in the water. (See Figure 4.3-4) We need to keep the water level low so that we do not soak the wires coming out of the plastic sphere in hot water.

Figure 4.3-4 Overall experiment setup with the LM35 sealed 4. In this application, the RS-232 communications will be used as the data interface between the PC and the PIC16F877 development board. Notice that PIC Flash Development board comes with 2 separate means of serial communications which are marked in Figure 4.3-5.

Figure 4.3-5 RS-232 Communication pins Due to the convenience of using a standard RS-232 cable one would prefer to use the standard DB-9 connector which is labeled P1 however, the transmit and receive pins for this cable/connector do not match the transmit and receive pins for the standard RS-232 cable so, we have to use the screw terminal RS-232 communications which is labeled RS232. So we cut the female connector off the standard RS-232 cable and strip the connector down to its shell. (Figure 4.3-6)

Figure 4.3-6 DB9 Female connector Now we can solder the Receive(R-pin number 3 ), Transmit(T-pin number 2) and Ground (G-pin number 5) pins according to the wiring schematic given in Figure 4.3-7. Keep in mind that this wiring scheme is given from the front view of the connector. The picture of the wiring is in Figure 4.3-8.

Figure 4.3-7 Wiring Schematics of the RS-232 communications

Figure 4.3-8 View of the Development board with RS-232 communications established 5. After checking the wiring and making sure the LM35 is sealed properly, we can power up the development board and plug in the RS-232 serial communications cable to the computer and start the hyper terminal application which will be used for data acquisition. The usual path of the hyper terminal is start menu>Programs>Accessories>Communications>hyperterminal. Settings of the hyper terminal communications is given in Figure 4.3-9.

Figure 4.3-9 Hyper terminal Communications Settings Now we are ready to acquire data. Due to the while loop we have implemented in the source code, it will take 5minutes to acquire our first set of data. It would be convenient to delete the ten delay_ms(30000) lines and put a single delay_ms(500) to test if we are acquiring meaningful data. Depending on the applications unfortunately, RS-232 is somewhat a troublesome communication link. If you experience problems with communications, make sure the ICD-S software is not running and ICD-S is not plugged in the development board, try connecting and disconnecting until communications is established. If there are problems with the acquired data, we should try recycling power of the development board and rebooting the PC. A screen shot of the hyper terminal screen is given in Figure 4.3-10.

Figure 4.3-10 Screen Shot of the hyper terminal screen 6. The values recorded through hyper terminal screen can be saved as a text file and be opened in MS Excel and plotted. The results of the experiment are given in Figure4.3-11. Notice that the first and second values of the curve is 52 and 79. Since the water is boiled we would expect the first reading to be 100oC. However, the coins and the plastic bulb, which is at room temperature initially, absorbs some of the energy therefore the temperature drops significantly and reaches a steady state 79 oC before decaying.

Figure 4.3-11 Cooling curve of the boiled water in ADC thermistor experiment 4.4. Open Loop and Close Loop Temperature Control As a final experiment we will get a chance to deploy all the features of PIC16F877, which we previously have investigated. In addition to these features we will also learn how the usage of a 8-bit Digital to Analog Converter (DAC). As in the ADC experiment, the temperature sensor LM35 is placed into a cup of water. This cup is also exposed to hot air from a blow dryer which can be considered as a disturbance to the system intended to be controlled. Speed of a PC fan is regulated, to keep the water temperature at 27oC. Obviously, we should not ignore the effects of the natural convection as an additional disturbance. Two different controls approaches are used while regulating the temperature: Closed Loop Control: The fan speed is adjusted according to the temperature feedback every time step. The generic block diagram of the control system is given in Figure 4.4.1.

Figure 4.4-1 Generic Block Diagram of Closed Loop Temperature Control System Open Loop (Bang Bang) Control: The fan is either turned on at maximum speed or turned off depending on temperature feedback exceeding the temperature goal. Actually, this control system can also be considered to be close loop since the control system responds to a feedback, however since the feedback only triggers a switching operation, it is considered an open loop operation. The generic block diagram of is given in Figure 4.4-2.

Figure 4.4-2 Generic Block Diagram of Open Loop Temperature Control System The procedure of the experiment: 1. As the first step of the experiment, we will build our DAC/LF353 Op-Amp Circuit. A schematic of the DAC /Op-Amp circuit is given in Figure 4.4-3. The theory of operation for this circuit is that when an eight bit word is sent to the digital to analog converter (DAC), the DAC outputs a current that is defined in equation 2.1. Equation 4.4. 1

The output current is then fed into the op amps of the LF353 integrated circuit. The output from the LF353 circuit is defined:

Equation 4.4. 2

The DAC/LF353 card takes a digital word as an input, and outputs a proportional voltage. In this application the digitalword of 181 will result in an output voltage of 4.2 V, given a reference voltage of +12 V. 181 corresponds to fans minimum speed. Digitalword of 255 will produce output of 7.5V which is the maximum speed of the fan. All the pins of PortD of the PIC16F877 is set for output and they are wired to the DAC/LF353 circuit. Illustration of DAC/LF353 circuit is given in Figure4.4-4.

Figure 4.4-3 Schematics of the DAC/LF353 Op-amp circuit

Figure 4.4-4 DAC/LF353 Op-amp circuit 2. As the second step we can build our TIP31 Power Transistor Circuit. A schematic of the TIP31 power transistor circuit may be found as Figure 4.4-5 This circuit is necessary because motors do not run on voltage, rather they run on current. The current is obtained from an external power supply, which is added proportionally to the voltage that is input to the TIP31 circuit. The TIP31 works by reading a reference voltage from its base pin (b), then an equivalent voltage supplied by the a source attached to the collector (c), is allowed to pass to the emitter (e). This allows for an external power supply to be regulated by a low current circuit. The DAC/LF353 Op-amp circuit is illustrated in Figure 4.4-6.

Figure 4.4-5 Schematics of the Power Transistor TIP31 Circuit

Figure 4.4-6 Power Transistor TIP31 Circuit 3. For this experiment, as we review the schematics, it is evident that we need a power supply which can give us the following voltages:12V,-12V and 5V. We can use a common PC power supply for this application. However we need to make a slight modification to the power supply. The PC power supplies are switching supplies. Hence, they require proper amount of load to be operational. The following site is a nice guide for modifying PC power supplies for general use:

http://web2.murraystate.edu/andy.batts/ps/powersupply.htm. The main idea is to add a 10ohm 10watt resistor across 5V and common to apply the necessary load for operation. However, the resistor gets extremely hot; so, it would be appropriate to apply a heat sink on the resistor and place the resistor in front of the power supply fan (Figure-4.4-7) to avoid resistor failure which would eventually lead to power supply failure.

Figure 4.4-7 Power supply with load applied 4. Now we can start assembling the circuit. The reference voltage of DAC/LF353 is tied to +12V of the power supply. The grounds of all the components (Development board, LM35, DAC/LF353, TIP31 Power transistor circuit/DC Fan) are tied to the power supply ground. The output voltage of Pin7 of LF353 is tied to the TIP31 base. The LM35 is wired as described in section 4.3 ADC Experiment. This time instead of using a 9V battery to power the LM35, we can use 5V power supply. The RS-232 communications cable is wired as described in the ADC experiment in section 4.3 and is plugged into the computer. We also need a blow-dryer for this experiment as a disturbance to the system as described above. While doing the wiring, preparing the hardware necessary for this experiment, be sure to check the wiring before putting power to it. Each sub-assembly should be tested separately before putting the experiment setup together as a whole. For instance, once the DAC/LF353 circuit is prepared, run the dip.c program and check if the voltages correspond to the digitalwords using a voltmeter. The Experiment setup is illustrated in Figure-4.4-8.

Figure-4.4-8 The Experiment Setup 5. We are ready to program the chip. The code given in Figure4.4-9 is used for the close loop application. The code is also provided in file project3.c. There arent any new commands introduced with this code. The digitalword=181 can be considered as the threshold value which gives 4.2V and generates enough current through the TIP31 circuit so that the fan rotation starts. Furthermore, the digitalword=255 generates 7.5V which generates the highest speed using the hardware listed in this section. So, we can control the speed through the digital word ranging from 181 to 255. The resolution is 255-181=74 steps. We use Kp=2.5 as the proportional gain of the control system. This seems to be an ideal value for the operational range and the cooling load involved.

Figure4.4-9 The source code for the Open Loop (Bang-Bang ) Control is given in Figure4.4-10. It is also available with file project3bb.c. The temp_comparator variable compares the temperature feedback with the target temperature and switches the fan on at full speed or off.

Figure4.4-10 6. We are ready to program the chip and start the experiments. In the first experiment, the initial temperature of the water is chosen to be 42oC. As stated before, the target temperature is 27 oC. In the second experiment the, the water is heated from 16 oC to the target temperature 27oC. These two experiments are conducted both using the close loop and open loop program. The data recording is performed via the hyperterminal screen as described in Section 4.3. All the recorded data is also provided in Appendix A in Excel Spreadsheets.

Cooling Experiments: In Figure4.4-11 and Figure4.4-12, the results Close Loop and Open Loop cooling are given respectively. While reviewing the graphs, keep in mind that, the negative speed commands mean digital words smaller than 181 which correspond to motor currents smaller than the threshold level for the DC Fan to move. So, the DC Fan does not move with the negative speed commands. These values are given only to illustrate how digitalword changes with varying temperature level. The closed loop system cools down to the steady state between 500sec and 2200sec. So, it takes roughly 1700 seconds for it to cool down. However for the open loop system, since the fan is commanded to its maximum speed while the temperature is higher than the target, it takes much less time (1800-500=1300sec) for it to cool down to the desired steady state. In the closed loop system, the system seems to be critically damped since there is steady state error and no overshoot. We can increase the gain and check the overshoot if a faster responding system with minimal steady state error is desired.

Figure4.4-11 Cooling Curve for Close Loop Fan Speed Control

Figure4.4-12 Cooling Curve for Open Loop Fan Speed Control Since in the open loop cooling, temperature feedback is intermittently under the influence of noise, the control system becomes unstable especially around 1000 second mark. If the effects of noise becomes more significant, a low pass filter can be added to the circuit; but in this case the effect is minimal. Since the fan is either turned on or off, the fan commanded speed takes values either 0 or 74 as we converge to the steady state. One might find it difficult to follow what speed commands are given at each time-step to the DC fan at steady state temperature. The Excel Sheets given in Appendix A can be used for more thorough analysis of the data. Heating Experiments: In Figure4.4-13 and Figure4.4-14, the results Close Loop and Open Loop cooling are given respectively. Since in both close loop and open loop system the fan is off before converging to steady state, the rise time for both systems are roughly the same which is approximately 1000sec. We observe intermittent electrical noise problems which do not impact the control system performance significantly. In close loop control mode, around 2300sec mark, after the system reaches steady state, the hairdryer is moved closer to the cup, in order to experiment increasing the effect of the disturbance. 60 seconds later the temperature starts increasing. Roughly 100seconds later, the control system starts to stabilize the increasing temperature and around 2500second

mark, the temperature is back to target temperature. This is a good indication that the system responds very slowly to varying disturbances.

Figure4.4-13 Heating Curve for Open Loop Fan Speed Control

Figure4.4-14 Heating Curve for Open Loop Fan Speed Control 7. For the heating, the performance of the open loop and close loop systems are very similar. As the results are reviewed for cooling , the close loop control system seems to be critically damped. Obviously, we can improve the rise time by increasing the gain. Since we get a better rise time for the open loop system and it takes less time to reach steady state, it is more preferable over the Closed Loop system with proportional gain of Kp=2.5.

Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

EECS 100/43 Lab 8 Introduction to the PIC Microcontroller


1. Objective In this lab, you will learn about how to use your PIC Microcontroller. This lab is the first lab for the digital component of the EE100 project. The goal of the project is to simply display the strain gauge measurement from your Strain Gauge lab on the LCD display on your PICDEM 2 Plus demo board. 2. Equipment a. Breadboard b. Wire cutters c. Wires d. Oscilloscope e. Function Generator f. Power supply g. PICDEM 2 Plus demo board h. MPLAB ICD 2 (Incircuit Debugger) i. MPLAB IDE installed on lab computer1 j. Various connectors for power supply, function generator and oscilloscope. 3. Theory a. Introduction to microcontrollers [1] You have all heard of the Intel and AMD microprocessors. These little devices are the brains of your computers. However, there is another very important CPU (Central Processing Unit) in the digital world: the microcontroller. Microcontroller differs from a microprocessor in many ways. First and the most important is functionality. In order for a microprocessor to be used, other components such as memory, or components for receiving and sending data must be added to it. On the other hand, microcontroller is designed with most of the components above built-in. Very few external components are needed for its application. Thus, we save the time and space needed to construct devices. You will learn in lecture how digital electronics and systems are a beautiful abstraction of the analog world. You will also learn how you can construct computational circuits and memory units using digital electronics2. In lab, you will learn how to use a very popular microcontroller the PIC from Microchip corporation.

1 Note: The microcontroller programming tools are installed in 140 Cory ONLY for ease of maintenance 2 EE100 Summer 2007 lectures at the University of California, Berkeley Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

Be advised that we will view the microcontroller from a very high level perspective. That is, we will not go into the nitty-gritty details of designing microcontrollers because it is beyond the scope of this lab. However, the aim of this lab (and the project) is to give you a working idea behind PIC microcontrollers so that you may build useful circuits and continue to explore the microcontroller world on your own. We will explore the most important components of the microcontroller unit in this section. i. The CPU You will see how memory can be understood using the concept of digital feedback in the EE100 Summer 2007 lectures. For now, an abstract view of memory will suffice, refer to Figure 1.
Figure 1. Simplified view of a memory unit

You will also see how you can build simple circuits that add, subtract and compare: the Arithmetic Logic Unit (ALU). The CPU simply consists of the ALU along with internal memory locations called registers, refer to figure 2.
Figure 2. A simplified CPU Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

ii. The Bus We now have two independent entities (memory and CPU). Thus any exchange of data is hindered, as well as its functionality. If, for example, we wish to add the contents of two memory locations and return the result again back to memory, we would need a connection between memory and CPU. Simply stated, we must have some "way" through data goes from one block to another. Enter the concept of a bus. Physically, a bus represents a group of 8, 16, or more wires. There are two types of buses: address and data bus. The first one consists of as many lines as the amount of memory we wish to address and the other one is as wide as data, in our case 8 bits or the connection line. First one serves to transmit address from CPU

memory, and the second to connect all blocks inside the microcontroller. Figure 3 shows the new situation.
Figure 3. Connecting memory and CPU using instruction and data bus

iii. Input Output unit As far as functionality, the situation has improved. But a new problem has appeared: we have a unit that is capable of working by itself, but it does not have any contact with the outside world! In order to remove this deficiency, let's add a block which contains several memory locations. One end of this block is connected to the data bus and the other has connection with the output lines on the microcontroller. These output lines can be seen outside the microcontroller as output pins (just like the output pin of your opamp). Refer to figure 4.
Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS Figure 4. Example of a simplified input-output (I/O) unit that provides communication with the real-world

A pin on the microcontroller chip that lets you talk to the outside world is called as a port. There are several types of ports input, output or bidirectional (input and output). When working with ports, it is necessary to choose which port we need to work with and then send data to or receive data from the port. Notice also from figure 4 that working with a port is like reading and writing to a memory location. This is accomplished using registers. A register is a memory location mapped to a port. When you write to or read from the register, you are reading or writing from the corresponding port. iv. Serial communication We can now communicate with the outside world, but what if we wanted to communicate kilobytes of data? Lets make a quick calculation on how many lines we would need. 1 kilobyte = 1024 bytes. 1 byte = 8 bits. Thus, we would need: 1024 bytes x 8 bits/byte = 8192 bits. If a port carries 1-bit of data, then we would need 8192 ports or 8192 pins! What if we wanted to carry a megabyte (1024 kilobytes) of data? You would need 8,388,608 lines! Thus it is obvious that if you want to communicate large amounts of

data with the outside world, a port is very inefficient. Ports are useful only for carry a bit of data. In order to overcome this problem, we have to come up with a way to reduce the number of lines and not lose functionality. Suppose we are working with three lines only and one line is used for sending data, other for receiving, and the third is used as a reference line for both the input and the output. In order for this to work, we need to set a few rules for the exchange of data. These rules are called protocols. Let us suppose we have the following protocol: The logical unit "1" is set up on the transmitting line until transfer begins. Once the transfer starts, we lower the transmission line to logical "0" for a period of time (which we will designate as T), so the receiving side will know that it is receiving data. Hence, the receiving side will activate its mechanism for reception. Now the transmitting side can start sending binary data. Let each bit stay on the line for a time period which is equal to T. In the end (after transmitting all the data) let us bring the
Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

logical unit "1" back on the line. The protocol we've just described is called in professional literature: NRZ (Non-Return to Zero). Figure 5 illustrates this concept. Figure 6 shows a block diagram of the serial communication unit.
Figure 5. NRZ protocol. Notice that there is a clock which tells us how long a logic 1 and logic 0 are. We will discuss clocks in the next section Figure 6. The Serial communication unit.

v. Timer unit We have seen in the previous section that we need a clock signal as a reference. You have seen how you can generate a square wave using a simple op-amp circuit. Figure 7 shows the capacitive square wave oscillator you are already familiar with.
Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS Figure 7. Square-wave generator. Output Vo will oscillate between Vpp and Vnn.

However, there are more efficient methods to generate oscillators. We will not go into these techniques. It is sufficient to understand that the basic unit of the timer block is a free running counter whose numeric value increments by one in even intervals.

Therefore, if we read the value of this counter at T1 and then read it again at T2, the difference would indicate how much time has elapsed. vi. Watchdog Timer Unlike a regular PC, your microcontroller will be functioning in time critical applications (like aircraft control) and/or in remote in-accessible areas (like seismic sensors). Hence, if your microcontroller crashes then there is probably no one to push the reset button (unlike a PC). To overcome this obstacle, designers introduced the concept of a Watchdog Timer. This block is in fact another free-run counter where our program will write a zero every time it executes correctly. If the program gets "stuck" due to some external condition, zero will not be written and the Watchdog timer will reset the microcontroller upon achieving its maximum value. This will result in executing the program again, and correctly this time around. The Watchdog timer is thus an important element of every
Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

microcontroller. It helps the system recover from errors without human supervision. Notice that the Watchdog timer is NOT a substitute for correct program functionality. It is assumed that the program is functioning correctly. Figure 8 shows a block diagram of the Watchdog timer.
Figure 8. The Watchdog timer

vii. Analog to Digital (A/D) converter As external signals are usually substantially different from the ones that microcontroller can understand (zero and one), they have to be converted into a pattern which can be comprehended by a microcontroller. This task is performed by a block for analog to digital conversion or by an ADC. Figure 9 shows a block diagram of the A/D.
Figure 9. Block diagram of the A/D Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

viii. The Microcontroller Block Diagram Now we are ready to assemble our microcontroller based on the building blocks discussed above. Refer to figure 10.
Figure 10. Microcontroller block diagram

ix. Programming a Microcontroller

Now that we have the hardware in place, we need to program the microcontroller to accomplish a task. First, we will write a simple program in pseudo-code. By pseudocode we mean this program is not written using any programming language (like C). Refer to the code below.
Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

START REGISTER 1 = MEMORY LOCATION A REGISTER 2 = MEMORY LOCATION B PORT A = REGISTER 1 + REGISTER 2 END The program above simply adds two memory locations and puts their sum on port A. The first line of the program moves the contents of memory location A into a CPU register. As we need the other data as well, we will move it into register 2. The next instruction tells the CPU to add the contents of those registers and send it to port A, so the sum would be visible to the outside world. Of course we program in the real world using languages like C. However, programming a microcontroller is more complex than programming on the PC. This is because of the fundamental issue in microcontroller programming: you are writing a program that is going to run on a completely different system. This process is called cross-compiling. Hence you need sophisticated tools (hardware and software) to help you program a microcontroller. In the next section, we will deal with the hardware the PICDEM 2 Plus development board. b. The PICDEM 2 Plus development board [2] In this section, we will give an overview of the PICDEM 2 plus development board, shown in figure 11.
Figure 11. The PICDEM 2 plus development board (PICDEM 2 plus demo board).

This board has at its core a P18F4520 microcontroller. The board also has a host of other peripherals to ease interfacing to the microcontroller and programming the microcontroller. The most important of these are covered below. i. Board Hardware Features ([2], p. 10) The PICDEM 2 plus development board has the following hardware features (refer to figure 12):
Summer 2007 Lab 8

EE100/EE43 University of California, Berkeley Department of EECS

1. 18, 28 and 40-pin DIP sockets. Although three sockets are provided, only one device may be used at a time. In your case you have a PIC18F4520 in the 40-pin DIP socket. 2. On-board +5V regulator for direct input from 9V, 100 mA AC/DC wall adapter or 9V battery, or hooks for a +5V, 100 mA regulated DC supply. 3. Serial (RS-232) socket and associated hardware for direct connection to an RS232 interface. 4. In-Circuit Debugger (ICD) connector. 5. 5 K potentiometer for devices with analog inputs. 6. Three push button switches for external stimulus and Reset. 7. Power-on indicator LED. 8. Four LEDs connected to PORTB. 9. Jumper J6 to disconnect LEDs from PORTB. 10. 4 MHz canned crystal oscillator. 11. Unpopulated holes provided for crystal connection. 12. 32.768 kHz crystal for Timer1 clock operation. 13. Jumper J7 to disconnect on-board RC oscillator (approximately 2 MHz). 14. 32K x 8 Serial EEPROM. 15. LCD display. 16. Piezo buzzer. 17. Prototype area for user hardware. 18. Microchip TC74 thermal sensor.
Figure 12. PICDEM 2 Plus hardware Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

You should relate the board components above to the high-level microcontroller blocks you learned about in section (a). For example, the serial hardware on the board helps a computer interface to the microcontrollers serial unit. For a detailed description of the board hardware, refer to pp. 15 and 16 in [2]. Now that you have an idea of the hardware platform, it is time to play with the actual board. c. Introduction to MPLAB IDE and MPLAB C18 C Compiler In this section, you download the digital code to your microcontroller board. You will use the ICD2 (In-Circuit Debugger) module to do so. Note that since you do not cover digital systems etc. in great detail, we have designed all the code for you. The digital portion of your project simply requires you to change a few bits to instruct the

microcontroller to read from a different A/D the goal of the final lab. For now, you will just burn the code onto the PIC: 1. Download the StrainGauge project folder from the EE100 labs homepage. Save this to your U: (network) drive. DO NOT SAVE THIS ONTO YOUR DESKTOP. FILES SAVED ONTO YOUR DESKTOP ARE AUTOMATICALLY DELETED WHEN YOU LOG OFF!! 2. Navigate to your folder and double-click on icon. A window similar to figure 13 will pop up.
Figure 13. MPLAB IDE has opened your Strain Gauge project Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

3. Now, double click on main.c in the StrainGaugeInterface.mcw window. The main program should pop up. Look through it. Find the line that displays VOLTMETER. Replace VOLTMETER with EE100 ROCKS! 4. You should debug the program before downloading it to the board. To do this: Click on Debugger Select Tool. Make sure MPLAB ICD 2 is selected. Refer to figure 14.
Figure 14. Make sure MPLAB ICD 2 is selected as the debugger

5. The debugger should ask you to download an operating system to the board. Defaults are OK for everything. Before you connect to the board, MAKE SURE THE BOARD IS POWERED ON AND CONNECTED TO THE ICD2 DEBUGGER. MAKE SURE THE DEBUGGER IS CONNECTED TO THE COMPUTER (check with a TA). Next, connect to the board: Debugger Connect. 6. Build your program. Select Project Build All 7. Program the board with your code: Debugger Program. 8. Run the program: Debugger Run. 9. If all goes well you should see the LCD screen display EE100 ROCKS! and a voltage reading on the second line. Use the pot (RA0) on the PICDEM 2 plus board to adjust the voltage value (from 0.00 to 5.01 V).
Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

10. If you are satisfied that your program is working, you can permanently download code to EEPROM3. First, halt debug mode: Debugger Halt. 11. Select Debugger Select Tool None. You cannot use the programmer and the debugger at the same time. 12. You pretty much repeat the same process for programming as debugging: Select Programmer Select Tool MPLAB ICD 2. 13. Select Programmer Connect 14. Select Programmer Program 15. Select Programmer Release from Reset. 16. Power off the board and power-on again. Your code will start running again.
3 EEPROM:

Electrically Erasable Programmable Read Only Memory

Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

4. PRELAB NAME:__________________________________/SECTION____ Please turn in INDIVIDUAL COPIES of the prelab. They are due 10 MINUTES after start of lab, NO EXCEPTIONS! a. TASK 1: THOROUGHLY READ THIS DOCUMENT! (YES, THIS PRELAB IS A GIMME) PRELAB COMPLETE: _________________________________ (TA CHECKOFF)
Summer 2007 Lab 8 EE100/EE43 University of California, Berkeley Department of EECS

5. REPORT NAME(S):__________________________________/SECTION____ a. TASK 1: PICDEM 2 Plus LCD displays EE100 ROCKS! TA Checkoff:_______ b. TASK 2: Program still functional after power cycle. TA Checkoff:_______ TURN IN ONE REPORT PER GROUP AT THE END OF YOUR LAB SESSION. THERE IS NO TAKE HOME REPORT. 6. REFERENCES [1] PIC Microcontrollers: Chapter 1 Introduction to Microcontrollers. Online at: http://www.mikroe.com/en/books/picbook/1_chapter.htm. Last Accessed: July 8th 2007 [2] PICDEM 2 Plus Board Users Guide. PDF format. Microchip corporation, http://www.microchip.com 7. REVISION HISTORY Date/Author Revision Comments Summer 2007/Bharathwaj Muthuswamy Typed up source documentation, organized lab report, typed up solutions.

You might also like