You are on page 1of 44

EasyPIC 1 A Beginners Guide

Teach Yourself Microcontroller Based Application Designing and Programming


Dr. Amer Iqbal Qureshi
Microelectronics Pakistan www.electronicspk.com : info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 2

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.

Scope of Microcontroller Applications


Due to the versatile nature of these chips, they have found applications in almost every electronic device today. Think of any device which seems to be computer controlled, it will have a microcontroller working in it. For example a microwave oven, has a megnatron gun, which heates the food, a motor which rotates the plate, and a display to show the time and cooking parameters etc. Now on the basis of cooking parameters selected by user, the microcontroller inside will be controlling the plate motor, as well as the megnatron gun, turning them on and off periodically to heat the food. Think of a temperature regulator in your air-conditioner, the microcontroller is sensing the room temperature and according to the selected options, turns the compressor on or off, and the wind swivel motor on and off. So it has a microcontroiller as well. Think of traffic lights, they have to be turned on and off in a set order, it is easy to make them using logical gates, but what if we need to change the order and timing? A microcontroller can do the job easily. Think of your car, it has microcontroller sitting in it, which is controlling the fuel injection, monitoring the engine RPM, tyre speed, engine temperature and many other parameters. On the other hand it is contrling the amount of fuel to be given, adjusting the appropriate gears and displaying various engine parameters on screen to driver. Think of an industrial automation system, where small robotic arms are being used to assemble the product, all this automatic process is being carried out by microcontrollers. Think of the moving sign-boards on airport terminals, the LEDs in them are being controlled by the microcontroller to display messages. In short there are literally thousands of applications including cell phones, personl and industrial robots, security systems, data logging systems and what not all have microcontroller application. So if you are interested in electronics as a hobby, or as a professional, it is mandatory to know how to use microcontrollers.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 3

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

Starting with PIC Microcontrollers


There are a variety of microcontroller chips available. A large number of manufacturers like, ATMEL, AVR, MOTROLLA, Microchip and many more manufacture these chips. Each manufacturer has his own unique design and architecture. Nevertheless idea is same, but the internal architecture is different, just like Apple and IBM, both are making personal computers, doing similar jobs, yet the programming methodology and structure is different. Same is the case with microcontrollers. Microchip (www.microchip.com) is one of the leading and experienced microcontroller manufacturer. It produces a large number of microcontrollers, all varying in the level of resources available, like amount of RAM, EEPROM and variety of peripheral devices supported. However the programming and architectural structure is similar at all levels. Therefore if you master one MCU the knowledge will be applicable without modification to the next higher MCU. The microcontrollers manufactured by microchip, are named as PIC (I don't know why, microchip never used this for the controllers). This stands for Peripheral Interface Controller. Originally designed to control peripheral devices in a computer, so that the burden of CPU is shared. However now these devices are self sufficient and can work independently without the need of another CPU. PIC microcontrollers are very popular among students and hobbyists because of their easy handling , portability and wealth of peripheral devices built right into the chip, requiring very little supporting hardware. Writing this Document I had to make some assumptions about you, otherwise the number of options would be even larger than it is now. So if you do not match the description below, some information might be irrelevant to you, and some recommendations might not be appropriate. Be your own judge. This page is intended for someone who : Wants to start using PIC microcontrollers but has no prior experience in microcontroller Has more time than money (typical situation for a hobbyist or small-scale professional) Is more interested in experimenting and building proto-

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 ;)

What is in the Name?


A long, long time ago (when computer chips died when a cat came near on a dry day) General Instruments produced a chip called the PIC1650, described as a Programmable Intelligent Computer. This chip is the mother of all PIC chips, functionally close to the current 16C54. It was intended as a peripheral for their CP1600 microprocessor. Maybe that is why most people think PIC stands for Peripheral Interface Controller. As far as I know Microchip has never used PIC as an abbreviation, just as PIC. And recently Microchip has started calling its PICs microcontrollers PICmicro MCU's.

Are You Really Sure ..


But first let's take two steps back. You think you want to start using microcontrollers? I hope you realize what you are up to. It is surprisingly easy to use a microcontroller to perform some nice tricks like flashing a LED, or even controlling a simple robot. But these simple tricks will whet your appetite for more complex applications, and then the big struggle will start. On the hardware side microcontrollers are powerful and complex chips, so you are in to some serious reading, especially of the data sheet of the chip you will be using. I know the 200+ pages of a 16F877 data sheet look intimidating, but you will have to bite that bullet some time. And when you have finished that document there is still the midrange reference manual at almost 700 pages! On the software side things can get quite complex too, especially if you want to do more than one thing at the same time. Programming is difficult, and microcontroller programming (beyond the blink-a-LED level) even more. When all you ever want to do is blink a few LEDs, switch

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 4

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.

