Manual Pic Lab 1
Manual Pic Lab 1
Introduction To Microcontrollers
elcome to the wonderful world of microcontrollers. You are reading this document, because you are interested in the fascinating world of electronics. This document assumes that you have basic ideas about electronics, and are able to build simple electronic projects. Although microcontrollers are hi-tech devices, yet they are extremely easy to use. Once you have mastered the ideology behind and know the procedure to control various devices, a whole range of applications is open to you. Devices which required a large number of components and skillful logic design can now be built with almost no or minimal components. One of the greatest advantages of microcontrollers is that they can reduce the hardware requirements dramatically. The logic which was going to be implemented using a number of devices and components can be replaced by software in microcontrollers. Truly speaking microcontrollers are small, one-chip computers. As opposed to microprocessors, which require a number of peripheral devices, like, memory, I/O etc microcontrollers have all the necessary peripheral devices built into it. However the scale is small, memory is limited, so are other features. Remember Microcontrollers were designed to control small peripheral devices, and as such these applications do not require mega bytes of memory or the entire power of your PC. Whatever memory and peripheral devices that have been integrated into the package are enough to handle the job. A large number of microcontroller units are available, each differing in terms of memory available, and the number of peripheral devices integrated on the chip. Therefore once you have mastered, how to use these devices, it then remains a matter of choice for a particular application, which microcontroller to chose. Since basic ideology is same, if you master one chip, it is very easy to migrate to another. Moreover if you tend to stick to one clone, they are all upwards compatible. In a nutshell we can say that a microcontroller is just an integrated circuit which is programmable. Unlike most other digital ICs, which have a designated function, like NAND gates, Flip flops, Oscillators, 7 segment display drivers, arithmetic calculators etc microcontroller has no designated function. If you have a Microcontroller (MCU) chip in your hand and ask what type of function is it going to do? The answer would be I don't know! It can be used to control a motor, or an LCD display, or a 7 segment LED display, or can perform mathematical calculation, or control an infra red remote control or what else? This is such a surprise that a single chip can do so much. It is versatile, in a sense that you can get a variety of jobs done by this chip, if properly used. In order to get a job done by this chip, you need to program it first. This program will control the various I/O lines of the chip, and these I/O lines in turn control the devices like mo-
tors, LEDs, Infrared sensors etc. Thus in order to control a device you need to know, its control structure, for example controlling a simple DC motor is different from a stepping motor, and this in turn is different from servo motor. It is therefore essential before starting an application to understand the control requirements of the device. Then you program the microcontroller accordingly, and this makes a complete application.
Having a basic idea of electronics, and programming is all that you need to enter into this fascinating world. This course will take you from beginning to an intermediate level, where you should be able to design your own applications.
types than in assembling large series Has (at least) basic knowledge of both electronics and programming
Note that I do not assume a master's degree in electronics or programming. But on the electronics side understanding the basic working of a resistor, capacitor, diode, LED, transistor etc., and being able to apply at least Ohm's law are mandatory. On the programming site you should have some programming experience, so terms like variable, assignment, if, while, call, goto and return ring a bell. Starting with PICs requires you to make a lot of choices. This document tries to help you doing so, sometimes by making a strong suggestion, but always - I hope - by providing you the information you need to make the right decision for your particular situation. If all you want is a list of pre-cooked advices don't read on, just ask on comp.arch.embedded or any other forum and you will get all possible combinations of advices, just pick one ;)
some relays etc. you might be better off with an environment that hides the ugly hardware details (and most of the power!) from you, like a BASIC Stamp, essentially a PIC or SX chip with a BASIC interpreter. If so, get a Stamp and put this document aside until you are in for more
PICs. You will still find lots of designs in electronics magazines and on the internet using these chips. But recently Microchip has broadened its offering of flash chips with types that are much more attractive. In my opinion three of these are prime candidates to be 'my first PIC': the 16F628, the 16F877 and the 18F452. The 16F628 is somewhat cheaper than the old 16F84, has twice the code size, much more RAM, a UART and some more goodies. This is the chip for simple applications and of course for beginners. The 16F877 is around twice the price of the old 16F84, but it has eight times the code size, much more RAM, much more I/O pins, a UART, A/D converter and a lot more. Unless your budget is very tight I would recommend the 16F877 as your first buy, otherwise you should consider the 16F628. The 16F84A (the 16F84 - without A - and the 16c84 are obsolete) should be used only to build an existing design that you do not want to modify. The 18F452 is part of the new (16-bit core) series of PICs. It offers an instruction set that is much improved over the 14bit (16F) PICs, improved peripherals, twice the code space and twice the speed compared to the 16F877, at a price that is only marginally higher. The 16F628 can be considered the next-generation 16F84, because it is pin-compatible with those older chips. But note that it is not fully software compatible. The 16F628 also has a smaller cousin, the 16F627 (1k code instead of 2k). The 16F627 does not seem to be an attractive chip as the prices I found were actually a little higher than for the 16F628. With 8K code space and 34 I/O pins the 16F877 is the largest chip of the 16F87x family, The 16F876 comes in a smaller package with less (IO) pins. It is about the same price as a 16F877, so it is interesting only when the larger package of the 16F877 is a problem. Note that the 16F877 and 16F876 both have a UART (for asynchronous serial communication) and an MSSP (for SPI and I2C), while the smaller chips have only a UART. The 16F872 is a 16F870 but with an MSSP instead of a UART. The 18F chips are new family of PICs, with an instruction set that is much improved over the 16F chips, with more peripherals, and more code and data space. Yet the price of the 18F chips is only marginally higher than the comparable 16F87x chips. There are variations of the 18F chips that have an integrated CAN controller - nice when you want to create a network of PIC chips. If you can't make sense of the Microchip part numbering you are not the only one. These are the only patterns that I have found: The prefix 12 is for chips with 8 pins.
Personally I started with PICs and have not looked into the other ones much. Motorola's 68HC family is often used for somewhat more complex tasks than PICs, but tends to be more difficult to buy. The smaller AVR's are much like the PICs in price and performance. (Hence PIC-or-AVR debates tend to be very hot.) There are so many 8051 clones around that it is difficult to say something in general about this family. OK, so you have not been scared away and are firmly decided to start using PICs. May you live in interesting times, and never say I did not warn you!
Selecting a PIC
So which PIC should you choose to start with? A few years ago this question was easy to answer: the 16F84 (or, before that chip was available, the now discontinued 16c84). These were the only affordable flash PICs and hence THE hobbyist
The prefix 16 is for 12-bit and 14-bit core chips with more than 8 pins. The prefix 18 is for 16-bit core chips. Next the letter C is for EPROM (OTP or windowed) chips, except for the 16C84 that has EEPROM, which is (for a user) almost the same as flash. The letter F is for flash chips. They have flash memory, which can be erased and re-programmed. Windowed EPROM chips have a JW suffix. For some of the chips Microchip has released improved versions, identified by appending an A to the type. Such A chips are in most aspects identical to their non-A predecessors (but it does not harm to check the data sheets or the 'migration' document), except that the programming algorithm often changed. Hence you can buy and use an A chip if it is available (they are often slightly cheaper), but check that your programmer explicitly supports the A version. Note: The 16F84A uses the same programming algorithm as the 16F84, but the A chip can run at up to 20 MHz, the non-A only up to 10 MHz. The SX PIC clones are interesting because they provide MUCH more computing power than the Microchip PICs. On the downside the SX'es do not provide much peripherals (only a comparator and a timer), so you will need those MIPS to implement what the manufacturer call virtual peripherals. This is a nice and powerful concept, but not suited to a beginner. So what chip should you choose to start with? As said before, first check which chips you can actually buy. Then consider whether you want to use an existing design or other document. In that case the choice has been narrowed down for you. If you already have a programmer, check which chips it supports. For the choice I recommend that you take the most powerful chip that still fulfills the above constraints. The 18F452 (the largest chip of the 18F family) would be the first choice, the 16F877 (the largest chip of the 16F87x family) the next, and the 16F628 the last. Once you have acquired some experience with your first PIC, and you have a nice project debugged and running, it might be the right time to fit it into a cheaper PIC.
guage: Which languages do you know (but beware that C for a microcontroller might not exactly be the ANSI-C you are used to on a desktop system, well mostly its same). Price of the tool , or compiler Quality of the tool Quality of the tool documentation Support for the tool (vendor, mailing list, newsgroups) Ease of writing (a high level language is definitely easier to write in than assembler) Availability of useful libraries Effective use of the microcontrollers resources
The last issue (effective use of resources) can start a flame war on its own: the famous C-versus-assembler war (for C you can substitute your own favorite language). As often in such a case the answer depends a lot on the application. My opinion is: An assembler programmer can, given sufficient time, always make his program smaller, faster, etc. than a programmer that uses C or another high level language. Given insufficient time the reverse is true. (If you are a professional programmer: When was the last time you were given enough time to write an application? If so you are probably in an industry where the size of a production run is measured in the thousands, if not more.) My conclusion is that for a product that will be made in large numbers assembler should be used and for a a product that is produces in smaller numbers a high level language. But that leaves the question open how large or small the series must be, and it leaves a large gray area. A good middle road is often to use a high level language for most of your code and inline assembly for the parts that are very time- or timingcritical. Microchip provides MPLAB, a free assembler programming environment. Even when you do not want to use assembler you should get MPLAB, if only for the built-in simulator. Various companies sell C compilers for PICs. The prices range from moderate (below $100) to out-of-the-question (at least for a hobbyist: around $1000). I have not used any of these compilers extensively, so I cannot make a recommendation. A few free small versions are available for download they are good for a beginner, but can not be used for professional applications. High-Tech C provides PICC-Lite, a free demo version of their compiler. PICC-Lite targets an number of 16F chips, some with limitations. Check the Hi-Tech website for the most recent information. BKD provides a free demo version for their CC5X, which
can generate up to 1K instructions for all PIC types. This might be interesting to hobbyists, but be aware that CC5X is not exactly an ANSI-C compiler. Bytecraft provides a demo version of their C compiler. This demo produces only a listing, so you can not use it to translate an application, but it might be useful to see how C constructs are translated to PIC assembly. Jal is a freeware tool for programming PICs. Jal looks more like Pascal or Ada than C. I think Jal is a very good tool to start (and continue!) using PIC microcontrollers. Recently a large number of companies have started producing BASIC language compilers. Unlike the name, they are very good in functionality. The language is simple to use and learn, and they provide a wealth of built in libraries which produce tons of code. I have personally used these compilers and in fact they are producing very efficient code. So, which language should you choose? Sorry, I can't decide this one for you. Like for all choices, if you have an individual or group near you that can help you, it is not a bad choice to select the same tools. Otherwise the right choice depends a lot on your programming experience. If you have experience in a single language, you might select a PIC language that resembles it. If you don't have prior programming experience: There are people who advice assembler as the best choice to start programming, but personally I would definitely suggest a High Level Language. Or even better: forget PICs for a while and start programming on a PC, using the parallel port to interface to 'the real world'. I will recommend, PROTON-BASIC a compiler from Crown-Hill software. This is a Basic language compiler, supporting almost all PICs, and provides an IDE, Integrated development environment. This simplifies the development process and excellent for beginner. A Lite version with some limitations is available for free download, and provided with this development kit. We will be using this compiler for exploring our PICs. Another very powerful BASIC language compiler is available from Mickrode this Mikro_Basic is an extensive tool to develop professional applications using PICs.
ogy of transfer varies from one microcontroller to another, and therefore a special software is also coupled with the hardware programmer, that sends the data to programmer according to the programming specifications of the chip. A number of hardware programmer designs and software are available. The options are many and selection sometimes become difficult. In our course we will be using a very simple programmer, that you can also build yourself. This is called JDM serial programmer, and use a very commonly used and freely available software called ICPROG. There are 2 different ways to program a PIC: serial (used by nearly all PICs), and parallel (used only by some older nonflash types). Now USB programmers are also available. There are two different ways to put a PIC in programming mode. One is called High Voltage programming mode (HVP) and other low voltage programming mode (LVP) these will be discussed below. one alternative to an external programmer (self-programming using a bootloader). This option is dependent upon the chip. Production programmers and prototype programmers. Production programmers are fast, and check each and every byte while programming, while prototypes are somewhat slow, but are ok for smaller load and for hobbyists. you can either build your own programmer or buy one. The commercially available programmers are expansive, as they have been made to program a large variety of chips. For small businesses and educational purposes where the variety of chips will be limited you can build your own. When you start using PICs you should use only flash-based PICs. Flash PICs can be re-programmed quickly, if needed without taking them from the circuit. The programming time depends (among other things) on the size of the program, but even the largest chips can be programmed in about 30 seconds. EPROM-based PICs come in two versions: cheap OTPs (One Time Programmable) chips for production, and more expensive windowed (/JW) chips that can be erased using a UV EPROM eraser. Development using windowed chips is slow and tedious: erasing requires that the chip is removed from the circuit, put in the eraser, and erasing can take 20 minutes. Then you have to put the chip back in the target circuit and hope that you still know what you were trying to do. A professional can invest in a set of windowed chips and an eraser that can erase the while set in one go, but for a hobbyist the high price of windowed chips makes this unattractive. A PIC programmer puts the target PIC in programming mode and then uses the programming interface pins to enter the program into the target. The PICs that are most interesting to hobbyists use two pins (RB6 and RB7) to enter the program into the PIC (serial programming). Some older PICs
Select A Programmer
This is yet another issue that can start a flame war, partly because there are so many options. In order to program a PIC you have to compile the program on your PC and then transfer the compiled (.hex file) into the microcontrollers program area. This process is sometimes called burning and sometimes downloading. In any case this is writing the program into the program memory. This is done using a special hardware called programmer. This hardware turns the microcontroller into programming mode and then accepts data from the PC and writes it into the chip. The exact methodol-
used a lot of pins to enter the program (parallel programming). Nearly all low-cost programmer designs support serial programming. High Voltage programming (HVP) is supported by all PICs and is the standard procedure. It requires application of 14V signal to MCLR pin, which puts PIC into programming mode. This is all done by the programming hardware. It then uses two pin RB6 and RB7 for writing and reading data. LVP requires application of logical 1 signal (5V) to LVP pin and then use data loading. The disadvantage is that the pin dedicated for LVP can not be then used by application and if somehow Code Protection (CP) turned on can not be over written. I therefore recommend using HVP method.
The 18Fxxx chips provide a PLL setting which generates an internal clock of four times the external (crystal controlled) clock. This can be used to get a 40 MHz internal clock, with only a 10 MHz crystal (note: A 40 MHz crystal is not supported). The internal and external RC clocks have an (in) accuracy of a few %. This is adequate for flash-a-LED applications, but either not or just barely for more timing-critical things like asynchronous serial communication. When you build an existing design you have no choice but to follow its choice of clocking, but for your own first experiment you could use a 'low cost' clock: INTRC for a 16F628 (4 MHz) or better use a 20MHZ crystal for best speed and timing critical applications.
Clock Options
All PICs require some sort of timing signals to advance the internal instruction pointer. This is called clock. Faster the clock signals, faster the chip operation. Although fastest is always better, but faster you run, more power is consumed. So for an application which needs to run on battery for a long period of time, and is not very critical about speed may be used with slower clock. A PIC has a number of clock options. For most PICs the options are: HS: high-speed crystal (4 .. 20 MHz) XT: medium-speed crystal (200 kHz .. 4 MHz) LP: low-power 32768 Hz .. 200 kHz watch-style crystal RC: (external) capacitor + resistor
When a crystal or resonator is used two capacitors are required, from each of the OSC pins to GND. The value depends on the frequency. I use 20 pF for 4, 10, and 20 MHz. 3 -pin resonators have build-in capacitors. It is advised to keep the leads from these capacitors to the GND pin short. Some PICs have other clock options: The 16F62x, 12Fxxx 12C509 provide an INTRC mode that generates an internal clock of approximately 4 MHz. One or both of the pins that are normally used for the crystal can be configured for IO. This is especially important on the 8-pin chips which would - when an external crystal and reset were used - have only 4 IO pins left. The 16F628 has an ER mode where an external resistor and an internal capacitor determine the clock. This mode has the big advantage over the RC mode that the external resistor carries only a DC current, so long leads can be used (for instance to a front-mounted potentiometer) without problems.
Motherboard
The motherboard, or basic experiments board contains the basic circuitry of PIC microcontroller as well as a few Input and Output elements. This board is based upon PIC 16F628A microcontroller, clocked at 20 MHZ. In addition the board has eight LEDs to indicate the state of MCU pin. It also contains two push switches to get the digital input, one transistor output for pizo buzzer and an RS232 port for serial communication with other devices or your PC. The motherboard has its own 5V regulated power supply, which can supply up to 1A of load. This board also provides two banks of headers, for extension on other projects or subboards to extend the functionality beyond the simple motherboard. Power supply is available through all headers to sub boards so that they do not need to have their own power source. Supply to the board is given through a 9V battery, or better a 6-9V DC Adapter.
Programmer
As you know a programmer circuit is needed to write the application into the chip before it can do anything. A number of commercial programmers are available in market, however they are expansive and beyond the reach of a student or hobbyist. Internet contains many designs published by experts. You can easily build them using a few components. The one shown here, is probably the simplest possible programmer with three resistors, one diode and one I.C. I have selected this programmer because it is easy to use and simple to construct. It was intentionally developed separately from the motherboard, so that you can use it separate from the Easy-Pic kit as well. Like once you have mastered the art, you decide to make a microcontroller based car or rocket, you can program its microcontroller on this board. This programmer has two sockets, one for 18 pin PICs, like 16F628A and 16F84A and a 40-pin socket for controllers like 16F877A as well as 18F452. So for the routine experimenting it will support all your PICs. It has a serial port which can be connected directly or through a cable (simple straight 9 pin Serial cable) to the serial port of your PC.
As you can see there is no power supply on this board. It takes the supply from the serial port. Some laptops and notebooks do not have enough power available on their seril ports, therefore this programmer can not be used with them. However it works fine with all desktop computers. If you intend to use the Laptop for development then you will have to get our universal programmer, which has power supply,
and works for all microcontrollers. You already know there are two types of programming modes, a HVP and LVP. This programmer puts the microcontroller into HVP mode, which is the safest and fairly standard approach. This design is called JDM Programmer. To get more details, just do a Google search for JDM programmer.
main screen of ICPROG. As shown below. It might be different from this one as it depends upon the type of microcontroller selected. Just don't worry about that. First we have to select our PIC device, which we are going to program.
Programming Software
So now you have the motherboard with a microcontroller, and the programmer to burn your first program into the chip. Before doing that you need a software which will communicate with this programmer and write the application into the chip. Again a large number of software are available, I recommend ICPROG. This is a small, time tested software, freely downloadable from the internet. ICPROG has to be configured first, so that it knows your working environment, and the programmer board. ICPROG is supplied along with this kit. Locate the software folder and find the ICPROG105D folder. Copy the entire folder to your hard drive, lets say to D: copy it to the root folder, or if you copy it to some subfolder please note down its complete path, as this will be required later. Right now I presume that its path is D:\ICPROG105D.
ICPROG supports a large number of devices. Just click settings > Deice > Microchip PIC and you will see a long list of PIC devices, we have to locate PIC 16F628A click more and you will have more list, locate the PIC 16F628A. Make
Configuring ICPROG
Before you start configuring connect the programmer using serial cable to one of the serial ports available on your computer. Most computers have one serial port, called COM1. however a few, like mine might have two or more. It is important to know the COM port you connected, i.e. COM1 or COM2. Next pull the lever of ZIF-18 socket up, this will open the pin slots. Insert the PIC into it. Make sure you are inserting in right direction. There are pin number labels on the programmer board, make sure that the IC pin-1 is at right location. Briefly speaking the notch on IC should be towards the capacitor present on board. Now lock the pins by turning the lever down. Once the IC is in ZIF-18 socket its time to start ICPROG. Open the ICPROG105D folder you copied onto your D: drive and locate he ICPROG.EXE file. This is the software. It does not have any installer. Double click on this file and the ICPROG window will appear. When you run it for the first time, you will see an error message indicating something like Privileged Instruction Error. This error is basically due to Windows XP security system. The ICPROG wants to communicate with the serial port directly, whereas windows-xp does not allow this. We will have to install the provided windows XP driver first to fix this problem. For now just click OK, and you will see the sure you select the A variant and not just PIC 16F628. ICs with A variant have different programming strategy. Once you have selected the desired microcontroller device, your
main ICPROG screen will change, and it should look like the one shown above. Note in the right hand corner a drop down box where your selected device PIC 16F628A is being shown and selected.
So now we have configured ICPROG to program 16F628A microcontroller. Next we are going to configure the ICPROG for the type of programmer hardware we are going
Your ICPROG is now configured. Lets try to read the contents of microcontroller, if it reads the program from microcontroller, your software is communicating with the pro-
to use. Again click settings > Hardware (or press F3). A hardware setup dialog box will appear. Click on the programmer drop down list and select JDM Programmer. Next have a look at Ports, and select the port number, your serial cable is connected to. Leave all other things as it is, Interface selected should be Direct IO as shown in the fig above. Click OK. The privileged instruction error again pops, just click OK. grammer properly. Click Command > Read All or just press F8. the progress box will appear indicating reading the program and data area of microcontroller. We supply microcontroller with a small program already into it. The program code panel, which normally shows 3FFF 3FFF 3FFF sequences should show some other numbers, which are binary codes for the program. The command menu has other options as well. Most common command is to write the program loaded from your compiler into the chip. This is accomplished by clicking on Program All icon or selecting Command > Program All or by pressing F5. when you reprogram the chip it is automatically erased first, so you do not need to explicitly erase it first.
Now we have to install the windows XP driver, provided in the ICPROG folder. If you download ICPROG from internet, this driver has to be downloaded separately. Again click settings > Options a multi tagged options dialog box will appear. Select the Misc tab. You will notice a check box, labeled Enable windows NT/2000/XP driver. Select this option. As soon as you select this option it will ask you to reload the ICPROG just click Yes, and then it will ask your permission to install the driver, click YES. Now the driver is installed.
two wires Red and Black, go to a battery clip, where you can connect a 9V batter. Next to the clip you can see the power ON/Off switch and next to it the power supply indicator LED. Microcontroller, requires 5V power. It works fine from 4 to 6 V but more than that will damage it. Therefore we have put on a 5V regulator I.C 7805. we supply it anything from 6 to 9V and it will give a precise output of 5V. As such microcontroller requires very little power supply, indeed it uses nano-watt technology and consumes very little supply. However LEDs and PIZO consume a lot, and if LCD display and motors etc are used they consume lot of current. In that case if supply is taken from the motherboard, the 7805 tends to get heat up. It is therefore protected by a heat sink. This 7805 IC can give up to 1A of load, which is more than enough for routine experiments.
PORTB Header
If you want to make your own devices, that can be controlled from this motherboard, you have the PORTB header (Also PORTA header). As you can see PORTB header has 10 pins, eight are data pins, labeled as RB0 .. RB7. this is the notation used by microchip to indicate individual pins of a port, and in future we will refer the pins by these names. In addition to these eight data pins, there are a GND an VCC supply available. So the regulated 5V supply is also available through the header for your
devices. Therefore if for example you make an infra red controlling device, you will not need to have its separate power supply. Also note there are two types of headers available, they are both directly connected together. Its only a matter of choice to use which header. The white header has lock and orientation system, and the cables we provide can be inserted into them in only one direction, therefore reverse polarity is avoided. The other header also allows you to take selected ins to your devices by using the crocodile clip cables (Optional). Anyway the PORTB header provides all the eight lines of this port available for sub boards, like LCD or any other device you make. Along with the 5V regulated power supply.
PORTA Headers
Just like PORTB headers, PORTA headers are also available for extension to other boards. Unlike PORTB, which is 8 bits port, PORTA has only 5 pins available named RA0.. RA4. rest of three pins are not available on this board, but if you wish you ca use in your prototype experiments, by not using external crystal, and not using an MCLR resistance (which we can talk later). In present situation since we are using the MCLR pin as well as crystal so these pins are not available for other applications and hence not provided on PORTA header. There is little misprinting on the board, the PORTA pins have been labeled as RB0 .. RB4 this wrong and should be read as RA0 .. RA4. Power supply VCC and GND are also available.
As you know the digital logic assumes 5V as 1 and 0V as 0. However the RS232 communication protocol takes +16V as 1 and 16V as 0. in order to convert the 5V0V logic into 16V 16V logic we need an IC called MAX 232. as shown in the above fig, it uses external capacitors to invert the volts and therefore manages the communication.
RA4. We have connected RA1 (DIP switch 2) to a transistor amplifier and then to the PIZO header (Red Arrow). You can connect any pizo, or a small speaker to get audible beeps, which will be produced by microcontroller, through RA1 line. RA2 (DIP switch 3) is connected to Push switch SW1. and RA3 (DIP switch 4) is connected to push switch SW2. Both these lines have a pull-up resistor connected to VCC. Therefore the RA2 and RA3 are logical 1 when switches are NOT being pressed. The SW1 and SW2 are connected to ground, so when they are pushed the respective lines (RA2 and RA3) go to logical 0. Therefore it is important to know while testing the state of these switches in our software that, when these switches are pressed they will give logical 0 signal to the microcontroller. Since these lines are also available through header for other boards, if these lines are used there, any one or all of them can be disconnected from these push switches and PIZO by turning the appropriate DIP switches ON or Off. DIP 1 DIP 2 DIP 3 DIP 4 No Connection RA1 (PIZO) RA2 (SW1) RA3 (SW2)
able through DIP switches Microchip Mid-Range PIC MCU, 16F628A microcontroller 20 MHZ external clock RS232 Port, for serial communication Two Push switches SW1 and SW2 for digital input selectable via DIP Switches One PIZO output selectable via DIP Switches 13 I/O lines available through PORTA and PORTB headers for external project boards.
So lets summarize the features available on the EasyPIC Motherboard. Power supply: 5V 1A regulated available through headers 8 LEDs monitoring PORTB status, Individually select-
Compilation . The software which does this is called a compiler. In addition to writing a high level program and compiling it and then transferring it to microcontroller, a number of other ancillary functions are helpful for the software developer. These include a debugger to find out why program is not producing expected results, a simulator, to run and test the program right in your PC without actually using a microcontroller, and getting help about the usage of internal registers of microcontroller as well. All these tasks are grouped together into one software, so tat the development cycle is facilitated. Such a working environment is called IDE, or Integrated Development Environment. I am going to introduce you one such tool, called PROTONIDE-Lite. So far as this development kit is concerned it does not matter weather you use BASIC, or C or Pascal or Assembly language, once program is compiled by appropriate compiler it can be used on EasyPIC training system. PROTONIDE is a complete development system for PIC microcontrol-
These are the only two limitations, all other commands are fully available.
PDS button (Green) and the installation will begin. Select all default options and continue till the software is installed. Once installation is complete the windows Start > Programs will contain Proton Development Suit group. Click on Proton IDE Lite icon and you will see the main window of proton IDE Lite. Although you can start working on it right now, it will be helpful to little fine tune the software so that, we can work more efficiently. lers. Developed by Mecanique and Crownhill Associates together. Full version of this development tool can be purchased from www.crownhill.co.uk this Lite version which is provide with this development kit, is free for download. Despite its few limitations, it has enough power to teach the microcontroller application development. Once you have mastered it and you need more, you can ask for full version. Well you know that we are going to write a BASIC language program in this software, and its compiler is going to translate the BASIC language programs (.Bas) into microcontroller understandable code called Hex file (.hex). This hex file can in turn be loaded by our ICPROG and transferred to the microcontroller program memory. That is fairly fine, but where is the hex file generated? Well when you save the program, into some folder, and execute the compiler the same folder will contain, the hex file along with many other generated files. If your program was named Test.bas then the generated hex file will be Test.hex (This is similar to PC .Exe thing). So after compiling we will have to load ICPROG, click its File Menu and open the required hex file and then burn it ito the microcontroller. Proton IDE contains its own Programmer software, caller Microcode Loader, this is not supported by our development board. Fortunately we can tell the Proton IDE that we want to use ICPROG. Then after compilation PROTON IDE will automatically load ICPROG and preload it with compiled hex file, ready to write into the microcon-
troller. This will greatly facilitate our job. You can install our new programmer in one of the two ways. Either Click View > Program and Compile Options and a dialog box with two tabs will appear. Select the Programmer tab, and click Install
Hello World !
Most of you who have already experienced learning some programming language, the very first program is usually some sort of Hello World program. In our case we will write a program to Turn all the eight LEDs on PORTB on. In the PROTON IDE click File > New and a new file named untitled.bas will open, having a default commented header. Enter The following code: New Programmer button. You can also do the same from main window by clicking the small arrow on side of compile and program icon and selecting Install new programmer wizard. Both of these steps are same here after. On selecting install a new programmer, a new dialog box opens asking for selecting a type of programmer software, ICPROG is not enlisted in this list. Select create custom program entry option and click next. In the display name dialog Enter ICPROG or any other meaningful name, this is just for Display. Now click next, in the Programmer File Name dialog enter ICPROG.EXE this is the name of executable file. Click next and in the programmer path, click find manually, and locate the folder where ICPROG is copied. If you followed this manually carefully, we copied it to D:\ICPROG105D folder. In the parameters dialog enter L$hexfilename$ this is instructing ICPROG to pre load the hex file. and click finish. Now your new programmer has been configured to work with PROTON IDE Lite. Now lets check the compile and program icon button. Click on the small arrow on its right side and see that ICPROG entry is there and its checked. Device=16F628A XTAL=20 ALL_DIGITAL=true Output PORTB PORTB=255 End Now save the file to a folder of your choice, I suggest PIC in my documents. Name the file as Test and save it. (Remember there is a problem with compiler that it can not comile files with filenames ending in number, like Test1, or Test2. I suggest naming them like 1Test, or 2Test). Once file is saved,
click the compile and program Icon or pres F10. This will compile the program and automatically load the ICPROG loaded with newly generated hex file. If it does not happen like that, perhaps you have not properly configured the Programmer properly in PROTON IDE. Well fo far so good. Now make sure your serial cable is connected to your JDM programmer hardware, put the microcontroller IC into it and click the program all icon, or press F5. It should transfer the hex file to the microcontroller. Once it is finished programming you should see the device successfully verified message box. Click OK. And close ICPROG. Remove IC from programmer, put it into the motherboard, make sure PORTB DIP switches are all ON. And turn the power ON. All LEDs connected to PORTB
should light up. This indicates a successful program. Your basic language program successfully compiled, and transferred to microcontroller. The program is running fine on the motherboard. So far you have come a long way to setup the working environment, now starts the real fun. Lets write a new program that should blink the LEDs (all 8). Now close the existing program, and click File > New. Enter the following program. Dont worry about commands, just enter it and compile it. At present I want you to get trained on compiling and transferring the program and running it on the motherboard. We will talk about the commands later. Device=16F628A XTAL=20 ALL_DIGITAL=true Output PORTB aa: PORTB=255 DelayMS 500 PORTB=0 DelayMS 500 GoTo aa End Now compile and burn the program and run it on your motherboard. What is the result ? Amazing, the LEDs are blinking, On for half a second and off for half a second. If you have succeeded to this point only then proceed further otherwise revise the lesson, and find what is missing. This is because up to this point I wanted to show you the development cycle. EDIT > COMPILE > PROGRAM > EXECUTE. And this should be encouraging that it works. Now get ready for some serious study. We are going to dive directly into a little theoretical discussion about the architecture and circuit details of the microcontroller, and then return to the BASIC language and programming. It would have been very easy to show you a few powerful commands of PROTON Basic, and help you make some nice programs, but you know a background structural knowledge is essential not only understand the things but to think and develop new devices and solutions. So have a nice mug of coffee and get ready !
Whats in a Family ?
A family of products share similarities in terms of organizational structure and common procedures. Microchip produces a whole range of microcontrollers, all having similar characteristics. They vary in terms of available peripherals. However the peripherals on one chip and the same peripheral on another chip will be the same, and the knowledge you have gained in using it on one microcontroller will be usable on the other. So migrating from a smaller microcontroller to the next higher level is damn easy. You have to learn only the newer peripherals. This is therefore encouraging that if you tend to master yourself of 16F628, it will be easier to use 16f877. as most of the procedure, and things you already had learnt will be the same.
RS232 communication system. This peripheral gives your device an RS232 Serial communication capabilities. PWM: Pulse Width Module CCP: Capture Control module Analog to Digital Converter: Reads analog data, like voltage and converts it into digital format for use in digital system. Analog Comparator: compare voltage with a reference voltage Character and Graphic LCD USB communication Keypad input Digital to analog module EEPROM Real Time Clock Timers Interrupts CAN : network facilities
namely RB2, TX, CK. This is done to reduce the package size. Internally this microcontroller has many registers, whose specific bits correspond with the function of these pins. Therefore a particular pin can be configured to be used accordingly by setting appropriate registers. This looks like a great headache to set these registers, and to remember the bit numbers corresponding to various functions. Fortunately high level languages, like PROTON BASIC and others do it automatically for us, depending upon the type of command issued. However to be on the safer side, and to be more in control one must know what is happening inside. Similarly you can not hard wire a pin to achieve two different functions, like if you hard wire pin 8, RB2 to LCD module, now if you configure the pin for serial transmission, it may interfere with the LCD function. Anyway it is important to know, that the function of various pins is selectable, based upon the bit settings of internal registers. These settings are done by the software.
There are literally many peripheral devices integrated on these chips. If a particular peripheral device is not available on the chip, either it can be made using the software, or additional chips can be used to implement that.
I/O PORTS
Input output ports are the heart of any microcontroller. They are the primary method of communication with the microcontroller. It all depends upon your application that how many I/O lines are required. Most microcontrollers differ in their number of I/O lines. Structure of PORT A These I/O lines are grouped toIC PORT Bit gether as Ports. Some ports contain 8 I/O lines while others may con- PIN tain less than that. Within our softPin 17 RA0 ware a port can be accessed as a whole or as individual bits (or Pin 18 RA1 lines). PIC16F628 has two I/O RA2 Ports. These ports are called Pin 1 PORTA and PORTB. As you can Pin 2 RA3 see from the pin diagram, PORTA RA4 has pin labels as RA0..RA7 and Pin 3 PORTB has labels from RB0..RB7 Pin 4 RA5 Therefore both ports are 8 bit ports. RA6 RA0 is the least significant bit and Pin 5 RA7 the most significant bit. Simi- Pin 15 RA7 larly RB0 and RB7. Pin 16 RA8 RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0 By default Pins connected to PORTB are configured to be
As you can see this is an 18 pin IC, and most of the pins have many functions. For example consider Pin 6, its both RB0 as well as INT. similarly look at pin 8, it has three functions,
used as PORTB whereas pins connected to PORTA are set as analog pins. That is not a big issue, anyway, because just a single instruction in PROTON BASIC will put them for use with PORTA.
The Interrupt
It is usually hard to understand interrupts for a beginner, you can skip this if you don't understand. The microcontroller continues to follow the instructions we have given in our program. However during this cycle if an external event takes place, like push of a button, or a signal from peripheral external device, microcontroller can not notice it until it reaches an instruction that is meant for reading that input. In that case that input might go unnoticed if the signal has ended before microcontroller reaches that instruction. To acknowledge these eternal inputs, and of course to interrupt the running program, every computer and microcontroller has interrupt system. PIC16F628 has one interrupt at RB0. when during a program execution, a logical 1 is received at RB0, microcontroller interrupts the executing program and jumps to a specific location of program, designed to acknowledge and handle that input signal. After handling that signal, the program returns back to the same location automatically from where it was interrupted and continues its execution. There are two type of interrupts, one are the external interrupts that are triggered when an external signal is received at the interrupt pin (RB0 or pin 6). Second types of interrupt are triggered internally due to hardware events. These events are usually the internal timers.
BIDIRECTIONAL I/O
Well so far we know that there are two ports available for communication in 16F628. as PORTA and PORTB. All pins, of PORTA and PORTB can both be used for digital input as well as output. They are therefore called Bidirectional ports. However before using a port, or even individual pin (bit) for input or output it has to be explicitly set in the software. This is also done by setting specific bits of a particular register. Thanks to PROTON BASIC we do not have to remember the register name, and just a command to set a particular bit or entire port as input or output is enough. On top of that there are many commands which will be using various pins, sometimes for input and sometimes for output, these commands will set appropriate pins for input and output automatically without our intervention.
thing else. Various microcontrollers differ in number of PWM modules available on chip. 16F628 has one PWM module. This is enough to learn. If you can work with one, you can work with 5 the same way.
RISC Computers
RISC stands for Reduced Instruction Set Computers. It was noticed that most of the machine level instructions, designed to work on a microprocessor are not used, and the ones frequently used are enough to do their job. So a new reduced instruction set was developed. This reduced the internal circuitry, as well as improved performance. PIC Microcontrollers are all classified as RISC computers. They are one chip computers. PIC 16 series have only 35 assembly language instructions. All processing is done using these 35 instructions only.
2K Flash Memory
PIC16F628 has 2K of flash program memory. Different microcontrollers differ in size of program memory. Unlike ordinary memory, this program memory is 14bit memory. Which means it has 2048 x 14 bits of program storage. PIC16F628 has instructions which occupy 14bits of memory. Therefore these microcontrollers are also called PIC-14. All Pic microcontrollers whose number start with 16, like 16F84, 16F628, 16F877 have 14 bits of program memory and instruction units. Although it looks 2K is a small program memory, but believe me that is more than enough to program a small robot! After all we are not going to write windows application :) 18F series have 16bit program memory, and instruction units. They are therefore called 16 bit core devices.
The Hardware
Well so far you have gained an insight about the various features of 16F628 microcontroller. Now is the time to understand how to use it in a project. In order to experiment with EasyPIC you don't need to do that, but it is an advantage to know, how the microcontroller based circuit is made. After all you are going to design your devices, using these microcontrollers and if you don't know how to put the thing into your circuit, of what use will be all this exercise. Certainly you can not use the EasyPIC motherboard in your application.!
V1 5V +V
U1 R1 10K
RA2 RA3 RA4 MCLR GND RB0 RB1 RB2 RB3 RA1 RA0 CLK2 CLK1 VCC RB7 RB6 RB5 RB4
C1 22pf
PIC16F628
U1 R1 10K
RA2 RA3 RA4 MCLR GND RB0 RB1 RB2 RB3 RA1 RA0 CLK2 CLK1 VCC RB7 RB6 RB5 RB4
C1 22pf
C2 22pf
A switch can be connected to vcc, giving 1 on the pin or connected to ground giving 0 when pushed. We prefer the second form, and the pin is connected using a 10K resistor to vcc to give logical 1 when switch is open and give logical 0 when switch is pressed. EasyPIC uses switches in this form, so when a switch is pressed, it will deliver a logical 0 to the program. For driving low current circuits, like other digital devices, pins can be used directly. To drive a transistor, it is customary to use a current limiting resistor in series, like 2.2K with the base of transistor. The transistor can then be used to drive heavy loads, like switching a relay On.
PIC16F628
Basic circuit drawing is shown above. PIC microcontroller needs only four components to start functioning. A crystal oscillator of your choice is connected between CLK1 and CLK2. and grounded using 22pf capacitors. A 10K resistor is connected to Vcc at MCLR. Connecting a push switch to ground will provide a convenient Reset circuit. (don't remove 10K pull up) so that when switch is open MCLR gets Vcc. Thats it. This is the basic circuit, and rest of the pins are all I/O you are free to use them, in whatever way you like. This circuit will run whatever program has been loaded into it. Since you will have to take the IC to programmer, try putting it in a socket. Now lets see if we can make a blinking LED connected to RB0, and an input switch connected to RA0. Although the PIC pins can both source and sink the load. It is customary to use them as source, so that a 1 on pin drives the load. These pins can give sufficient current to handle the load of an LED, still it is better to protect the pin from overloading by limiting the current flow using a current limiting
Transistor currents
The diagram shows the two current paths through a transistor. You can build this circuit with two standard 5mm red LEDs and any general purpose low power NPN transistor (BC108, BC182 or BC548 for example). The small base current controls the larger collector current. When the switch is closed a small current flows into the base (B) of the transistor. It is just enough to make LED B glow dimly. The transistor amplifies this small current to allow a larger current to flow through from its collector (C) to its emitter (E). This collector current is large enough to make LED C light brightly. When the switch is open no base current flows, so the transistor switches off the collector current. Both LEDs are off. A transistor amplifies current and can be used as a switch. This arrangement where the emitter (E) is in the controlling circuit (base current) and in the controlled circuit (collector current) is called common emitter mode. It is the most widely used arrangement for transistors so it is the one to learn first. Thus if base of transistor is given a small current via a resistance in series and connected to microcontroller pin, a logical 1 on microcontroller will turn the transistor on, and a logical 0 will turn it off.
In the OFF state: power = Ic VCE, but Ic = 0, so the power is zero. In the full ON state: power = Ic VCE, but VCE = 0 (almost), so the power is very small. This means that the transistor should not become hot in use and you do not need to consider its ma x i mu m power rating. The important ratings in switching circuits are the maximum collector current Ic(max) and the minimum current gain hFE(min). The transistor's voltage ratings may be ignored unless you are using a supply voltage of more than about 15V. For information about the operation of a transistor please see the functional model above.
Protection diode
If the load is a motor, relay or solenoid (or any other device with a coil) a diode must be connected across the load to protect the transistor (and chip) from damage when the load is switched off. The diagram shows how this is connected 'backwards' so that it will normally NOT conduct. Conduction only occurs when the load is switched off, at this moment current tries to continue flowing through the coil and it is harmlessly diverted through the diode. Without the diode no current could flow and the coil would produce a damaging high voltage 'spike' in its attempt to keep the current flowing.
DC. Relays can switch high voltages, transistors cannot. Relays are a better choice for switching large currents (> 5A). Relays can switch many contacts at once.
Disadvantages of relays:
Relays are bulkier than transistors for switching small currents. Relays cannot switch rapidly, transistors can switch many times per second. Relays use more power due to the current flowing through their coil. Relays require more current than many chips can provide, so a low power transistor may be needed to switch the current for the relay's coil.
Other sensors, such as a thermistor, can be used with this circuit, but they may require a different variable resistor. You can calculate an approximate value for the variable resistor (Rv) by using a multimeter to find the minimum and maximum values of the sensor's resistance (Rmin and Rmax): Variable resistor, Rv = square root of (Rmin Rmax) For example an LDR: Rmin = 100, Rmax = 1M, so Rv = square root of (100 1M) = 10k. You can make a much better switching circuit with sensors connected to a suitable IC (chip). The switching action will be much sharper with no partly on state. LED lights when the LDR is dark LED lights when the LDR is bright
This command sets the PORTB as output, so you can assign values to the PORTB register, and these values will be reflected on PORTB pins. PORTB=68 Now here we are assigning a decimal value of 68 to PORTB. As soon as this happens the appropriate pins on IC will go high and low. We can see this effect on the status of various LEDs on our EasyPIC board. End Truly speaking there is no end in a microcontroller program. The microcontroller has to do something all the time. The end statement actually puts the microcontroller in an endless loop. So enter the following program in PROTON IDE Lite compiler, and write it into your microcontroller and see the result. I hope you don't need the assistance to do that, to be brief, write the program, compile, ICPROG pops up, put IC in Programmer, Program All, remove IC from programmer, put into motherboard, turn Power on. Make sure DIP switches on PORTB for LEDs are all ON. Device = 16F628A XTAL = 20 ALL_DIGITAL = true Output PORTB PORTB = 68 End So what did you see, RB2 and RB6 are on rest are off, this is similar to 01000100 if you calculate this is the binary number for 68. (you can test it on scientific calculator in windows, write 68, and switch to bin mode). In PROTON BASIC you can represent numbers not only in decimal format, like 68 as we did above but also in binary and hexadecimal format as well. The same number could be written as : PORTB = %01000100 Notice the % sign before number. This indicates to the compiler that the following number is binary. PORTB = $FE This is the hexa-decimal notation for 254. notice $ sign before the number. The PORTB is a byte sized register, so it can hold a maximum value of %11111111 which is equal to decimal 255, or hexa-decimal $FF.
So what if we want to set bit 7 and bit 3 of portb on? Well simply write : PORTB = %10001000 That is fairly good, but when you assign a value to the entire byte, or the entire port, all bits are affected. What if we need access to a single bit? That would be great isn't that? Fortunately PROTON BASIC is here to help us. PORTB.7 = 1 This statement is instructing the compiler to specifically set bit 7 of PORTB without affecting other bits. And to turn the same bit off : PORTB.7 = 0 Simple ! And its quite logical that you can assign only 0 and 1 to bit level access. Now lets write a program to turn the bit 0 (RB0) on: Device = 16F628A XTAL = 20 ALL_DIGITAL = true Output PORTB.0 PORTB.0 = 1 End Notice the OUTPUT statement, instead of writing : Output PORTB we have written Output PORTB.0 this means we can individually set the status of port pins to be input or output. In contrast with the output is the INPUT statement, which we will see in action later. The INPUT statement will set a port, or port pin to be for reading in.
ond. Thus after setting the portb.0 high, processor goes into a loop which finishes exactly after 1000 ms. And then sets the portb.0 low again goes into a loop for 500ms (half a second) then is the Goto statement. GoTo AA This instructs the compiler to jump to a label named AA. As you see we have put a label named AA: just before seting portb.0 high. Labels will be used extensively to control the flow of program in PROTON Basic. Try this program, and see if the LED 0 blinks. There is another more logical way to set the bit values high or low, The High and Low commands. High PORTB.0 Low PORTB.0 The high command will set the portb.0 to 1 and low will set the portb.0 to 0 the high and low commands can also be used to set the entire port pins to 1 or 0. Toggle is another useful command that will invert the state of a bit. It will set 1 to 0 and 0 to 1. IF End IF Decision making and execution of certain instructions on certain condition is one of the most important aspects of a programming language. As we will see later in PROTON BASIC language reference, this is implemented very beautifully in this compiler. IF <Condition to be tested> Then Some instructions here More Instructions here End If This is the usual construct. IF keyword is followed by some testing of condition which will result in yes or no, if it is No, the program will jump to instruction after End IF key word. If the condition is true, or answer is Yes, it will branch inside the structure and execute the instructions there, after last instruction it will jump to the next statement after End IF.
BLINKING an LED
Now lets say we want to turn on and off LED connected to PORTB.0 (or RB0). And we want that LED should remain ON for 1 second and Off for half a second. Device = 16F628A XTAL = 20 ALL_DIGITAL = true Output PORTB.0 AA: PORTB.0 = 1 DelayMS 1000 PORTB.0 = 0 DelayMS 500 GoTo AA End Lets talk about this program, most of the things would be clear to you. Notice the command : DelayMS 1000 This is a processor delay in milli-seconds. 1000 milliseconds = 1 sec-
turn the LED 0 (RB0) on when Switch 1 is pushed, and turns it off when it is pushed again. In other words we want LED 0 to toggle on every push of switch 1. Device = 16F628A XTAL = 20 ALL_DIGITAL = true Output PORTB.0 Input PORTA.2 AA: If PORTA.2 = 0 Then Toggle PORTB.0 DelayMS 500 End If GoTo AA End Notice the IF .. End IF construct. In If we have tested if the portb.2 is low or not, if it is low, it means button is in pressed state, so it enters the construct, and toggles the PORTB.0 and therefore LED 0. a delay of 500ms has been provided to allow time for release of button, otherwise the speed of processor is so fast it would have passed through it a thousand times before you release the button. The GoTo AA will keep on looping. don't worry about other LEDs if they turn on, as we are not dealing with them. Our current project is to toggle the LED 0. Now we want switch 2 to toggle LED 7 (RB7) as well. Device = 16F628A XTAL = 20 ALL_DIGITAL = true Symbol LED0 = PORTB.0 Symbol LED7 = PORTB.7 Symbol SW1 = PORTA.2 Symbol SW2 = PORTA.3 Output LED0 Output LED7 Input SW1 Input SW2 AA: If SW1 = 0 Then Toggle LED0 DelayMS 500 End If If SW2 = 0 Then Toggle LED7 DelayMS 500 End If GoTo AA End This program has something new to share. The Symbol command. Actually symbol is not a command, as it does not do anything, it just declares some symbols, like Symbol LED0 =
PORTB.0 this declares that wherever I use the word LED0, the compiler will replace it with word PORTB.0 this helps in making the program more readable, you give various objects names, and associate them with certain symbols, then use those symbols in program. It will be easier to debug the program later. We can also put If within another IF. This is called nested IF. As an example look at the program below. If SW1 is pressed LED0 is toggled, if SW1 is pressed for more than 500 ms the LED 1 will also toggle. Try it. Device = 16F628A XTAL = 20 ALL_DIGITAL = true Symbol LED0 = PORTB.0 Symbol LED7 = PORTB.7 Symbol LED1 = PORTB.1 Symbol SW1 = PORTA.2 Symbol SW2 = PORTA.3 Output LED0 Output LED1 Output LED7 Input SW1 Input SW2 AA: If SW1 = 0 Then Toggle LED0 DelayMS 500 If SW1=0 Then Toggle LED1 DelayMS 500 End If End If If SW2 = 0 Then Toggle LED7 DelayMS 500 End If GoTo AA End
Producing Sound
Sound is an important feature of many devices. Many a times an audible beep is required to draw the attention of operator towards an event, or to indicate the press of a button. Just like visual alerts sounds are an equally important alert. Sound production in devices is usually through pizo system. Pizo is a ceramic that expands on application of voltage across it. You can use either pizo or speaker in your applications. To produce a sound you have to send a train of impulses to the pizo. These impulses can be sent through microcontroller directly, or through some other sound produc-
ing chip, being controlled by microcontroller. Since we are presently learning microcontrollers, we shall produce sound using the same. You can use any I/O pin connect a pizo directly to the microcontroller, or connect the pizo through an amplifying transistor in that case the microcontroller I/O pin will be connected to the transistor. EasyPIC connects a transistor to the PORTA.1 pin. Pizo headers are provided on the motherboard, just connect the pizo provided on these headers, and make sure that the DIP switch for pizo is ON. This will connect the pizo system with RA1 of microcontroller. Now in order to produce a beep, you have to turn this pin (RA1) rapidly on and off. The rapidity will determine the frequency of sound. Lets try this example first. Device = 16F628A XTAL=20 ALL_DIGITAL=true Output PORTA.1 aa: PORTA.1 = 1 DelayMS 50 PORTA.1 =0 DelayMS 50 GoTo aa Compile this program and run. You should hear an audible beep through pizo, or speaker, connected to the pizo header. Try experimenting changing the delays. This will alter the frequency and quality of sound. Well sound production is so frequently required that PROTON BASIC provides a simple command to produce sound. Sound command has the following syntax: Sound PORTA.1,[90,100] The numbers in brackets are the note and duration pairs. Now try this example: Device = 16F628A XTAL=20 ALL_DIGITAL=true aa: Sound PORTA.1,[90,100,70,50] DelayMS 1000 GoTo aa Notice we did not declare the PORTA.1 as output, the sound command does it automatically. You can even compose music and tones using this command. For details see the PROTON BASIC help for sound command, and try loading the sample programs for sound with EasyPIC training kit. Now since we have experimented with handling switch buttons, LEDs as well as sound, lets write a program that
should read two switches and produce a sound on switch push as well as turn an LED on and off. Device=16F628A XTAL=20 ALL_DIGITAL=true Symbol SW1 = PORTA.2 Symbol SW2 = PORTA.3 Symbol pizo = PORTA.1 Input PORTA.2 Input PORTA.3 Output PORTB PORTB=0 LL: If SW1=0 Then Toggle PORTB.0 Sound pizo,[100,50] DelayMS 50 End If If SW2=0 Then Toggle PORTB.1 Sound pizo,[100,50,110,50,90,50] DelayMS 50 End If GoTo LL I hope this program is quite familiar to you and does niot require a detailed discussion.
OUTPUT PORTB Dim x As Byte For x =0 To 255 PORTB=x DelayMS 100 Next x End In this program x is a variable. Before using a variable, it must be declared with dim statement. The dim statement tells the type of variable AS Byte, Word, Float etc. Even you can declare arrays of variables like : Dim temp[10] As Word This will create an array named temp, having 10 members. They can now be accessed as temp[0] .. Temp[9] or even you can replace the subscript with another variable. We can talk about this later when we talk about the programming techniques. Right now our focus is on EasyPIC development system.
Alphanumeric LCDs can display Letters, Numbers and few Symbols. All characters and letter fonts etc are built into the hardware of LCD device. Alphanumeric displays are further characterized by the number of characters it can display in one line, and the number of lines it has. In an actual project the choice will therefore depend upon the requirements of text to be displayed. For prototyping and general usage a 16 x 2 character LCD is used. From programming or hardware point of view, it does not make any difference. 16 x 2 display has 2 lines (1 and 2) and 16 characters per line. A total of 32 characters can be displayed at one time. One more characteristic, that adds to value of project as well as cost is the backlight option. A backlight brightens the display, and make it
trol the various characteristics of LCD. Have a look at the PRINT command in PROTON BASIC help. Now we are going to write a program that should display a number after every second. Device=16F628A XTAL=20 ALL_DIGITAL=true Dim days As Word ' to count upto 65535 2 byte variable Dim hours As Byte Dim minutes As Byte Dim seconds As Byte days = 999 hours = 0 minutes = 0 seconds = 0 Cls Print "Microelectronics" DelayMS 2000 Cls Print At 1,1,"Days HH:MM:SS" aa: Print At 2,1,DEC5 days," ", DEC2 hours,":",DEC2 minutes,":",DEC2 seconds seconds= seconds + 1 If seconds = 60 Then seconds = 0 minutes = minutes + 1 If minutes = 60 Then minutes = 0 hours = hours + 1 If hours=25 Then hours=0 days=days + 1 End If End If End If DelayMS 1000 GoTo aa
panel. Our Sw1 (RB0) will reset the timer, and Sw2 will Start and Stop the timer. Device=16F628A XTAL=20 ALL_DIGITAL=true Symbol Sw1 = PORTB.0 Symbol Sw2 = PORTB.1 Input PORTB.0 Input PORTB.1 Dim hours As Byte Dim minutes As Byte Dim seconds As Byte Dim s As Bit s=0 hours = 0 minutes = 0 seconds = 0 Cls Print "Microelectronics" DelayMS 2000 Cls Print At 1,1,"HH:MM:SS" aa: If Sw1 = 0 Then DelayMS 50 If s=0 Then s=1 Else s=0 End If End If If Sw2=0 Then DelayMS 50 hours=0 minutes=0 seconds=0 End If Print At 2,1, DEC2 hours,":",DEC2 minutes,":",DEC2 seconds If s=1 Then seconds= seconds + 1 DelayMS 1000 End If If seconds = 60 Then seconds = 0 minutes = minutes + 1 If minutes = 60 Then minutes = 0 hours = hours + 1 End If End If GoTo aa
So that looks nice and simple, you see its fairly easy to implement any conceptual thing using microcontrollers, without having extra hardware design. The LCD board contains two push switches as well, they are connected to RORTB.0 and PORTB.1 you can use them in your programs to accept user input. In addition you can use the two push switches on motherboard, and the pizo. Now we have a total of 4 switches and a pizo and an LCD display, we can do a lot with this. In our next application we are going to make a timer as well as use of buttons. We have two buttons available on LCD
Now this program is working as a stop-watch. Pressing Sw2 will reset the watch and pressing Sw1 will pause / start the timer. Now lets make another program. We want to make a program that will accept a number ranging from 1 to 255. on selecting the number the system will display the number times table on LCD. Device=16F628A XTAL=20 ALL_DIGITAL=true Symbol Sw1 = PORTB.0 Symbol Sw2 = PORTB.1 Symbol SwEnter=PORTA.2 Input PORTA.2 Input PORTB.0 Input PORTB.1 Dim x As Byte Dim i As Byte x=10 aa: Cls Print "Microelectronics" DelayMS 2000 Cls Print At 1,1,"Sel a No." While SwEnter <> 0 If Sw1 = 0 Then x=x+1 DelayMS 50 End If If Sw2 = 0 Then x=x-1 DelayMS 50 End If Print At 2,1,"X :",Dec x Wend Cls Print At 1,1,"Table :",Dec x For i=0 To 10 Print At 2,1, Dec x , "X", Dec i,"=",Dec x * i DelayMS 1000 Next i DelayMS 1000 Cls Print "Finished ..." DelayMS 2000 GoTo aa The program is simple, yet it shows how you can get a number from two or three switches without having a key pad. In this program a variable x has been declared, and an initial value of 10 set. This number is displayed on LCD and condi-
tion of switches is read, till SwEnter (PORTA.2) is pressed. Pressing SW1 will increase value of x and pressing SW2 will decrease it. When SWEnter is pressed, loop is exit, and another loop to calculate the table, based upon a loop controlled by variable i. the values of table are displayed on LCD. So you must be convinced by the versatility of microcontroller system, the same hardware, once configured to act as a timer and now as a simple calculator.
XTAL = 20 ALL_DIGITAL=true ' Set baud rate to 9600 HSERIAL_BAUD = 9600 ' Enable serial port and continuous receive HSERIAL_RCSTA = %10010000 ' Enable transmit and asynchronous mode HSERIAL_TXSTA = %00100000 Optionally clear the buffer before receiving HSERIAL_CLEAR = On LOOP: HRSOut "Microelectronics Pakistan",10, 13 Delayms 1000 Goto LOOP Well before discussing, run this program. In order to communicate with the terminal window, of your PC, you will need to configure it first. So, before turning the power of your motherboard on, lets get back to PROTON Compiler, click on View > Plugins > IDE serial Communicator. This should popup a serial communication window.
Now your PC is ready to communicate with our microcontroller. Now click on the connect Icon as shown below, and the terminal should start. Before turning the power of microcontroller on, make sure that the two jumpers for serial communication are ON. This will establish the link between pin 7 and 8 to the RS232 system. Now turn the power ON and you should see the message Microelectronics Pakistan appearing on terminal window, after every second. If all this succeeds then progress further, or check out the fault. This is the simplest communication, if you can not establish it, something is wrong. Lets talk about the various configuration settings we used in this program. As I already told you, Pin 6 and 7 are also used for other purposes, like PORTB.1 and PORTB.2. In order to activate the UART system, we have to set RCSTA and TXSTA registers of the microcontroller. Show below is the
configuration of RCSTA register. This register will set the receiving characteristics. Its highest bit 7, is SPEN, which means serial port enable. A 1 at this bit will enable the serial port. And CREN if set to 1 will put it to continuous receive (Asynchronous) mode. This register can be set by setting the values HSERIAL_RCSTA = %10010000 Notice the binary number, we have set the SPEN and CREN bits of this register. Similarly the Transmit register: TXSTA HSERIAL_TXSTA = %00100000 This window has three panels, one on left is to configure the hardware communication, like port number etc. the other two panels are for transmitting data to and received data from the port. Now click on Port Number and select the communication port of your computer which will be used for communication. Next click on the Baud Rate, this is the speed at which communication will take place, this must match the speed you have set while programming the microcontroller. We have set this to be 9600 in previous example. Next click on Parity and set it to none. Set byte size to 8, and stop bits to 1.
We have set the TXEN bit, which will enable the transmission of data from the UART port. HSERIAL_BAUD = 9600 This setting will select the transmit speed, and both devices should agree on that. HRSOut "Microelectronics Pakistan" This command is for transmitting the data to the other device. The ,10,13 in the program instructs new line and carriage return. These are optional. Now you can send any data
from microcontroller to the serial port including text, numeric as well as variables. For further details look at the HRSOUT command. Remember this command will only communicate using the pins, specially designated for communication using internal hardware. If you want to communicate using standard I/O lines, then use RSOUT or SERUOT commands. See Proton Help. Now here is some more complicated example, this program will display the Times table on the terminal. This is to show how you can display the variables from microcontroller onto your terminal.. Device 16F628A XTAL = 20 ALL_DIGITAL=true HSERIAL_BAUD = 9600 Set baud rate to 9600 HSERIAL_RCSTA = %10010000 ' Enable serial port and continuous receive HSERIAL_TXSTA = %00100000 ' Enable transmit and asynchronous mode HSERIAL_CLEAR = On ' Optionally clear the buffer before receiving Symbol Pizo=PORTA.1 Output Pizo Dim x As Byte Dim y As Byte y=2 LOOP: HRSOut "MIcroelectronics Pakistan",10, 13 HRSOut "Table of ", Dec y ,10,13 HRSOut "=====================",10,13 For x=1 To 10 HRSOut Dec y," X ", Dec x, "=", Dec x*y,10,13 Next x HRSOut "*******************",10,13 DelayMS 500 Sound Pizo,[100,50,110,50,90,100] DelayMS 5000 y=y+1 GoTo LOOP Well so far we have used the serial port of microcontroller to transmit data to other devices (in our case our PC). Now lets accept data from the device and return back some data. Device= 16F628A XTAL=20 HSERIAL_BAUD = 9600 ' Set baud rate to 9600 HSERIAL_RCSTA = %10010000 ' Enable se-
rial port and continuous receive HSERIAL_TXSTA = %00100000 ' Enable transmit and asynchronous mode HSERIAL_CLEAR = On ' Optionally clear the buffer before receiving Dim var1 As Byte Dim i As Byte HRSOut "Microelectronics Pakistan",13 HRSOut "=============================",13 Loop: HRSOut "Enter a Number 1-255 and press Enter",13 HRSin Dec var1 HRSOut "Here is Table of :", Dec var1 For i= 1 To 10 HRSOut Dec var1," X ", Dec i , " = ", Dec i * var1,13 Next i DelayMS 1000 GoTo Loop
Most of this program is same as before, notice HRSin this statement waits for an input from the terminal, reads the number into a variable and thats it. Now we have the input into the variable, we can do anything with it. This can be a command, or instruction to control the behavior of microcontroller.
Using EEPROM
Although the program memory is flash based, and the program is preserved even after the power is shut down, the run time memory for variables, is conventional RAM. All variables are created in this memory, and they tend are volatile. This means if power is shut down, the variables holding data are lost. We need some sort of permanent electronic storage, which can be read when required, and which is preserved even after power failure. This is an important feature of microcontroller applications. A common usage is to keep the last settings of the device. For example consider an airconditioner, where user has set the desired temperature, the speed of fan and the swing settings of air. When aircondition is powered off. These settings must be preserved, so that next time user should only turn it ON, and the aircondition is in the same mode as before! Similarly consider a microwave oven, where a number of settings are required for a particular type of cooking. Like one set of settings for defrost, another for heat, another for vegetables another for meat and still others for pop-corns! All these settings can be called pre-programs. Yet user can select his own settings and save them for each use later. This
type of application needs to store variables into some nonvolatile memory. The data must be stored and retrieved, as well as changed as required. EEPROM (Electrically Erasable and Programmable Read Only Memory). Actually its not read only, its both, read and write. However write is little slow as compared to conventional RAM. Therefore it is better to keep the writes minimal in this memory. Our 16F628 has 128 bytes of EEPROM memory available on chip. We can use it to store data, or settings. In this section we shall explore how to use this memory. If more memory is required you can either chose a different microcontroller, or use what is called external EEPROM. We will talk about this later. Lets have a look at this program. Device=16F628A XTAL=20 ALL_DIGITAL=true Dim a As Byte Dim i As Byte Loop: For i=0 To 4 a =ERead i Print At 1,1 ,"EEPROM Byte:",DEC3 i Print At 2,1, "Data Stored:", DEC3 a DelayMS 2000 Next i GoTo Loop End EData 100,20,59,70,100 There are two new commands, Edata and Eread. Edata is the first command I should introduce. This command can be issued anywhere, but usually at the end of program. It is not executed at the time of program execution, but during compile the data in bytes will be written directly into the EEPROM memory. So when the chip is programmed, this data is hard coded into its EEPROM. The data can then be read into the program for use by ERead command. This command needs the address of byte from EEPROM to be read. Like a=ERead 2 will read in byte no 2 (starting from 0) containing 59 into variable a. this type is very useful for writing permanent data, like pre programmed settings, or fonts etc. Now what if we want our program to write data into EEPROM. Its simple you issue EWrite command. The sytax is EWRite Address , [Variable, variable] Address is the starting address, and variable is the value to be stored. You can write just one variable at a time , or write multiple variables separated by comma. The number of bytes
consumed will depend upon the type of variables, like byte size will occupy 1 byte and word size will occupy 2 bytes. Lets consider the example of previous program, the toggling LEDs. you set the speed of toggling by selecting the value of t using Switches. The newly selected speed is OK for you. Once you power off, and restart the micro, it starts with the default value of t=100, and you have to set the speed again. Why not to store the value of t in EEPROM every time you change it, and read it back at the time of restart. So when you restart your program, it will start with the same speed, you last selected. Is that not Nice ! Have a look at this program: Device=16F628A XTAL=20 ALL_DIGITAL = true Output PORTB Input PORTA.2 Input PORTA.3 Dim t As Byte Symbol LED0 = PORTB.0 Symbol LED1 = PORTB.1 Symbol SW1 = PORTA.2 Symbol SW2 = PORTA.3 t= ERead 0 If t=0 Then t=100 EndIf loop: PORTB=1 aa: EWrite 0, [t] If SW1 = 0 Then t=t - 5 PORTB = t DelayMS 300 GoTo aa EndIf If SW2 = 0 Then t = t + 5 PORTB = t DelayMS 300 GoTo aa EndIf DelayMS 10 * t Toggle LED0 Toggle LED1 DelayMS 10*t GoTo loop Notice the Eread and EWrite commands. This program also does something clever, that when a switch is pressed the
value of t is displayed in binary format on the PORTB LEDs, after that they are cleared as microcontroller is taken out of the data entry mode and display begins toggling. If this looks confusing, you better try writing simple application. Now run this program, set some toggling speed. And turn the system off. Now restart it by powering on (not reprogramming), and the LEDs will be toggling at the same speed as previously set. EEPROM has many such applications, if more memory is required, we can get EEPROM Ram separately, and attach it to 16F628. It can then store data in that EEPROM (External) 16F628A contains all the necessary protocols to communicate with these devices (this is called I2C). We shall talk about it in advanced programming. Think about an application where a temperature sensor has been attached to the microcontroller. Is giving the environment temperature, now we want a data logger application that should be kept in some place and note the temperature variations after every 4 hours. So we can setup a timer within the microcontroller which will keep on recording the current temperature after every 4 hours in EEPROM. How will we get the data out of microcontroller EEPROM? Many possibilities display on LCD, transmit using UART or simple, read the microcontroller data using ICPROG!
Interrupt
As the name indicates, an interrupt is a process that interrupts the execution of a program. Normally our program is executing one instruction after another in a sequence. It can not notice an eternal event, like button press, or external impulses etc, unless it reaches a command that reads for it. Fortunately our microcontroller provides a mechanism. If the interrupt system is turned on, despite the program being executed, an external event will immediately bring the attention of microcontroller towards it. In order to handle such events we have to write a special part of code, called interrupt handler. Whenever interrupt takes place, microcontroller will stop executing the current instruction and jump to the interrupt handler, in interrupt handler, we do some process, depending upon what we want to do with the event that caused the interrupt, and then jump back to the same code and instruction, which microcontroller was executing before interrupt. Interrupts can be external and internal. External interrupt is a signal at RB0 (pin 6). Whenever a signal reaches here the interrupt handler will execute. This signal can be button press, external signals or anything, indicating availability of some data etc. Internal interrupts are fired by timers. If a timer has been configured to fire interrupt, whenever it reaches its full capacity, it fires the interrupt and enters into another cycle. For example if we turn on interrupt on timer1. Since its 16 bit timer, it will reach a maximum value of 65535. After which the next signal will make it 0 and cause an interrupt. This will indicate that the timer has reached its full value. Counting the number of interrupts and multiplying them with 65535 will give us the total number of impulses. So these interrupts can be used along with the timers and counters to handle the events. See frequency counter application using 16F628.
rotation depends upon the voltage. A 6V motor will run at full speed when 6V are applied. The speed will also depend upon the load as well. The direction of rotation will depend upon polarity. If you reverse the supply, I mean swap the +ive and ive supply, the motor will rotate in reverse direction. This is usually implemented using H-Bridge circuits and a microcontroller to control the motor.
Motors
Motors are very frequently used devices in applications, which does the mechanical function. Like turning a fan on and off, or opening a tray, positioning the laser pointer, moving the robot and lot more. All these are examples of using motors, but in each application motor is being used in a different manner. In turning a fan on and off, its simple, switching, in opening the tray, you have to control the motor till tray is open, and then turn the motor in reverse direction to close the tray. In positioning of laser, the motor has to move in precise way, so that we can position the device at an appropriate angle. A robot moving, using two motors, must control the speed of each motor in such a way that it can control its movement path, turn around, bend and lot more. It is therefore important to know what are motors and how to control them. Remember industry has a number of applications of microcontrollers controlling motors. The idea is same, however the level of motor power and current etc will vary, but the process will be same as you will learn here. Motor controlling module, is not part of this basic training kit, however you can purchase it separately from us. The following account is given only to introduce you what are motors and how they are controlled. The accompanying CD of this kit contains many articles which are more than enough to teach you.
Stepping Motors
Stepping motors are different from DC motors, in many respects. They do not run on application of current, but they move in steps. Each step depends upon the type of signals it is receiving. For example a stepping motor having 8 steps will complete one circle in 8 steps, on each impulse it will move by 45 degrees. Motors with a resolution of up to 0.72 degrees are available (500 steps in one rotation). So you can very precisely control the movement of device. You will find lot of articles on stepping motors on the accompanying CD.
Types of Motors
There are three types of motors commonly used in electronics. DC Motors (Brushed) Stepping Motors Servo Motors
Servo Motors
Servo motors are yet another type. They can position themselves only from 0 to 90 degrees. The precise angle depends upon the train of signals its receiving.
DC motors are the types we commonly encounter in toys etc. they require a DC voltage, and start rotating. The speed of
I purposly made this first program as small as possible, simply to demonstrate how easy it is to control a stepper motor. Also note the use of high and low commands to control the output lines, rather than peek and poke routines. For our purposes, high and low are sufficent.
tors line 2N2222. This transistor can be directly driven by PIC outputs. The transistor used, TIP120, is actually a NPN Darlington (it is shown as a standard NPN). The TIP120's act like switches, activating one stepper motor coil at a time. As previously discussed, inductors, should be protecting transistors by a diode. Due to a inductive surge created when a coil is toggled, a standard 1N4001 diode is usually placed across each transistor as shown in the figure, providing a safe way of dispersing the reverse current without damaging the transistor. Sometimes called a snubbing diode. The TIP120 transistors do not need an external snubbing diode becasue they have a built in diode. So the diodes shown in the drawing are the internal diodes in the TIP120 transistors. The simplest way to operate a stepper motor with a PIC is with the full step pattern shown in Table 1. Each part of the sequence turns on only one transistor at a time, one after the other. After the sequence is completed, it repeats infinitely until power is removed.
----listing 1---' First stepper motor controller program ' Rotates motor at set speed forever Symbol Q1 = PortB.3 Symbol Q2 = PortB.2 Symbol Q3 = PortB.1 Symbol Q4 = PortB.0 Output portB loop: high Q1 ' turn on Q1 delayms 25 ' wait 25 ms low Q1 ' turn off Q1 high Q2 ' turn on Q2 delayms 25 ' wait 25 ms low Q2 ' turn off Q2 high Q3 ' turn on Q3 delayms 25 ' wait 25 ms low Q3 ' turn off Q3 high Q4 ' turn on Q4 delayms 25 ' wait 25 ms low Q4 ' turn off Q4 goto loop ' forever ----listing 1----
them a negative supply through switching transistors. A logic 1 on base of a transistor will turn it on, and connect the entire column to ground. The pins of PORTB will determine which LEDs of that column will turn on. As you can see in the figure, we will turn only one coulumn ON at a time, and change the PORTB appropriately to reflect the pattern of LEDs to be turned ON, on a given column. In order to control the five transistors, we have implemented a decade counter IC, CD-4017 this IC has a clock input and ten outputs. Outputs are numbered from 0 to 9. On every clock signal, it turns the next output line a logical high, and all others are turned low. So when it is reset (using reset signal) output 0 will be 1 and all others 0 on receiving an impulse at clock, output 1 will become 1 and all others will go 0 this will continue until output 9 goes high, after which again output 0 goes high. Since we want only 5 columns to be selected we will clock the IC 4 times and then issue a reset impulse, to bring the counter back to 0. We have connected the PORTA.0 to the clock of 4017. thus a logical 1 followed by 0 on PORTA.0 will give it a clock pulse to change the column. Similarly PORTA.1 has been connected to the Reset pin of 4017, a similar pulse, 1, 0 will reset the counter and bring it back to column 0. This device also has two push switches connected to PORTA.3 and PORTA.4 and a pizo connected to PORTB.7. So far as the device data is concerned, we need to know only a few things: PORTB.0 to PORTB.6 will chose the rows (or LEDs to be turned on) and PORTA.0 will clock the selected Columns. PORTA.1 will reset the columns to col-0.
This may not seem very impressive but you can display all sorts of effects and treat it like a "window on a large video screen." The project comes with a series of test programs to test the operation of the screen and also the surrounding components. Then we come to the experiments. They start with a simple routine to illuminate a single LED and progress to flashing a LED, running a set of LEDs up and down the screen, and then a variety of animations. The things you can do are almost unbelievable. And it's all covered in the course. The approach we have taken is completely different to anything you have seen before. I have seen some of the other microcontroller projects been totally confused with their content and approach. They were really impossible to understand. You needed to be an expert to start the first lesson! That's why I felt compelled to create a project that teaches in a completely different way. Once you complete this course you will be able to look at the other projects and work out what they are trying to present. I'm saying this because if you have seen the other projects and given up in frustration, the worry is over.
col 0 Set Reset Clear Reset PORTB=127 ' Bits 0 to 7 are ON End Now run the program, this should turn all the LEDs in Col 0 turn On. Proceed to next step only if this is successful. Now try changing the value of PORTB in the above program, like : PORTB = %00000001 And see the results. This will turn LED in Row 0 ( as PORTB.0 is 1) and col 0 ON and stay on.
Persistence of Vision
As you are well aware, the project will display one column at a time , so how can we display the letter 0 as shown in figure above? This is because of persistence of vision, the same mechanism used in your television. Only one column is shown at a time, but they are shown in rapid succession, so that our eye sees it all at the same time Smart! Isnt that. So lets setup the board and here we go. Setting up the board is simple, there are two headers on board, labeled as PORTA and PORTB. Connect the supplied cables into them, and connect to the respective headers on motherboard. Right now, we are not going to use pizo so, forget about it. Since LEDs are going to consume lot of energy, connect a battery which is in good condition or better use an 6-9V adapter. Lets write our first program. Device=16F628A XTAL=20 ALL_DIGITAL=true Output PORTB Output PORTA.0 Output PORTA.1 Symbol Clock = PORTA.0 Symbol Reset = PORTA.1 ' give a reset impulse, this will select
Changing Column.
Now comes the Fun. Lets make all LEDs on a column on and change the column every second. Device=16F628A XTAL=20 ALL_DIGITAL=true Output PORTB Output PORTA.0 Output PORTA.1
Symbol Clock = Symbol Reset = ' give a reset col 0 Set Reset Clear Reset PORTB=255 AA: DelayMS 1000 ' give a clock Set Clock Clear Clock GoTo AA End
pulse
Now run the program, you will notice that all LEDs on a column are ON, and the column is advancing after 1 second. Notice after column 4 there is blackout, and after a while about 5 seconds the column 0 again turns ON. This is because, we are continuously clocking the 4017. after column 4 it goes to column 5, then 6, 7 and so on, which do not exist. So what we need is that we should clock only 4 times and then issue a reset pulse. Lets try this one. Device=16F628A XTAL=20 ALL_DIGITAL=true Output PORTB Output PORTA.0 Output PORTA.1 Symbol Clock = PORTA.0 Symbol Reset = PORTA.1 Dim x As Byte ' give a reset impulse, this will select col 0 Set Reset Clear Reset PORTB=255 AA: For x=0 To 4 DelayMS 1000 ' give a clock pulse Set Clock Clear Clock Next x Set Reset Clear Reset GoTo AA End As you can see we are using a For loop to repeat the cycle 5 times and then issue a reset impulse.
What did you find? You are right, increasing the speed, makes it difficult for our eye to follow, the changing columns, and at very high speed, we hardly can notice, that only one column is being shown at a time, what we see is that all LEDs are ON at the same time. This is persistence of vision.
Have a look at the figure above, as you can see numbers, and of course other graphics can be drawn on the 5 x 7 LED display. Lets concentrate on number 0. It contains 5 columns. Column 0, has the pattern 01111110, whereas column 1 has pattern 1000001. To facilitate this make a grid of 5 x 7 rows and columns, on a graph paper or even a simple paper and fill the appropriate boxes to make numbers. Now take one column at a time, and figure out the bit pattern, this is the number you are going set for this column on PORTB. The numbers shown in above figure are in hexadecimal format. So lets say in order to display number 7, you have to set PORTB to $40,$47,$48,$50,$60 (The $ sign indicates number in hexadecimal format). Lets try this program. Device=16F628A XTAL=20
ALL_DIGITAL=true Output PORTB Output PORTA.0 Output PORTA.1 Input PORTA.3 Symbol Clock = PORTA.0 Symbol Reset = PORTA.1 Symbol SW1 = PORTA.3 Dim x[5] As Byte ' Making an array to hold bit patterns Dim i As Byte x[0]=$40 x[1]=$47 x[2]=$48 x[3]=$50 x[4]=$60 aa: Set Reset Clear Reset For i =0 To 4 ' Column Scan PORTB = x[i] DelayMS 1 Set Clock Clear Clock Next i GoTo aa Run this program and it should display the number 7 on display. Now try changing the data in array and make new numbers. All numbers, letters, graphics have to be drawn within the bounds of 5 bytes. Each byte is the corresponding column.
Dim k As Byte Dim n As Byte x[0]=$40 x[1]=$47 x[2]=$48 x[3]=$50 x[4]=$60 x[5]=0 aa: For j = 0 To 70 Set Reset Clear Reset For i =0 To 4 ' Column Scan PORTB = x[i] DelayMS 1 Set Clock Clear Clock Next i Next j n=x[0] For k=0 To 4 x[k]=x[k+1] Next k x[5]=n GoTo aa We have increased the dimension of display to 6 columns. This is because to put a 0 in the last column, so that there is space between the scrolling number 7. the display is still using those 5 columns of array.
Up - Down Counter
Have a look at this program, it has a lot to teach. We have stored 4 numbers, 0,1,2 and 3 in EEPROM. And load the required number, depending upon the value of variable n. to display it. Next we read two switches, pressing SW1 will load next number and pressing SW2 will load previous. Device=16F628A XTAL=20 ALL_DIGITAL=true Output PORTB Output PORTA.0 Output PORTA.1 Input PORTA.3 Input PORTA.4 Symbol Clock = PORTA.0 Symbol Reset = PORTA.1 Symbol SW1 = PORTA.3 Symbol SW2 = PORTA.4 Dim x[5] As Byte ' Making an array to hold bit pattern Dim i As Byte
Dim n As Byte n=0 GoSub Load aa: If SW1= 0 Then DelayMS 200 n=n+1 GoSub Load End If If SW2=0 Then DelayMS 200 n=n-1 GoSub Load End If Set Reset Clear Reset For i =0 To 4 ' Column Scan PORTB = x[i] DelayMS 1 Set Clock Clear Clock Next i GoTo aa Load: For i=0 To 4 x[i]= ERead (n*5) + i Next i Return EData EData EData EData $3e,$41,$41,$41,$3e $0,$10,$20,$7f,$0 $27,$49,$49,$49,$31 $22,$41,$49,$49,$36 ' ' ' ' 0 1 2 3
ments of the digits are connected together, and only seven pins are taken out for data. However the common cathode (or anode) of every digit is taken out separately. So data is sent in the same way as we did in our 5 x 7 display project. Lets say we want to display 57 on two digit multiplexed display. First we will set the segments to be turned on for unit digit. Then we take down the common cathode of the unit digit and take high. So the data 7 will be displayed on unit digit. Next we set the data for number 5 and turn the unit digit off and tens unit on. Now 5 will be displayed on tens digit. We keep on scanning the digits speedily and due to persistence of vision we see 57 to be displayed. Most of the times seven I/O lines are used to turn the segments ON and OFF. And two or more lines (depending upon the digits) are used to turn on transistors which are connected to common cathode of digits. Next let's step up to 7 LEDs. And let's arrange them in the shape of a figure 8 like this: Wow, with this kind of configuration we can build the numbers 0 - 9 and even some letters. I should patent this idea. Anyway, a 7 segment display consists of 7 individual LEDs with one end of each LED connected together. If all of the plus ends are connected together, it is called common anode. If all of the minuses are connected together, it is called common cathode. Whether you choose common anode or common cathode depends on how you want to hook things up. I am going to choose common anode with all the pluses connected together for reasons you will see shortly. Figure 5 shows one way to connect the display to a PIC. The 8 cathode lines are connected to the 8 PortB lines through series resistors. 8? What happened to 7 segments? I have also connected the decimal point for good measure. The common anode line is connected to 5 volts. We could use the technique described above and put only one current limit resistor in the common line to 5 volts. However we would have to light up each segment one at a time over and over again in order to display a complete character.
We would need to do this at least 100 times per second (1000 times per second is better) to cut down flicker. If you only have one 7 segment display in your project, this could be workable. But we are going to add more. To add another display, we could use 8 more I/O lines, connecting the next display to PortC (for 16F877), for example. While it makes programming easier, it eats up I/O pins in a hurry. You could also add separate latches or even decoders for each display, but, once again, we are going to use software instead of hardware. As you can see in above Figure the cathodes from a particular segment of each display are all connected together and then connected to a PIC I/O line through a series resistor. We have also removed each common anode from 5 volts and made it controllable by a PIC I/O pin. In this manner, we can set up the segment value for a given display and then briefly turn on the anode for that display. If we do each one fast enough, we will see the entire display, flicker free.
Let's look at the case of 8. Eight is pretty simple. It is all the LEDs (except the decimal point) on. To display 8 we need to put a binary 1000 0000 on PortB. This will turn on all the LEDs except the decimal point. 0 = on? Remember, we are controlling the minus side of the LEDs. We also need to put a value onto PortA to address a specific LED digit, 1110. Once again, 0 will turn on one of the transistors and 1 will ensure the others are off. The number 0 is simply an 8 with the middle segment off, 1100 0000. Now we could have a subroutine to decode each digit, but that gets long and I hate to type (hard to tell?) The easiest way to proceed is by using a lookup table. This method is particularly effective when you have a limited number of combinations of desired states, in our case 10 (09.) So I hope this should be helpful in designing an application to display data on seven segment displays. So now you have fairly large number of ways to present data. You can use an LED, you can use sound, character LCD display, matrix displays or 7 segment displays. Number 0 1 2 3 4 5 6 7 8 9 Segments 1100 0000 1111 1001 1010 0100 1011 0000 1001 1001 1001 0010 1000 0010 1111 1000 1000 0000 1001 1000 Hex $C0 $F9 $A4 $B0 $99 $92 $82 $F8 $80 $98
Remember earlier we chose common anode? Let's take a look at current considerations to see why. The PIC is now driving up to 8 LEDs (segments) at a time off a single port. Just as each I/O pin has a limit to the amount of current it will source or sink, each port also has a limit. To do the least damage, we are sinking the current to ground rather than sourcing it to 5 volts. You'll also note in the figure that I snuck in a transistor between the PIC and the common anode to each display. Since the current for the entire display runs through this one pin, it could overload a single I/O line. The transistor amplifies the current drive capability of the I/O line to solve this dilemma. It is easy to operate, put ground on the I/O pin to turn on the transistor and enable a given display, put 5 volts on the pin to turn off the transistor and the display. Now all we need is software. The first task is to figure out how to get numbers (and even some letters) on the display. All we really have right now are a bunch of individual LEDs connected to I/O pins. To form characters, we need to come up with a way to turn on specific ones while leaving others off.
filter only 38KHZ signals and transmit the signal as logical 1 on RB2. When making this board, please make sure the power supply pins are in accordance with the motherboard. Most receivers give 0 when they receive infra red signal. The transmitter is a simple single transistor digital switch, when pin RB1 goes high this turns the transistor on, passing current through the IR LED's, with the current limited by R5 between the LED's. This passes quite a high current through
on the same theme - but, depending on the actual input device, you may be forced to use a particular method. This scheme can be implemented using transistors as well.
the LED's and it's important that they are pulsed and not left on permanently or damage will probably occur - C2 is fitted to provide the required high current pulses without upsetting the main 5V rail. By pulsing the LED's with high current we increase the range and lower the current requirements - this is standard practice in IR remote controls, R5 limits the current through the LED's. As the receiver detects 38KHz modulation, we need to pulse the LED's at 38KHz, this can be done by feeding the LED's with a 13uS pulse followed by a 13uS space - in actual fact I decrease the pulse length, and increase the space length (keeping the total length at 26uS) this reduces the power consumption. Although it's labeled as connecting to PortB, as with most of the boards, it can also be connected to PortA if required.
Using Keypad
Keypad is the standard method of getting numeric input, and many other types of inputs. Instead of using the individual buttons, as previously used, keypad is a better alternative if more switches are required. For example consider a key pad with 16 switches, this is called a 4 x 4 matrix keypad. Normally this would require you 16 individual I/ O lines to read the switches. However the keypad would require only 8 lines. Shown in the figure is a keypad where switches have been arranged in 4 rows and 3 columns. This is 4 x 3 keypad and would require (4+3) 7 I/O lines. Every key in keypad is connected in the form of a matrix, so each key would have a row and a column. In order to use the keypad you have to connect pull-up resistances on rows. This is how the HEX keypad is connected, each square with a number or letter in it is a push to make switch, which connects the horizontal wires (rows) with the vertical wires (columns). So if you press button 'A' it will connect COL1 with ROW4, or pressing button '6' will connect COL3 with ROW2. For a numeric (4x3) keypad COL4 will be missing, and 'A' and 'B' replaced with '*' and '#' but is otherwise the same. The sample programs use a lookup table for the keys, this would need to be changed to insert the correct values for the non-numeric characters. The labels on keypad are all arbitrary, the system will only recognize which key is pressed, irrespective of its label. A common use for keyboard scanning applications, this example reads the keypad and transmits IR remote control signals to control a Sony TV, this works in a very similar way to the circuit used in your TV remote control. As you can see in the accompanying figures, you can make a simple board, with pull up resistors, and connect your keypad on one end, and the connector cable for your microcon-
troller kit on the other hand. The number of I/O lines used will depend upon the keypad. We recommend the 4 x 3 keypad and connect it to PORTB on 16F628 motherboard. The rows are connected to RB0..RB3 and Columns from RB4..RB6 (or RB7 if 4 x 4 keypad is used). Since PIC16F628 has internal pullup resistances on PORTB, you don't need these pull up resistors if connecting to this port. However it is always good to have pull up on your device, so that you can connect it to some other port, like PORTC on 16F877 if required.
matic is simple, we leave it up to you to write the software. This schematic shows different connection scheme of connecting keypad with microcontroller. It does not matter, you can change the pins and connections the way you want, and change the program appropriately. for example I would like to connect the keypad to PORTB and rest of circuitry to PORTA.