PIC Lab

23
Lab 1: Flashing an LED Description Today is our first session in PIC microcontroller lab, and we will begin with an experiment that flashes an LED on and off. While this looks very simple it is the best project to start because this makes sure that we successfully wrote the program, compiled it, loaded inside the PIC, and the circuit is correctly built on the breadboard. In this lab session we will connect an LED to one of the port pin of PIC16F688 and flash it continuously with 1 sec duration. Required Theory You must be familiarized with, digital I/O ports (PORTA and PORTC) of PIC16F688 direction control registers, TRISA and TRISC special function registers CMCON0 and ANSEL If you are not then please read this first: Digital I/O Ports in PIC16F688. Circuit Diagram To our basic setup on the breadboard (read Getting Ready for the First Lab), we will add a light-emitting-diode (LED) to port pin RC0 (10) with a current limiting resistor (470 Ohm) in series. The complete circuit diagram is shown below.

description

Lab manual

Transcript of PIC Lab

Lab 1: Flashing an LED

DescriptionToday is our first session in PIC microcontroller lab, and we will begin with an experiment that flashes an LED on and off. While this looks very simple it is the best project to start because this makes sure that we successfully wrote the program, compiled it, loaded inside the PIC, and the circuit is correctly built on the breadboard.In this lab session we will connect anLED to one of the port pin of PIC16F688 and flash it continuously with 1 sec duration.Required TheoryYou must be familiarized with, digital I/O ports (PORTA and PORTC) of PIC16F688 direction control registers, TRISA and TRISC special function registers CMCON0 and ANSELIf you are not then please read this first:Digital I/O Ports in PIC16F688.Circuit DiagramTo our basic setup on the breadboard (readGetting Ready for the First Lab), we will add a light-emitting-diode (LED) to port pin RC0 (10) with a current limiting resistor (470 Ohm) in series. The complete circuit diagram is shown below.

Flashing LED circuit

Prototyped circuit on the breadboardSoftwareOpen a new project window in mikroC and select Device Name as PIC16F688. Next assign4.0 MHz toDevice Clock. Go to next and provide the project name and the path of the folder. It is always a good practice to have aseparatefolder for each project. Create a folder named Lab1 and save the project inside it with a name (say, FlashLED). The mikroC project file has .mccpi extension. The next window is for Add File to Project . Leave it blank (there are no files to add to this project) and click next. The next step is to include libraries, select Include All option. Next, click Finish button. You will see a program window with avoid main() function already included. Now, go to Project -> Edit Project. You will see the following window.

This window allows you to program the configuration bits for the 14-bit CONFIG register inside the PIC16F688 microcontroller. The device configuration bits allow each user to customize certain aspects of the device (like reset and oscillator configurations) to the needs of the application. When the device powers up, the state of these bits determines the modes that the device uses. Therefore, we also need to program the configuration bits as per our experimental setup. Select,Oscillator -> Internal RC No ClockWatchdog Timer -> OffPower Up Timer -> OnMaster Clear Enable -> EnabledCode Protect -> OffData EE Read Protect -> OffBrown Out Detect -> BOD Enabled, SBOREN DisabledInternal External Switch Over Mode -> EnabledMonitor Clock Fail-Safe -> EnabledNote that we have turned ON the Power-Up Timer. It provides an additional delay of 72 ms to the start of the program execution so that the external power supply will get enough time to be stable. It avoids the need to reset the MCU manually at start up.Read PIC16F688 datasheet for details on Configuration Word.

Appropriate configuration bit selectionHeres the complete program that must be compiled and loaded into PIC16F688 for flashing the LED. Copy and paste this whole program in your main program window. You have to delete the void main() function first that was already included. To compile, hit the build button, and if there were no errors, the output HEX file will be generated in the same folder where the project file is. Then load the HEX file into the PIC16F688 microcontroller using your programmer./*Lab 1: Flashing LED with PIC16F688Internal Oscillator @ 4MHz, MCLR Enabled, PWRT Enabled, WDT OFFCopyright @ Rajendra BhattOct 7, 2010*/// Define LED @ RC0sbit LED at RC0_bit;void main() {ANSEL = 0b00000000; //All I/O pins are configured as digitalCMCON0 = 007 ; // Disbale comparatorsTRISC = 0b00000000; // PORTC All OutputsTRISA = 0b00001000; // PORTA All Outputs, Except RA3

do {LED = 1;Delay_ms(1000);LED = 0;Delay_ms(1000);} while(1); // Infinite Loop}Download the HEX file