So You Have Decided


When you have decided to use a microcontroller the next step is to decide which one. This document is about PICs, but you should at least be aware that other options exist, like the Motorola 68HC, Atmel AVR, and the 8051 in all its varieties from various manufacturers. There are firm proponents of each of these microcontroller families, and probably for good reasons. Asking 'what chip should I choose' on an appropriate internet newsgroup will give you an idea of how religious this issue is to some people. Criteria that you can take into account when choosing a microcontroller (family) are: Availability Price Ease of use (as a start consider only controllers with flash memory that can be (re) programmed in-circuit) Quality and price of development tools Support from friends, neighbors, clubs, newsgroups, mailing lists Availability of application notes, reference designs, hobbyist web pages Features of the chip (IO pins, UART, A/D, D/ A, counters, speed, code size, data size, etc.) Ease of migrating to smaller (cheaper) or larger (more capable) chips

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 5

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

Select a Programming Language


A discussion about choosing a microcontroller might create a lively discussion on the appropriate newsgroups, but the next choice is sure to raise an outright flame war: which programming language should you use? I will not attempt to answer this question for you (the answer depends on too many factors), I will just give some criteria and present some alternatives. Criteria that can be taken into account when choosing a lan-

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 6

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-

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 7

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.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 8

Easy-Pic-1 Training Kit


o far you have learnt the various types of microcontrollers, and how they differ or work. In order to show you how this all works, I have developed a simple and basic PIC training kit. This kit hides from the user all the wiring details, and allows him to experiment with the PIC microcontrollers.

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,

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 9

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.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 10

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.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 11

Testing The Motherboard


Well, so far you have setup the programmer and programming software. Now is the time to have a look at the motherboard, which will run our applications. Motherboard comes pre-tested, for all the host functions. However when shipped the microcontroller is programmed with a small testing program, which will put the binary numbers from 0 to 255 on PORTB, this can be seen by the eight LEDs. Two switches on PORTA are used to increase and decrease the speed of change, with each button press, there will be an audible beep from the PIZO and an increase or decrease in speed depending upon the switch pressed. In addition to that on every number divisible by 50 there will be a beep from the PIZO. This is all the program does. This program does not test the RS232 communication, which we will do later. Now lets have a look at he motherboard. It is preconfigured, just attach a 9V battery, or a 6-9V adapter and turn the power switch on. An LED next to the switch will turn on indicating the power supply. Wrong polarity of battery or adapter will not allow it to pass through and light will not turn on. Once the power is connected, LEDs on PORTB will start turning on and off in a sequence, indicating the binary number. On reaching 50 the PIZO will beep. (In case it is not connected do it on the PIZO header, polarity does not matter). Now press the push switch 1 (SW1) and you will hear an audible beep, release it and you will notice a change in speed, press it a few more times to achieve a higher speed. Now press SW2 this should also produce a beep and decrease the speed of change on LEDs. This shows that all LEDs connected to the PORTB are working OK, PORTB is behaving OK, and Two push switches are giving appropriate signals to the microcontroller, to which it is behaving. The sound system, a PIZO also connected to PORTA is also working well. This shows that the motherboard is OK.

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 Status Indicators


Next have a look at the eight LEDs connected in a row on the board. These LEDs are connected through a current limiting resistors and a DIP switch to the PORTB (which we will talk latter) of the microcontroller. PORTB is a one BYTE port having 8 bits. So one LED is connected to each bit, so that you can see if a bit (and of course the corresponding) pin of microcontroller is on or off. These indicators are there just to see the state of PORTB lines. In actual applications these pins will be then used to control other devices, like infrared red LED, or motor etc. if turning on and off of these LEDs interfere with your application circuit, they can be disconnected from the circuit using the appropriate DIP switches. As shown in the above figure all LEDs have been disconnected.

A Look at The Motherboard


Have a look at the motherboard and get acquainted with various parts. We will refer them time and again in our rest of discussion. Shown below is the power supply section. The

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 12

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.

The Microcontroller Socket


Next have a look at the heart of motherboard, the microcontroller itself. Since microcontroller has to be taken out of the circuit and inserted into the programmer for programming, we have provided a ZIF (Zero Insertion Force) socket. To remove the IC. Lift the release lever and IC will become free, now you can remove it. After insertion, lock the lever down and IC pins will be locked and ready for operation. Before removing or inserting the IC always turn the power off. Next important thing is to insert the IC in correct direction. Note there is a notch (Yellow Arrow) on the IC (Every IC has it) this notch side must be inserted towards lever side of this ZIF. Note the position of PIN-1 (Red Arrow) the PIN numbers are also labeled on the motherboard. Notice the crystal oscillator close to the ZIF socket. This is 20MHZ crystal oscillator and giving the microcontroller control impulses to execute the program. This IC has an internal 4MHZ oscillator as well, if we use that the two pins connected to crystal are then free and available with PORTA. However since we have hard wired the crystal, these two pins are not available on PORTA. 20MHZ gives highest possible speed and accuracy for time critical applications. Moreover this configuration also allows the same board for use with older (now obsolete) PIC 16F84A. A large number of tutorials and designs available on internet use this 16F84 microcontroller.

RS232 Serial Communication


Many device provide an RS232 serial communication system. This is a fairly standard method of communication among devices. Almost all microcontrollers support this standard. Therefore an RS232 communication system has been provided on board, to teach how to send and receive data using this port to other devices. The communication system uses two of the PORTB pins for transmission and receiving, since PORTB is also used for other purposes, if RS232 is interfering with your application, the RS232 can be disconnected from the microcontroller by two jumpers, as shown by Arrow. Usually this is not a problem.

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.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 13

The Push Switches and PIZO


EasyPIC motherboard provides two push switches as digital input, and a PIZO for sound output. These are not as such a special feature of microcontroller, but implemented using software. All PORTB as well as PORTA lines are Bi-Directional. This means we can configure individual lines to be used for input or output. Our PORTA has 5 I/O lines available, RA0 ..

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.

Installing PROTON-BASIC Integrated Development Environment Compiler.


Now when you are aware of your motherboard, and configured the programmer, its time to install the compiler. A large number of programming languages are available, all have merits and de-merits. However for a beginner I prefer a language and development system that should be simple and let the project go in minimal time, as well as hiding complex internal working details of the microcontroller. I therefore recommend the Students Language BASIC. BASIC is a time tested tool for beginners of computer programming. Since microcontrollers are in fact one chip computers I would recommend this language. A number of companies have developed software that support BASIC language commands and syntax and convert the high level, English like instructions into microcontroller understandable machine level instructions. This process of writing instructions in a high level, English like language and then translating them into microcontroller specific instructions is called

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-

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 14

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.

Installing The PROTON-IDE Lite


Proton TDE-Lite is provided on the accompanying CD with this kit. Just locate the software folder and open the Proton folder. There you will find the PDEVLite application. Double click it and the installer will begin. Click on the Install

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-

Limitations of the Lite Version:


The Lite version can program code for only two microcontrollers, PIC 16F628A and PIC 16F877 Since both these microcontrollers are more than enough for beginners, we are happy with this limitation. The program (Basic language) has a limitation of 50 lines of code. This excludes the comment lines and label lines. Although it seems to be a real limitation, but for experimenting and learning this is OK for most projects.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 15

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

Congratulations You Are Done!


Well we are now ready to take off. Our development environment is fully configured and we are ready to write our first test program.

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 16

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 !

The PIC 16F628 Microcontroller


Microcontrollers differ from microprocessors in many respects. A microprocessor is supposed to work in an environment where a number of supporting hardware like RAM, I/ O, Keyboard interrupt controller etc are available. This is a typical scenario of a computer system. On the other hand microcontroller is supposed to be present in a device, designed to do a particular operation. All necessary supporting hardware, must be made available at minimal component cost, as this will increase the size and complexity of devices. Microcontrollers therefore tend to have most of these supporting hardware built into the same chip. These supporting hardware are called peripheral devices, available in a particular microcontroller. This dramatically reduces the number of components required to accomplish a task and therefore reduce the size of device. Secondly and more important thing is that if you master those peripheral devices, you will be familiar with their use, and now its a matter of minutes to design another device, using the same peripherals without relearning them. Thus the more you work on a single microcontroller, more control you get on its peripherals and you can design a wide range of products, using the same components, with little change.

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.

What are the various Peripheral Devices ?


As I have already told you that the particular requirement of a project will dictate what other hardware support is required. However the list is long, and you actually select a particular microcontroller to suit your project according to its requirements. However today's microcontrollers usually offer following peripheral devices into them: UART : Universal asynchronous serial transport : This is used to communicate with other devices, having

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 17

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