We used the in-built library function Delay_ms() to create the 1 sec delay for flashing On and Off. Delay_ms() returns a time delay in milliseconds.

OutputYou will see the LED flashing On and Off with 1 sec duration.

- See more at: http://embedded-lab.com/blog/?p=148#sthash.WFgBzGkF.dpuf

his is to be followed after you have successfully completed the following steps: InstalledmikroC Pro for PICon your PC. Installed the programmer software that came with your PIC programmer. If you have got an iCP01 USB PIC programmer fromiCircuit Technologies, you should install Microchips PICkit programming software. Got a breadboard and aregulated +5V power source.Basic setup on the breadboardAs mentioned before all the experimental circuits will be constructed on the breadboard because it is easy to modify the circuit and correct any wiring error. Figure 1 shows the pin diagrams of PIC16F688. It is a 14-pin microcontroller with a precision internal oscillator. It provides 12 I/O pins with individual direction control, and can drive LEDs directly. 8 out of 12 I/O pins also serve as ADC channels for the internal 10-bit ADC. The various features of PIC16F688 will be discussed later in more detail in following lab sessions. For now, we will look at a simple circuit setup for PIC16F688 on the breadboard that will be used in all the experiments.

Figure 1: PIC16F688 pin diagramFigure 2: Basic setup for PIC16F688 with an external reset switchFigure 2 shows a PIC16F688 microcontroller with minimum support components. We will use the built-in oscillator of PIC16F688 so that we dont have to provide an external oscillator circuit. This frees up two port pins (2 and 3) that can be used for I/O purpose.There are many circumstances when you may want to reset the microcontroller and force the program execution to restart from the beginning. This can be achieved by connecting an external reset button to the MCLR (Master Clear) pin of PIC16F688 as shown in Figure 2. Normally, the MCLR pin is at logic 1, and it goes to logic 0 when the reset button is pressed. The logic 0 at MCLR pin resets PIC16F688. When the button is released, the microcontroller operates normally, executing instructions from the beginning of the program memory. However, the MCLR pin can also be disabled and used just as an I/O pin through software (will see it later).PIC16F688 can be programmed serially (while in the target circuit) through two pins:ICSPDAT (RA0, 13), andICSPCLK (RA1, 12). This technique is known asin circuit serial programming(ICSP). During ICSP, the MCLR/Vpp pin is driven to approximately 13V by the programming device. Therefore, the application circuit must be isolated from this high voltage. In our case, the 10K resistor connected between the +5V power supply and MCLR/Vpp will prevent any voltage conflict during programming. Dont ever press the reset button while the microcontroller is being programmed.Thatsdangerous, never do that. TheRA1/ICSPCLK pin is the clock line driven by the programming device during ICSP, and RA0/ICSPDAT isthe bidirectional data line which is driven by the programmerwhen programming, and by PIC16F688 when verifying. These pins must be isolated from therest of the application circuit so as not to affect the signalsduring programming.Besides, a 100 nF capacitors serves as the decoupling capacitor and should be placed close to the microcontroller. See the pictures below that show the whole arrangement made on the breadboard.

Figure 3: PIC16F688 with minimum support components on the breadboard.

Figure 4: Basic PIC16F688 circuit with a +5V power source plugged into the breadboard.

Figure 5 : Basic PIC16F688 setup circuit with a +5V power source and the programmer plugged into the breadboard.Now you are pretty much set with the required hardware and software, and you are ready for your first experiment with PIC.- See more at: http://embedded-lab.com/blog/?p=190#sthash.ob1HRjru.dpufRPS:Embedded systems require electric power to operate. Most of the components in them including the processors can operate at a wide range of voltages. For example, the operating voltage range for PIC16F688 is from 2 to 5.5 V. It means you can supply power from three AA size batteries (4.5 V) and it will work just fine as long as the battery voltage doesnt fall below 2 V. But there are certain applications where you need a regulated constant voltage for safer operation of the embedded system. For instance, any application that uses analog-to-digital converters (ADCs). ADCs require a fixed reference voltage to provide accurate digital count for input analog signal. If the reference voltage is not stable, the ADC output is meaningless. So, today we are going to make a regulated +5V power source for our lab.An LM7805 linear regulator IC is used for this purpose. It converts a DC input voltage of range 7-25 V to a stable +5 V. It requires just two external capacitors and is very easy to use, as shown below.