Characteristics of PIC 16F628


Lets have an overview of the 16F628 microcontrollers structural organization, as of interest to the software developer and device engineer, as well as an overview of the peripheral devices integrated on the chip.

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,

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 18

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.

A Note About PORTA


PORTA has something different about its behavior. The pins 15 and 16 have functions of RA6 and RA7 as well as OSC1 and OSC2. If your application requires high speed clock oscillation, as in our EasyPIC motherboard, you will have to use an external crystal oscillator to these pins. In that case you can not use these pins as part of PORTA. So RA6 and RA7 are not available if an external oscillator is used. If you need these I/O pins, then you must configure your application to use internal 4MHZ oscillator, then these pins are available as RA6 and RA7. Similarly notice Pin 5. This is connected to RA6 as well as MCLR. MCLR is master clear, which means reset. A 0 on pin 5, if configured as MCLR will reset the microcontroller, without turning power off. And connecting it to +5V using a 10K resistor (logic 1) enables the microcontroller. RA6 is available if pin 5 is not configured to be used as MCLR. In most situations, and in EasyPIC motherboard, pin 5 is tied to +5V using 10K resistor. Therefore this pin can not be used as part of PORTA. PORTA therefore will consist of 5 I/O lines in our EasyPIC development system. RA0 .. RA4. Another point to note about PORTA, is that RA4 is an open collector, which means it is not internally connected via a resistance to +5V. Therefore in order to get logical one on this pin, it must be tied using a 10K resistance to +5V in your projects. This is called a pull up resistor. Since PORTA is by default configured to be used as analog. Since most of our applications use these ports as digital, it is mandatory to configure it as digital before using. don't worry its just one command in PROTON BASIC.

The Timers and Clocks


There are two 16 bit and one 8 bit timers available in 16F628 microcontroller. They have various uses, as we will discuss under appropriate sections.

Pulse Width Modulation Module


We shall talk about pulse width modulation in a separate section. However just for reference I shall talk briefly about this. As you know digital systems only produce logical 1 and 0. In our case 1 is 5V. So if we want to produce a voltage like 3V its difficult, without using resistors. Pulse width modulation is a technique where bursts of signals 1 and 0 of varying width are sent, this effectively reduces the amount of power available, and reduces the amount of power according to duty cycle of pulse. Using this method we can easily control, lets say the speed of a DC motor, or magnetic field strength or illumination of an LED. PWM can be easily implemented by sending impulses through one of the I/O port lines. However when microcontroller is sending PWM signals through our software, it can not do anything else, like writing data on LCD. Alternately if it writes data on LCD, PWM will stop. Luckily availability of PWM module gives us a facility of multitasking. There is a designated pin for PWM, and when PWM module enabled, it will automatically keep on sending the set duty cycle pulses on that pin, and program can continue doing some-

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 19

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.

EEPROM Data Memory


All applications need to store their data, which should be safe on power failure or even reset. Most microcontrollers have some sort of mechanism for that. Microchip microcontrollers have EEPROM. There are two type data memories, one are just EPROM. These memories can be written to, but have to be erased for reuse using special equipment. In contrast EEPROM is electrically erasable memory. EEPROM will retain the information even after power is turned off. Different microcontrollers differ in amount of EEPROM available on chip. 16F628 has 128 Bytes of EEPROM memory available. This seems quite small amount, but remember most devices only need to store very little data here, as we will be talking about it later. If more EEPROM is required you will have to use different microcontroller, or use an external EEPROM IC. Small ICs with huge memory storage, like 64K, 128k or more can be easily used with 16F628 and other PIC microcontrollers. Their use becomes specially important when data logging devices are made. For example if we need to make a device that should record the environment temperature every 4 hours along with some other data for 7 days. After 7 days we would like to see the recorded data for analysis. Such data will be saved in EEPROM. So EEPROM is one of the very useful features available in PIC microcontrollers and have wide usage.

The Flash Program Memory


Everybody is aware of flash drives, compact mass storage devices. These microcontrollers use the same technology to store program. Flash program memory is re-writable, and retains data for considerably long periods of time without power supply. The letter F in 16F628 indicates that it is flash device.

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.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 20

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

resistor, usually a 330 or 680 .


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

C2 22pf R2 330 D1 LED1 S1 R3 10K

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

Using Transistors (Basic Electronics)