The input DC voltage for LM7805 could be obtained from a 9V DC wall adapter that can supply 1 Amp of load current. Actually, 12 to 24 V adapter will work too, but the LM7805 regulator dissipates an extreme amount of heat energy at higher input voltages and, therefore, requires a bulky heat sink. The wall adapter is chosen because it is cheap, easily available (you might already have got a spare one at home), and safe (the high voltage mains AC is isolated). You can solder this circuit on a general purpose prototyping board. Here are some pictures I took of my power supply unit.

I have soldered male header pins (shown above) to +5 V and Gnd terminals so that the power supply unit can be plugged into the breadboard (shown below).

The power supply unit is ready now. Measure the output voltage with a digital multimeter and see how close is it to +5 V.

The development of an embedded system requires some hardware and software products. Although the hardware requirements depend on the type and complexity of the project, the following hardware tools are required in all of the experiments we are going to discuss here.1. Asolderless breadboardfor constructing and testing the experimental circuits. The breadboard is chosen because it is reusable. You can change, modify or remove the components on it at any time. While an embedded system is in development phase, you never know in advance whether or not your circuit will function correctly when assembled. So it is always good to test it first on a breadboard. Once it performs well, the circuit can be transferred to a printed circuit board.2. Microcontroller chips (PIC16F688andPIC16F628Ain this case)3. APIC programmerto load firmware inside the microcontroller. You need to buy one within circuit serial programming(ICSP) capability. This allows you to quickly program the PIC while it is in the target circuit. I have got aniCP01 USB PIC programmerfrom iCircuit Technologies. It is very handy, easy to use, and low-cost ICSP programmer for the most popular flash-based PIC microcontrollers. The best thing about it is that it is compatible with Microchips PICKit2 and MPLAB IDE softwares. And, it works great. ReadChoosing a PIC Programmer.4. APCis required for two purposes: to develop and compile the firmware for the microcontroller, and to transfer it to the PIC programmer so that it could be loaded into the program memory of the microconroller.5. Aregulated +5VDCsource to power your circuit on the breadboard.6. Adigital multimeteras test equipment.7. Other components like resistors, LEDs, capacitors, wires, etc as required.

iCP01 USB PIC programmer that uses PICkit2 software for programmingRequired Software ToolsIn addition to the above hardware, following software products are required during the experiments.1. ACompilerto develop and compile the firmware. You need to download and install the free version of mikroC Pro for PIC (a C compiler for PIC from Mikroelektronika) to follow these experiments. Here is the download link:mikroC Pro for PIC. Also downloadmikroC Pro manualandCreate First Project. These users manuals describe the compiler features and setup procedure in detail.2. Amicrocontroller device programmersoftware thats provided by the vendor along with the programmer hardware. It is required to transfer the firmware from the PC to the microcontroller. You can download PICkit2 programming software for iCP01 USB PIC programmerhere.- See more at: http://embedded-lab.com/blog/?p=170#sthash.Lz5hZE3B.dpuf

PIC16F688 is a 14-pin flash-based, 8-bit microcontroller. It can be obtained in different packages, but the DIP (Dual In-line Package) version is recommended for prototyping. The figure below shows a PIC16F688 microcontroller in DIP chip, and its pin outs.

Most of the pins are for input and output, and are arranged as PORTA (6) and PORTC (6), giving a total of 12 I/O pins. All of these can operate as simple digital I/O pins but they do have more than one function. For example, eight of total 12 I/O pins also serve as analogue inputs for the internal analog-to-digital converter (ADC). Similarly, the PORTA pins RA0 and RA1 are also used to serially load an user program into the PIC16F688 flash memory. The mode of operation of each pin is selected by initializing various control registers inside the chip. All these options will be discussed later on.

PORTAPORTA is a 6-bit wide, bidirectional port. A bidirectional port is one that can act as either an input port, to receive information from external circuitry, or an output port, to give information to external circuitry. The direction of the PORTA pins is controlled by the TRISA register. Setting a TRISA bit (= 1) will make the corresponding PORTA pin an input, and clearing a TRISA bit (= 0) will make the corresponding PORTA pin an output. The RA3 pin is an exception because it is input only and so its TRISA bit will always read as 1. The TRISA register controls the direction of the PORTA pins, even when they are being used as analog inputs. Therefore, the user must ensure the bits in the TRISA register are maintained set when using them as analog inputs. I/O pins configured as analog input always read 0.

PORTCSimilar to PORTA, PORTC also has 6 bidirectional I/O pins. Each of the pin can be selected as input or output by setting or clearing the corresponding bit in the TRISC register.