There are two types of standard transistors, NPN and PNP, with different circuit symbols. The letters refer to the layers of semiconductor material used to make the transistor. Most transistors used today are NPN because this is the easiest type to make from silicon. We are going to talk about NPN transistors and if you are new to electronics it is best to start by learning how to use these first. The leads are labeled base (B), collector (C) and emitter (E). These terms refer to the internal operation of a transistor but they are not much help in understanding how a transistor is used, so just treat them as labels!

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 21

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.

When to use a Relay


Transistors cannot switch AC or high voltages (such as mains electricity) and they are not usually a good choice for switching large currents (> 5A). In these cases a relay will be needed, but note that a low power transistor may still be needed to switch the current for the relay's coil! Advantages of relays: Relays can switch AC and DC, transistors can only switch

Using a transistor as a switch


When a transistor is used as a switch it must be either OFF or fully ON. In the fully ON state the voltage VCE across the transistor is almost zero and the transistor is said to be saturated because it cannot pass any more collector current Ic. The output device switched by the transistor is usually called the 'load'. The power developed in a switching transistor is very small:

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 22

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

Using a transistor switch with sensors


The circuit diagram shows an LDR (light sensor) connected so that the LED lights when the LDR is in darkness. The variable resistor adjusts the brightness at which the transistor switches on and off. Any general purpose low power transistor can be used in this circuit. The 10k fixed resistor protects the transistor from excessive base current (which will destroy it) when the variable resistor is reduced to zero. To make this circuit switch at a suitable brightness you may need to experiment with different values for the fixed resistor, but it must not be less than 1k. If the transistor is switching a load with a coil, such as a motor or relay, remember to add a protection diode across the load. The switching action can be inverted, so the LED lights when the LDR is brightly lit, by swapping the LDR and variable resistor. In this case the fixed resistor can be omitted because the LDR resistance cannot be reduced to zero. Note that the switching action of this circuit is not particularly good because there will be an intermediate brightness when the transistor will be partly on (not saturated). In this state the transistor is in danger of overheating unless it is switching a small current. There is no problem with the small LED current, but the larger current for a lamp, motor or relay is likely to cause overheating.

A transistor inverter (NOT gate)


Inverters (NOT gates) are available on logic chips but if you only require one inverter it is usually better to use this circuit. The output signal (voltage) is the inverse of the input signal: When the input is high (+Vs) the output is low (0V). When the input is low (0V) the output is high (+Vs). Any general purpose low power NPN transistor can be used. For general use RB = 10k and RC = 1k, then the inverter output can be connected to a device with an input impedance (resistance) of at least 10k such as a logic chip or a 555 timer (trigger and reset inputs). If you are connecting the inverter to a CMOS logic chip input (very high impedance) you can increase RB to 100k and RC to 10k, this will reduce the current used by the inverter.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 23

Writing your First PROTON BASIC Program


So enough has been talked about the PIC 16F628 microcontroller, and some general electronics principles. It was important to know this hardware detail, as without this knowledge, it would be difficult to design new devices. Now we are back to our software development section. We will be writing simple programs, to turn various port pins on and off. I know you can now connect transistors and relays with these pins to get a lot more ! Well when programming microcontrollers, it is important to inform the compiler, what kind of microcontroller you are going to program. This is because there are some internal differences in terms of addresses of registers, and availability of peripheral devices on the chip. The first statement in PROTON BASIC is usually to describe the device. Device=16F628A This statement tells the compiler that we are going to program 16F628A microcontroller. The lite version only supports 16F628A and 16F877 microcontrollers. Next you are going to tell the compiler at what clock speed is this chip hardware running. This means the crystal speed you are using. If you don't mention that a crystal speed of 4 MHZ is assumed. And all timing calculations will be based upon that figure. A wrongly selected clock frequency will result in wrongly calculated time delays. The lite version supports only 10 and 20 MHZ crystal frequencies. Since our EasyPIC uses 20 MHZ crystal our next instruction would be: XTAL=20 Now as I already sated that PORTA pins are by default configured to be used as Analog, if we want to use PORTA switches etc, or otherwise for any other digital input or output, we have to declare it as digital. ALL_DIGITAL=true This statement does the internal register settings to set all I/O lines to be digital. When you are developing advanced applications, you would like to set individual pins as digital or analog, this will be accomplished directly by manipulating the appropriate register bits. For now we are going to talk about all digital. Output PORTB

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.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 24

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-

Testing the Switch on EasyPIC Board.