ImportantPIC16F688 has two analog voltage comparators and eight 10-bit ADC channels. The inputs to the comparators are multiplexed with I/O port pins RA0, RA1, RC0 and RC1, while the outputs are multiplexed to pins RA2 and RC4. On a power-on reset, RA0, RA1, RC0, and RC1 are configured as analog inputs, as controlled by the CMCON0 register. In order to use these pins as digital inputs, the comparators must be turned OFF. This can be done by assigning decimal value 7 to CMCON0 register (CMCON0=0b00000111).Similarly, the PIC16F688 port pins that are multiplexed with ADC channel inputs are also configured as analog inputs on a power-on reset. The ANSEL register must be initialized to decimal 0 (ANSEL=0b00000000) to configure all ADC channels as digital inputs. The CMCON0 and ANSEL registers will be discussed in more detail later.- See more at: http://embedded-lab.com/blog/?p=238#sthash.1HMlRAx7.dpuf

Lab 2: Basic digital input and output

DescriptionToday we will learn how to read digital inputs from a push button switch. A digital input has only two values: 1 and 0. The configuration of the push button switch is same as that of the reset switch except it goes to a different port pin. The status of the switch will be read through RC1 and every time when it is pressed, an LED connected to RC0 will be toggled ON and OFF.Required TheoryYou must be familiar with the digital I/O ports of PIC16F688 and their direction settings. If you are not, readDigital I/O Ports in PIC16F688.Circuit DiagramTo our last setup (seeLab 1: Flashing an LED), connect a push button switch to RC1 as shown below. The input ports of a PIC microcontroller have very high input impedance, and therefore, during normal condition when the switch is open, the RC1 pin is pulled High through the external 10K resistor. When the switch is pressed, RC1 is pulled to ground and the microcontroller will read it as logic Low. In this way, a simple push button switch with a pull-up resistor can be used to provide digital inputs (1 and 0) to the microcontroller.- See more at: http://embedded-lab.com/blog/?p=164#sthash.44YPou0B.dpuf

Circuit for reading digital inputs.

Prototyped circuit on the breadboardSoftwareSince the switch is connected to RC1, this port pin must be defined as input. This is done by setting the corresponding bit in the TRISC register. Again, dont forget to disable the comparators and ADC channels. The code for this experiment is provided below. You should compile it with the MikroC compiler and load the output hex file inside the PICMicro. The MikroC compiler has an in-built library routine (namedButton) for reading digital inputs from push button switches. The syntax is,

You can see that the Button command has debounce features built in.Debouncing a switchWhen a mechanical switch (like a push button) is pressed or released to make or break an electrical contact, the switch tends to make multiple transitions between open and close before coming to the stable final state. This is called switch bounce and this activity may go on for tens of milliseconds. We cannot see this bouncing but a microcontroller is relatively fast as compared to the action of the switch, and is, therefore, able to recognize this as multiple button presses and respond accordingly. Therefore, the switch must be debounced before its status is read by a microcontroller. Debouncing circuits require extra hardware and thus raises the cost of the embedded system. The easiest solution is to implement debouncing in software. The simplest logic is to wait for a few milliseconds (5-20 ms) after the key press or release is detected, and read the final state of the switch again to make sure it is a valid button press or release.

Note that the configuration bits setting is same as in Lab 1. /* Lab 2: Toggle LED with a Tact Switch Input Internal Oscillator @ 4MHz, MCLR Enabled, PWRT Enabled, WDT OFF Copyright @ Rajendra Bhatt Oct 8, 2010 */ // Define LED @ RC0 and Tact switch @ RC1 sbit LED at RC0_bit; sbit Switch at RC1_bit; #define Switch_Pin 1 #define Switch_Port PORTC #define Debounce_Time 20 void main() { ANSEL = 0b00000000; //All I/O pins are configured as digital CMCON0 = 0x07 ; // Disbale comparators TRISC = 0b00000010; // PORTC All Outputs TRISA = 0b00001000; // PORTA All Outputs, Except RA3 LED = 0; do { if (Button(&Switch_Port, Switch_Pin, Debounce_Time, 0)) { if (!Switch) { LED = ~LED; } while (!Switch); // Wait for release of the button } } while(1); // Infinite Loop}Download the complete mikroC project filesOutputEvery time the switch is pressed, the LED toggles ON and OFF. Once the switch is pressed, the microcontroller will wait for its release before it detects another press.

- See more at: http://embedded-lab.com/blog/?p=164#sthash.44YPou0B.dpuf