As we know two push switches are present on the motherboard. They are connected to PORTA.2 and PORTA.3 (or RA2 and RA3). The respective pins are normally set to high (logical 1) when the switch is pressed it gives logical 0 on the pin. Or puts it in low state. Lets write a program that will

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 25

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-

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 26

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.

Variables and Data Types


Those of you who already have been into programming must know the variables. Variables are identifiers which can hold some value, that can be changed programmatically. When required the variable can be accessed and its value used in calculations or output of data. The PIC microcontroller 16F628 has 8bit memory architecture for holding data. Any variable which can hold 8 bits of data will be called byte size variable, and its value will range from 0 to 255. Other variable types like integers, long integers and floating point variables are all managed basically by the software, or the programming compiler. Therefore actual data types available to you will vary with the type of compiler you are using. More advanced compiler, better data types it supports. PROTON Basic supports all major data types like, bit, byte, word, DWORD, Float and string. All these data types are handled by the compiler, and not a property of microcontroller. Now lets use a variable to hold the value of a number and display the value on LEDs using PORTB. Device=16F628A XTAL=20 ALL_DIGITAL=true

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 27

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.

readable in dark as well.

Using EasyPIC Character Display board.


The EasyPIC motherboard does not have onboard LCD display. This display is rather available as a separate board. Connecting and using this board is fairly easy with EasyPIC, and PROTON BASIC. All connections have been set according to the default settings of PROTON compiler. However almost every compiler, may it be C, or some other form of BASIC which supports an LCD library, allows configuration, so that you can define which pins of microcontroller will be connected to the LCD pins. For now lets write a simple program to Display a hello message on LCD. Connect the LCD board to the motherboard, using the supplied cable. Use PORTB of motherboard. Remember to connect the connectors in correct orientation. You don't need separate power supply as LCD will obtain power from the motherboard using on port supply. LCD require considerable amount of power. Sometimes if you are using battery, it does not have enough amperage to supply the LCD and the circuit simply fails to work. So make sure you are giving an appropriate source of power. I prefer using 6-9V wall adapter, that works fine. Now enter the following program and here we go! Device= 16F628A XTAL=20 ALL_DIGITAL=true Cls Print At 1,1,"Welcome" Print At 2,1,"Microelectronics" End That is it. All technical details have been taken up by the good compiler. The CLS command clears the display. And print command simply prints text on the LCD. You can use print to display variables in various formats as well as con-

Using LCD to Display Data


It is common for microcontrollers to interact with user. This interaction depends upon an input from the user, which is usually in the form of a button press. The microcontroller inturn responds by switching on or off some LEDs, or producing sound. Sometimes however the data to be presented is complex, like numbers, text or some symbols etc, which require a more complex display system. For these purposes LCDs (Liquid crystal display) are the most commonly used devices. LCDs come in a variety of formats and structures, however most of them share a standard protocol. We shall talk about the technical details of using LCD is some other section. However it is relevant to talk little about how to use them. There are two types of LCDs which are commonly used. Alphanumeric or Character LCD Graphic LCD

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 28

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 29

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.

Using UART Serial Communication


Serial communication is a fairly convenient and standard method of communication among the devices. Serial communication has a special format of its own. It can be implemented trough two I/O lines of a microcontroller. Just any two lines can work, but this will require all communication to be handled by the software. This is quite an overhead on the microcontroller. Some microcontrollers like 16F628 provide an on-chip UART communication hardware, this relieves the microcontroller from lots of overhead and the communication is all handled by the on-chip UART hardware. PROTON BASIC provides commands for both type of communication. Our EasyPIC board uses hardware UART facility on 16F628. if you look at the pin configuration of the microcontroller you will notice that, pin 7 and 8 are labeled as RX and TX as well. RX is for receiving and TX for transmitting the serial data. These two pins will be connected to the hardware UART system, when appropriate registers have been set. Note when these pins have been configured as RX/ TX they can not reflect the status of PORTB.1 and PORTB.2. since portb.2 is used by our LCD system, we can not use both at the same time. Most convenient device to communicate with through serial port is your personal computer. The same port through which you are programming, can be used to communicate with microcontroller to exchange information. There are two types of serial communication, Synchronous and Asynchronous. Synchronous communication is timed by a clock signal, whereas asynchronous system keeps on transmitting without acknowledgment that the other system is receiving or not. UART is of asynchronous type. To enable serial communication with your PC, you will have to unplug the serial cable from programmer (after programming) and connect to the serial connector on motherboard. You will then need a serial terminator program which should monitor all serial communication. Windows has HyperTerminal, located in Programs > Accessories > Communication, or you can use a plug-in provided with PROTON compiler, we shall be using the later. Device 16F628A

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 30

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 31

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 32

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 33

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.

Timers, Counters and Interrupts


Well these are little advanced topics, and will not be covered fully in this beginners manual. However just to give you an idea, what they are and how to use them, I will try to give an outline. Every microcontroller gives these facilities to some extent. PIC16F628 has three timers namely Timer0, Timer1 and Timer2. Timer0, has 8 bits of storage, whereas Timer1 and two are 16 bits. All three of them can be configured as counters, or as timers. The only difference in timer and counter is the source of impulse. When it is configured as timer, the impulse is taken from the PIC clock, the same clock signals which are driving the program. May it be a crystal oscillator, or internal 4 MHZ oscillator, it will take impulse from it. On every impulse it will advance the timer by one. When it is configured as Counter, there are two external inputs TOCK1 and TOCK2 (see pin labels). The counter will advance when ever an impulse is received on these pins. In that case it is counting the impulses. The number in timer0 can be read using TMR0 register. You can also write any value to this register, like 0 to reset it. For example you can count the number of impulses in one second to read the frequency of a signal. Timer1 and 2 are 16 bit numbers and can be read using TMR1H and TMR1L registers. H is highest 8 bits and L are lower 8 bits.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 34

Controlling External Devices


Well so far you have learnt how we can control the various I/ O lines of the microcontroller. Using these I/O lines its easy to control relays, or transistors to turn various devices on and off. However a large number of devices, including sensors are manufactured by many companies, they can be controlled using our microcontroller. In order to do that you have to understand the controlling requirements of the device. For example if you want to control your television using remote control codes. You can make an application, connected to an infrared LED, and give it appropriate impulses to transmit data. Now the word Appropriate is important. You have to send the data in a format your TV understands.

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.

How we can Increase or Decrease the Voltage using Digital Logic?


As I already said you can control the speed of DC motor, by increasing or decreasing the voltage. However in digital systems, the circuit is either on or off. When on it will be giving 5V and when 0ff giving 0V. Using transistors you can change the top voltage, like 12V, but can only turn transistor on or off! So how we can control the speed? The answer lies in Pulse Width Modulation (PWM). This is a very commonly used technique in electronics. In pulse width modulation you give pulses of 1-0 the duration of 1 and 0 (ratio) will determine the amount of energy, motor will get, and therefore its speed. The amount of time our signals will spend in logical 1 during the cycle is called duty cycle. A duty cycle of 100% means the system is on all the time, so full energy will reach the motor and it will run at its top speed. A 75% duty cycle, will giving signals of lets say 1 KHZ in such a say that for 75% of time the line is in logical 1 and 25% of time its logical 0 so motor will receive less energy and will run slow. Fortunately PWM is easily implemented using PROTON BASIC as well as our 16F628 microcontroller.

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 35

First Experiment with Stepper Motor


Here is the schematic of our first test circuit. The PIC's output lines are first buffered by a 4050 hex buffer chip, and are then connected to an NPN transistor. This step is however not necessary, and you can use some general purpose transis-

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----

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 36

The 5 x 7 Display Device


We have included with EasyPIC a device which uses 5 x 7 LED matrix display. This device has been included for two reasons. 1: whatever we are going to implement with this, is not as such a feature of microcontroller, and we want to teach you, if you get a third party device, how you can make your own controller for this device. 2: 5 x 7 displays are very commonly used in industry, as well as many devices like elevators to display numbers, text, animations etc. it will be great to program this device and teach you a lot of programming skills. If you understand that, you can very easily make message boards like the ones on airports to display the messages. In other words this project is going to open a whole new world of applications of microcontroller. 5 x 7 matrix display contains a commonly available, matrix of LEDs this matrix contains LEDs connected in the form of a matrix. As you can see it has 7 rows and 5 columns. The LEDs are connected in such a way that each row has common anode of LEDs connected, and the common cathode of each column is also connected. The LED matrix therefore has 7 pins of each row, and 5 pins for each column. Giving a positive supply to a row and a negative supply to a column, will turn a single LED on, which is at the intersection of Row and Column. So we can say we have an x,y grid, and only the LED whose x,y are mentioned will turn on. In this way we can control all the individual LEDs (5 x 7=35 ) with only (7+5=12) lines. The control is however tricky and that is what you are going to enjoy in the rest of this section. We have connected the display in such a way that the rows are selected by the PORTB of microcontroller. We are using PORTB.0 to PORTB.6 (PORTB.7 is additionally used for sound on this device) the columns are selected by giving

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.

What are we going to Achieve with this?


Before actually learning, lets have a look, what are we going to have. This will energize your morals and spirits. Sit back and take a big breath. You are about to take part in one of the best microcomputer (microprocessor) projects you have seen. It uses a PIC16F628 micro and you will be shown how to program the chip to create quite amazing effects. It's a simple project and you will be starting at the beginning of programming, so don't worry if you have never worked with a microprocessor before. The project consists of 35 LEDs arranged as a 5x7 matrix.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 37

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.

Blink The LED


Now try this program, its simply a blinking PORTB.0 now since PORTB is connected to our 5 x 7 matrix board, it is also blinking the Row 0, col 0. 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 col 0 Set Reset Clear Reset PORTB=0 AA: Toggle PORTB.0 DelayMS 500 GoTo AA End

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 38

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

PORTA.0 PORTA.1 impulse, this will select

Increasing the scan speed


Now try increasing the scan speed, step by step try following Delay settings. DelayMS DelayMS DelayMS DelayMS DelayMS DelayMS DelayMS DelayMS DelayMS 500 250 125 60 25 12 6 2 1

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 39

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.

Running The Message (Horizontal scroll)


You must have seen the horizontally scrolling sign boards. The basic idea is to shift the columns to left one by one, and keep on refreshing the display. Have a look at 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[6] As Byte ' Making an array to hold bit pattern Dim i As Byte Dim j As Word

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

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 40

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.

Using 7 Segment Displays


Seven segment displays are frequently used to display numeric data. Applications where only numeric data is to be displayed, may not require an expensive 16 x 2 LCD character display. Seven segment displays come in two varieties, common anode and common cathode. Moreover using single display or multiple digits, as in the above picture, requires a lot of pins to feed data. Every digit requires 7 lines for individual segments, and 1 for decimal point if required. If more digits are required, lets say we want 4 digits it will require 32 lines. I/O lines on microcontrollers are limited and have other functions as well. It is therefore mandatory to use the multiplexed displays. In multiplexed displays, all seven seg-

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 41

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.

Using Infra-Red Transmitters and Sensors.


Very frequently devices communicate using infra-red system. Infra-red (IR) consists of an IR transmitter and an IR receiver. There is a simple way of connecting the receiver and transmitter. However the IR receiver may get a signal due to surrounding heat (heat is infra red). In communication systems it is therefore customary to modulate the IR signals at 38KHZ. This circuit shows an IR system, in consists of a transmitter comprising of a transmitter connected to RB1. giving a 38KHZ impulse at RB1 will transmit infra red signal. The receiver is connected to RB2. This module will automatically

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 42

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.

Attaching other input devices


There are a number of sources which can act as input to the microcontroller, like temperature sensors, light sensors, pressure sensors etc. to implement these sensors use following guidelines. Inputs to a PIC have the same 5V logic requirements, and just as outputs can be 'sink' or 'source', so the inputs can be active 'high' or active 'low'. Basically this is just a variation Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 43

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.

How to read the Keypad in PROTON BASIC?


This is extremely easy, there is a command called Inkey. This command scans the keypad and returns the value in a variable. DIM VAR1 as BYTE VAR1 = INKEY ' Scan the keypad DELAYMS 50 ' Debounce by waiting 50ms Now the var1 will contain the number of key pressed. INKEY will return a value between 0 and 16. If no key is pressed, the value returned is 16. Using a LOOKUP command, the returned values can be re-arranged to correspond with the legends printed on the keypad: The Lookup command has following Syntax: Var1 = LOOKUP index, [10,20,30,50] Where index is the position you are looking for and numbers in brackets are the values returned. So if index =0 it will return 10 and if index is 1 it will return 20 and so on. X=inkey Y=LookUp x, [1,4,7,*,2,5,8,0,3,6,9,#]

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

Easy-PIC-1: Teach yourself Microcontrollers: Development Kit / 44

Making a Combination Lock


Here is a schematic diagram of a combination lock, which can be used with keypad, and DC powered lock. The sche-

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.

Where to find more projects


Internet is literally full of help. It contains hundreds of projects, and programming tips. So just do a Google search, or visit Piclist.com or better join a web ring for pic micros. People are really helpful out there.

Microelectronics Pakistan : www.electronicspk.com | info@electronicspk.com

You might also like