99929710 Beginnig PIC Programming

download 99929710 Beginnig PIC Programming

of 252

Transcript of 99929710 Beginnig PIC Programming

  • Learn By Doing: Less Theory More Practical

    Microtronics Pakistan Invent Future

    Lets Begin Microcontroller Programming

    Using PIC Microcontrollers

    Amer Iqbal Qureshi

    Microtronics Pakistan www.electronicspk.com

  • Preface

    L earning electronics has been my passion ever since I was i high school. It was always a fun seeing my project coming to life. Only a passionate hob-byist can appreciate the feeling, jubilation and sense of pride one feels when the LEDs turn ON. A wonderful sight nothing is comparable with the first glow of LEDs. Things kept on progressing, early experiments turned into more complex and more complicated ones, but one thing remains the same Yes its working man !.

    Professionally I am cardiac surgeon and an electronics hobbyist. Therefore I am fully aware of the needs of a hobbyist. Most hobbyists are not technically sound people. They just love doing electronics. They have expertise in their own fields, but a passion to see electronics work. This book has been written therefore from this point of view. It will concentrate more on practical things than going into theoretical details. However I feel one should know what's happening behind the scenes. So a reasonable time will also be spent on understanding basic theory as well.

    Although this book is about learning microcontroller programming , and not about electronics, yet I feel it would be nice to have an overview of little electronics as related to microcontrollers projects as well. Pro-gramming a microcontroller is not much difficult job. However getting a project work is somewhat labori-ous. Therefore one needs to know and learn little bit of electronics as well.

    My passion has always been to help others learn whatever Allah has blessed me with. A number of texts exist for experienced and professional people, yet I Always think there is a need for absolute beginner. Its the beginning that is most difficult. Thats why cars have maximum engine resources available in first gear when it has to take a start. Once things start rolling pervious experiences tend to facilitate more learning.

    As a hobbyist I would say, I have learnt maximum by doing wrongs. So do not worry if the project is not working, its blessing indeed, that nature wants you to try 100 different things that you would normally ig-nore. The key to learning is Persistence.

    So I conclude here with the pray to Almighty Allah, that please help me transfer whatever I have to those who have the desire to learn (Amin).

    Dr. Amer Iqbal

    [email protected]

    www.electronicspk.com

  • Table of Contents Introduction to Microcontrollers and Control Systems 4

    Microchip PIC Microcontrollers 8

    Setup Your Personal Workbench 11

    A Brief Tour of MikroBasic 16

    MikroBasic Programming Language 26

    Hello World 32

    Understanding I-O Ports and Special Function Registers 38

    Control Structures Loops and Decisions 42

    Connecting Output and Input Devices

    50

    Using Push Switches 57

    Character LCD Display 63

    Seven Segment LED Display 77

    USART Universal Asynchronous Receiver and Transmitter

    84

    Dealing With Analog Data 99

    Graphic LCD and Touch Screen 112

    Using Numeric Keypad 119

    Producing Sound 129

    Pulse Width Modulation 133

    I2C Communication EEPROM 144

    I2C Communication DS1307 Real Time Clock 152

    Interrupts and Timers 158

    Motor Control, DC Motor, Stepper and Servo 170

    LED Matrix Displays 190

    Infra Red Communication and Remote Controls 195

    SPI - Serial Parallel Interface 211

    RS485 Long Range Serial Communication 218

    Dallas One Wire Protocol 230

    USB - Universal Serial Bus 244

  • E ver since man has started interacting with his environment there has been one goal Control. Its been the basic nature of man to control his environment, things around him and even nature. By control he means getting something useful out of what was not useful to him. This very nature persists and is the basis of development. All research may it be biological, physical or chemical is to know the vary na-ture of things and then to find ways to control it.

    By definition control means we should be able to command it. The very particular thing should respond to our requirements. When talking about microcontrollers the same philosophy applies. We want to control the flow of electron, a very sim-ple desire. Our scientists and engineers designed electronics components like resistors, conductors, transistors and so on to make this happen. It has been customary to make devices us-ing these discreet components. However the demand to con-trol went on increasing and when logic got involved designing a control system just by discreet components became really difficult. It was here that the need of a microcontroller felt.

    In fact before the advent of microcontroller, computer in some form was already invented. So there was already a system to solve the problems using a set of instructions, a program. The control systems were separate entity used mainly in industry where mechanical jobs were to be controlled, like automatically packing the products, monitoring the tension of a thread in textile etc. The merger of computer and these control systems resulted in what we today know as micro-controller.

    So microcontroller in fact is a complete computer along with various other devices necessary for a control system integrated on the same chip. Microcontrollers are used in automatically controlled products and de-vices, such as automobile engine control systems, implantable medical devices, remote controls, office ma-chines, appliances, power tools, and toys. By reducing the size and cost compared to a design that uses a separate microprocessor, memory, and input/output devices, microcontrollers make it economical to digi-tally control even more devices and processes.

    What is the difference between a microprocessor and a microcontroller?

    Well this is an important question that needs to be answered in the beginning. Truly speaking both can be considered almost same. However there are slight differences in philosophy. A microprocessor has a central processing unit (CPU) and a system to connect this CPU to the outside world. In order for this CPU to work it needs a program. This program must be stored somewhere. Usually it is loaded from an external storage medium into an electronic memory. The microprocessor system must have an external memory where not only program can be stored, but also intermediate results of processing be stored. The microprocessor also needs to have a system of devices that are responsible for getting data from outside world and present data from processor to outside world. This kind of arrangement makes the system highly flexible and adaptable. Just consider your personal computer. You have the choice to configure it in a number of ways. You can add more memory, change hard disk type, have a CD or DVD ROM, many different types of input devices and so on. You also have the liberty to run a variety of programs at your will. At one time you are listening to music and at other time working with your spreadsheet. So microprocessors are used where you want flexibility and freedom.

    Microcontrollers on the other-hand are designed to work in a very narrow spectrum of job. Once pro-

    1 Introduction to Microcontrollers

  • grammed for a particular job, it is not supposed to do another in a given scenario. Thus a microcontroller needs to have a precisely defined job. Second objective of microcontroller usage was to reduce the external circuitry. It was therefore decided that everything that is required to make a microcontroller work should be integrated within the same integrated circuit. The microcontroller therefore has a CPU, program memory, working memory, extra storage memory etc. In addition to that the other commonly required features or modules like Analog to digital conversion, serial communication, timers etc are also built into the same chip. Microcontroller therefore is a complete computer in itself. Although not as robust as your PC, but still its complete. Many a times these microcontrollers are also called One-Chip-Computers. Although you can say to some extent that we can program a microcontroller to do any job, like driving an LCD display, con-trolling a motor, sensing a temperature sensor and so on, why cant we call it a general purpose small scaled computer?

    Yes you are right, you can make this tiny computer do a lot many functions and some times all together. Like you can setup a system where temperature is sensed, displayed on an LCD display and turns a fan ON or OFF based upon set temperature. Precisely speaking when we say microcontrollers are not general pur-pose, we mean, when a particular hardware is designed, lets say the above example, and a microcontroller has been appropriately programmed to handle the job. Now that particular controller is going to stay there and function like that only. No body would love to program the same programmer to transmit the data on serial port, as the particular hardware has no serial connection.

    So hardware design and microcontroller program are made for each other. The hardware is designed ac-cording to a particular microcontroller in mind, and microcontroller is programmed to control the particular hardware.

    Why are there so many different kinds of microcontrollers?

    Yes this is most relevant question that can and should arise in your mind. Truly speaking there is not much difference. I frequently quote an example of cars. You may phrase the same question, as "Why are there so many different kinds of cars, or automobiles?" Try to answer this question yourself, or ask your friend. The an-swer you get is 100% true and applicable to microcontrollers.

    Just like there are many different manufacturers of cars, they have different internal architectures, and core engine issues, but all have same basic structure. After-all they are all run on gasoline. Still they have something their own. But a few things are always same. they all have similar gearing system, similar ignition system, simi-lar steering wheel, accelerator and brakes paddle and they function exactly the same way. From a users perspective there is not much difference. Thus if you ignore what's inside and learn to drive a Mercedes there are bright chances you will be able to drive a Toyota with same confidence. Except for small differences like position of radio, the look and feel of your dash-board every-thing is same.

    Same is the case with microcontrollers. There are a number of manufacturers, ATMEL and Microchip for example. If you have the core idea of one you can easily switch to another, believe me its that easy. So its decided that for our purposes we do not need to get our lives complicated by the issue where to start? They are all same, with slight differences in flavor.

    Why are there so many different microcontrollers even from the same manufacturer?

    Humm, well again a very logical query. If the microntrollers differ among manufacturers do they also differ if from same manufacturer? Again to solve this question lets frame it around our automobiles example. Toyota for example manufactures automobiles from small 'student cars' to huge trucks. All having same architectural plan, but designed from different usage perspective. Student car has smaller engine, low lux-ury but cost effective. Family cars are more capacious slightly more powerful engine, have bigger trunk, and lots of luxuries like air conditioning, music system etc. The truck needs engine power, hydraulic system for unloading loads but no luxury at all.

    Same is true about microcontrollers from the same manufacturer. Since a microcontroller is going to be

  • used for a specific job when the project is finalized. It may or may not need every possible facility. The manufacturers therefore make these various devices to help you select the one that best suits your require-ments. Conceptually and from the using point of view they are almost same. In a hierarchy the controllers with low pin count and smaller number of resources are compatible with higher processors. Thus if you experiment a prototype with a reasonably powerful processor, and your project is only using a few LED indicators and a serial communication. The final device will use a controller with low pin counts and smaller number of peripherals. The programming technique and commands will almost remain same.

    I hope I made my point clear. If you learn one microcontroller, switching to another from same manufac-turer involves only very small re-learning. You need to learn only the modules that are different. A USART (serial module) in 14 pin microcontroller is same as in 40 pin bigger controller. Another major difference is in the amount of memory available. so when your project is finalized on a prototype you can inspect your final program and decide which particular microcontroller from this family will be best suited. There are usually two criteria to affect this decision, 1: Price 2: Size both of these affect the final commercial product. If this is not the issue you can continue with whatever is available.

    Is it Possible to have more than one microcontrollers in a project? Absolutely yes. Indeed complex projects have various modules, and each module having its own microcon-troller. In order to create harmony among these modules the modules are connected with each other as well so that microcontrollers communicate among themselves as well. An example is an automatic car. Modern automatic cars have about 40 microcontrollers in it. Some for engine, some for breaks other for windows etc.

    Lets re-cap what we have learned for about microcontroller.

    1. It is an integrated circuit (IC) that is available in various sizes and packages 2. It is programmable, without a program it has no function assigned to it

    3. It has various modules integrated into it, the type and number varies with the microcontroller type

    4. Most of the processes are either same or similar, so if you master one microcontroller its easy to switch

    5. Microcontrollers are able to control other devices through logical signals, but do not have enough power to drive them directly. They are controllers not drivers.

    6. In a given application the microcontroller will continue to work on a pre-defined path and they are not meant to be programmed to perform a large variety of tasks

    7. Many circuits can still be made using specialized discreet ICs, however using microcontroller instead would greatly reduce the component count, and made it extremely easy to change design.

    A brief history, how microcontrollers were developed.

    In the year 1969, a team of Japanese engineers from BUSICOM com-pany came to the USA with a request that a few integrated circuits for calculators were to be designed according to their projects. The request was set to INTEL company , Marcian Hoff was in charge of the pro-ject there. Since having been experienced in working with a computer PDP8, he came to an idea to suggest fundamentally different solution instead of the suggested design. That solution presumed that the opera-tion of integrated circuit was to be determined by the program stored in the circuit itself. It meant that configuration would be simpler, but it would require far more memory than the project proposed by Japanese engineers.

    After a while, even though the Japanese engineers were trying to find an easier solution, Marcians idea won and the first microprocessor was born. A major help with turning an idea into a ready-to-use prod-

  • uct, Intel got from Federico Faggin. Nine months after his arrival to Intel he succeeded in developing such a product from its origi-nal concept. In 1971 Intel obtained the right to sell this integrated circuit. Before that Intel bought the license from BUSICOM company which had no idea what a treasure it had. During that year, a microprocessor called the 4004 appeared on the market. That was the first 4-bit microprocessor with the speed of 6000 operations per second. Not long after that, American company CTC requested from Intel and Texas Instruments to manufacture 8-bit microprocessor to be applied in terminals. Even though CTC gave up this project at last, Intel and Texas Instruments kept working on the microprocessor and in April 1972 the first 8-bit microprocessor called the 8008 appeared on the market. It was able to address 16Kb of memory, had 45 instructions and the speed of 300,000 operations per second. That microprocessor was the predecessor of all todays microprocessors. Intel kept on developing it and in April 1974 it launched 8-bit processor called the 8080. It was able to address 64Kb of memory, had 75 instructions and initial price was $360. In another American company called Motorola, they quickly realized what was going on, so they launched 8-bit microprocessor 6800. Chief constructor was Chuck Peddle. Apart from the processor itself, Motorola was the first company that also manufactured other peripherals such as 6820 and 6850. At that time many companies recognized greater importance of microprocessors and began their own development. Chuck Peddle left Motorola to join MOS Technology and kept working intensively on developing microproces-sors.

    At the WESCON exhibition in the USA in 1975, a crucial event in the history of the microprocessors took place. MOS Technology announced that it was selling processors 6501 and 6502 at $25 each, which inter-ested customers could purchase immediately. That was such sensation that many thought it was a kind of fraud, considering that competing companies were selling the 8080 and 6800 at $179 each. On the first day of exhibit, in response to the competitor, both Motorola and Intel cut the prices of their microprocessors to $69.95. Motorola accused MOS Technology and Chuck Peddle of plagiarizing the protected 6800. Because of that, MOS Technology gave up further manufacture of the 6501, but kept manufacturing the 6502. It was 8-bit microprocessor with 56 instructions and ability to directly address 64Kb of memory. Due to low price, 6502 became very popular so it was installed into computers such as KIM-1, Apple I, Apple II, Atari, Com-modore, Acorn, Oric, Galeb, Orao, Ultra and many others. Soon appeared several companies manufacturing the 6502 (Rockwell, Sznertek, GTE, NCR, Ricoh, Commodore took over MOS Technology). In the year of its prosperity 1982, this processor was being sold at a rate of 15 million processors per year!

    Other companies did not want to give up either. Frederico Faggin left Intel and started his own company Zilog Inc. In 1976 Zilog announced the Z80. When designing this microprocessor Faggin made the crucial decision. Having been familiar with the fact that for 8080 had already been developed he realized that many would remain loyal to that processor because of great expenditure which rewriting of all the programs would result in. Accordingly he decided that a new processor had to be compatible with the 8080, i.e. it had to be able to perform all the programs written for the 8080. Apart from that, many other features have been added so that the Z80 was the most powerful microprocessor at that time. It was able to directly address 64Kb of memory, had 176 instructions, a large number of registers, built in option for refreshing dynamic RAM memory, single power supply, greater operating speed etc. The Z80 was a great success and every-body replaced the 8080 by the Z80. Certainly the Z80 was commercially the most successful 8-bit micro-processor at that time. Besides Zilog, other new manufacturers such as Mostek, NEC, SHARP and SGS appeared soon. The Z80 was the heart of many computers such as: Spectrum, Partner, TRS703, Z-3 and Galaxy.

    In 1976 Intel came up with an upgraded version of 8-bit microprocessor called the 8085. However, the Z80 was so much better that Intel lost the battle. Even though a few more microprocessors appeared later on the market (6809, 2650, SC/MP etc.), everything was actually decided. There were no such great improvements which could make manufacturers to change their mind, so the 6502 and Z80 along with the 6800 remained chief representatives of the 8-bit microprocessors of that time.

  • A mong a large number of companies manufacturing microcon-trollers Microchip is relatively young, yet proven its worth. Although microcontrollers were being developed since early 1970s real boom came in mid 1990s. A company named Microchip made its first simple microcontroller, which they called PIC. Originally this was de-veloped as a supporting device for PDP computers to control its periph-eral devices, and therefore named as PIC, Peripheral Interface Controller. Thus all the chips developed by Microchip have been named as a class by themselves and called PIC.

    A large number of microcontroller designs are available from microchip. Depending upon the architecture, memory layout and processing power. They have been classified as low, mid and high range microcontrol-lers.

    The beauty of these devices is their easy availability, low cost and easy programming and handling. This has made PIC microcontrollers as the apple of hobbyists and students eyes. We shall be talking about mid-range PIC microcontrollers, and use PIC18F452 as a prototype in this book to explore them. Knowledge gained by learning and exploring one microcontroller is almost 90% applicable on other microcontrollers of the same family. The only difference is in availability of resources on different chips. We shall shift to other microcontrollers where a particular feature is required like USB devices.

    General Layout of PIC Microcontrollers When we talk about discreet components it is cus-tomary to talk about the pin numbers. Most of you who have experienced working with various inte-grated circuits know that most schematics show connection details in terms of pin number of an IC. That is also true to some extent when we talk about microcontrollers. However it is more customary to talk about Pin-Names instead of numbers. Since the names tend to remain the same in many different microcontrollers from the same manufacturer it be-comes extremely easy to adapt from one controller to another.

    Functional Compatibility As you can see the pins shown here have various symbols assigned to them, separated by /. These abbre-viations are pin names and correspond to the specific function of the module inside to which they are at-tached. Note each pin has multiple associations, like pin 26 is RC7/RX/DT. It means the pin can assume three different types of functions. However at any given time, or in any given project the pin is set to as-sume any one of them. This is simply done during programming by setting various special function regis-ters. Generally speaking when we talk about a pin in PIC we use its common name, and that is the one which is written first for example RB0, RB1, RC6 etc. Another beautiful thing about this naming conven-tion is that since most microcontrollers from PIC share similar modules, so they tend to have almost same names. The exact pin number might be different, but functionally they tend to behave same. As an example look at the pin-outs of an 18 pin PIC microcontroller. You can see this microntrollers has RB0 to RB7 pins, which are similar to those in 18F452. however pin numbers are different.

    2 Microchip PIC Microcontrollers

  • Therefore when making a project the discussion says you have to connect an LED to RB4. This should mean pin 10 in case of 16F84 and pin 37 in case of 18F452. Functionally both will be same. Note simpler design of 16F84, as most of pins have sin-gle function. This means this microcontroller does not have many modules inside.

    Since functions tend to repeat in all processors from Micro-chip. Learning them facilitates working with higher processors. In next higher processor you have to learn only whats new.

    Pin Compatibility As far as pin counts of microcontroller is concerned you will find many different models with same pin counts. For example 16F84 is an 18 pin PIC mi-crocontroller, so is 16F628A and 16F819 and many others too. Being different processors they definitely have differences in the available mem-ory, additional storage and number and type of peripheral device modules like Timers etc. a look at their Pin arrangement will reveal that the pins with same names are located in same position. Such microcontroller are therefore called pin-compatible. You can easily replace one for an-other in the same hardware, without any connection changes and enjoy the powers of a better processor if required. For example you started a project and designed the hardware, for 16F84 microcontroller with 1K program memory. Initially the project went smoothly, but as it grew in complexity the 1K memory was not sufficient. So you can replace it with 16F628A having 2K memory and same pin layout. Of-course you will need to recompile the code for 16F628A but the beauty is you do not need to modify the hardware.

    How PIC Microcontrollers are Numbered (Named). This is interesting to note that all microcontrollers from Microchip have PIC as part of their name. the next 2 digits indicate the family or series. We shall talk about this later. Then comes the letter F. This stands for Flash. An F indicates that this microcontroller has flash memory and it can be erased and re-programmed many thousand times. The other types have C in this location. These microcontrollers are one-time programmable. Next two or three digits are the model number. Sometimes the have a post-fix of letter A like 16F628A the models with A postfix are revised versions and are preferred over their non-A versions.

    Microcontroller Instruction Set You will come across various computer and electronics geeks talking about instruction sets and speaking a lot of unfamiliar words. Do not be confused and disappointed on hearing those. Truly speaking every mi-croprocessor has a core language called Assembly Language. Microprocessor understands only numbers, and various basic actins like transferring a byte from one memory location to another, adding two integer numbers or comparing two memory locations. These commands are called the basic instruction set of a mi-crocontroller. Having more possible commands means more liberty to play with, but this also increases the complexity of processor itself. The instruction set of Microchip PIC microcontrollers varies from 35 in-structions for low end controllers to over 80 instructions for high end controllers.

    Do we really Need to Know These Commands? I would say No and yes. As a beginner and hobbyist you will almost never need to talk to the microcontrol-ler in these commands. It will be your compiler that will do this job. So you will need to know the com-mands your compiler gives, and do not need to worry about these low level, controller commands. However when you progress and become a professional a knowledge of these underlying commands is helpful. Occa-sionally you may need to bypass the compiler generated instructions and write a part of your application in assembly to give more speed.

  • What are RISC Computers. RISC stands for Reduced Instruction Set Computers. Although having more instructions in the core instruc-tion set gives more liberty and power, yet it also complicates the controller architecture. It was observed that many of the instructions available in the instruction set are not very frequently used, and their function can be achieved by a combination of other instructions. For example consider multiplication. Multiplying a number by say 40 can be achieved by adding the same number to itself 40 times. Thus eliminating need for multiplication instruction and reducing controller complexity.

    More and more processors were then developed using this philosophy to reduce the instruction set and therefore reduce the complexity of processor. This has resulted in rather more efficient, faster and economi-cally cheaper processing power.

    This became more relevant to microcontrollers where it was supposed to look-after simple tasks and did not require very powerful instruction set.

    PIC Microcontroller Families Microchip manufactures microcontrollers for a wide spectrum of applications. There are controllers requir-ing very little processing powers, then there are mid-range processors and finally digital signal processing controllers for processor intensive applications. As already said all have similar plans, and know one family facilitates a project with another family. Although you have to see the microchip site and study appropriate data sheets, a rule of thumb is that PIC 12FXXX series are low end controllers, 16FXXX are Mid range with 14 bit program memory, and 18FXXX High end with 16 bit memory. 24FXXX and 32FXXX are 24 bit and 32 bit processors for proces-sor intensive functions.

    For beginners I would suggest start with 16F628A and progress to 18F452. The figure below shows the hierarchy of various PIC families.

  • N ow that you have a basic understanding, although a lot remains to be said about PIC microcontroller, I think it would be wise to discuss all those things where they are addressed or used. I per-sonally believe there is only way of perfect learning and that is Learn By Doing. There is not alternate to this statement, rather I shall ex-tend it by Do It Yourself . Therefore if you are really interested in learning these beasts, roll your sleeves and setup your own workbench. Most hobby-ists and students have already a place in home, where they can spend hours and hours with their gadgets. In this section we shall talk about the basic setup that you must have. Its not hard and fast rule to have everything as I mention, you can modify your working environment as well as gadgets to suit your needs. I would recommend you to go through a very nice text, Electronics for Dummies .

    I shall not talk about the bench itself, and the qualities it should have. All you would need is a table, a per-sonal desktop type computer and a few tools. Desktop computer, because they are rather cheap, easily available, and even an older Pentium 4 will work fine. More so because they have Hardware serial ports which are more suitable for cheaper student type programmers and for establishing serial communication with microcontrollers.

    You should have a minimum of following hardware to get started:

    Project / Bread Board. This is also called solder-less board. You can find a number of them in different sizes available in local market and electronics hobbyists shops. The beauty of this board is that it can be used again and again for various projects. Components can be easily plugged into the holes and various connections made using jumper wires. You can have multiple such boards and pre-made common circuits on them so that you do not have to made them again and again. The jumper wires you use should be little stiff and single wire, instead of twisted wires. It is easier to insert the rather stiff single wire into the holes.

    The top and bottom rails are connected horizontally and are used for power supply. The rest if holes are connected together vertically making columns of inter connected holes. See http://en.wikipedia.org/wiki/Breadboard for details about using a breadboard.

    Digital Multi-Meter A digital multi-meter is mandatory for any electronics lab. This meter has three measuring systems in it. A voltmeter to measure the AC and DC Volts, an Ampere meter to measure the flowing current and an Ohm meter to measure the resistance. See http://en.wikipedia.org/wiki/Multimeter for details about using a multi-meter. You will find a number of simple and advanced multi-meters in market. To begin with get the sim-ple one, There is no need of other functions like pulse generator or frequency measurements for our pur-pose.

    3 Setup Your Personal Electronics Workbench

  • DC Power Supply This is an important part of your lab. We shall need a 5V regulated power supply for our projects, but some parts of the project may require more than that. A num-ber DC power supply adapters are available in market having selectable output volts. Indeed battery packs are also available however they give a fixed output supply. A few packs have rechargeable batteries. I shall not suggest a very sophisticated power supply at this mo-ment. Get a multi volt 3-12V DC adapter preferably 300-500mA rating. These adapters usually have a polarity selection switch as well, make sure your adapter has this as it is useful to change the positive and negative terminals. Notice the adapter shown in figure has multiple outlet pins. Also there is a clip like 9V battery. This is specially good, as we can have 9V Battery holder in our project and can power the board through 9V battery or this DC adapter. I shall not go into details of building a 5V supply. If you are going to use Breadboard for your experiments, make sure you have a 7805 voltage regulator IC and make appropriate 5V supply either on the breadboard or separately.

    Programmer Programmer is a piece of hardware that will transfer the program from your computer to the program memory of your microcontroller. Once the program has been transferred you insert the chip into the development board or your bread-board and let the program execute. This picture shows a very simple programmer for students and hobbyists. This programmer can accept program through a serial port cable connected to your computer. The target microcontroller is inserted into the ZIF socket. After the program is transferred the controller can be removed and inserted into your project board. A number of other designs, some cheaper and some expansive also exist. This particular programmer is called JDM design. You can visit JDM home page at: http://www.jdm.homepage.dk/newpic.htm, or the Feng deign, http://feng3.cool.ne.jp/en/pg5v2.html as of the one shown above. Many microcontroller hobby shops sell these and many other de-signs at reasonable prices. It is better for a beginner to get a pre-made and tested programmer so that he may concentrate on his primary objective, i.e programming. Once he has made through the things, and his confidence level is high he can attempt to make things himself. Many shops also sell these programmers as kits, that include PCB, and components so that you can build yourself.

    In Circuit Programming It is traditional to have a ZIF socket programmers. You insert the controller at appropriate place in pro-grammer socket, burn the program into controller and then remove the controller from its socket. Re-insert it back into the project board and test. This removal and insertion again and again has its hazards. You can break the legs, insert it wrong way and damage the controller. Moreover its tedious job. The current stan-dard is to program the controller in its target board. This does require a programmer, but you do not need to remove the controller from its target board. The target board however needs to have a way the programmer can be connected. This is called In-Circuit programming header (ICSP). You can see the header in above figure. If your board has such a header, just connect a connecting cable between programmer and board and your controller can be programmed right there.

    Bootloader There is another advancement in microcontrollers, called self-programming. Not all controllers have this capability. Only newer and advanced controllers can be programmed in this way. 16F628A can not be pro-grammed through bootloader. Howerver 16F877A or 18F452 etc can all be programmed. Although we shall

  • use the standard programmer, it is useful to know about this technique as well. In order to use this tech-nique you have to install a small software, called bootloader into the program memory of microcontroller using a standard programmer. Once the bootloader is in place now each time you reset or start the controller bootloader executes first. It will check the serial port, or USB if controller has one, to see if a new program is coming. In case a new program is available, it is accepted, and written into free memory of controller. After the program is transferred the control is transferred to new program and starts executing.

    Development Boards Well PIC microcontrollers basically need a very simple hardware setup to execute a program in them. But the program will execute inside the controller. In order to communicate with external world or actually con-trol something we need to have some external devices connected to the con-troller. This is fairly easy to the level of a few LEDs or buzzer but becomes quite complicated when a number of devices need to be interfaced. If you are making a specific project, its worth making a proper PCB, or do it on vero-board, with soldering.

    Many commercial companies and or-ganizations have made complete boards, that have many devices pre-built over them. You can use them to test your programs, or extend them to connect to your particular project. These boards can be as simple as con-taining just microcontroller , crystal and power supply to huge containing dozens of devices.

    I would suggest getting a simple board first. Once you have mastered the basic structure you can invest on something like Easy PIC-6 from microelectronica.

    Just ask your geeky friends and I am sure they will guide you the appropriate place where you can get these boards.

    Smart boards Every development board does not has every possible interfacing device. And there are certain devices that are com-monly required in many projects, again and again. So these devices are usually available as standalone boards, called smart boards. These boards alone can not do any function, but can be easily plugged into any microcontroller pro-ject, and extend its functionality. An example can be Real time clock chip. This chip has all the necessary circuitry and program to maintain the time. Project where time and date keeping functionality is required this chip can be useful. In case your board does not have this chip, you can have it as a smart board. Not only you can use the smart board with your particular development board, but can incorporate it into other standalone projects.

  • Understand your board You can connect the various devices to microcontroller in many different ways. Specially when it comes to general purpose devices like LED, LCD and switches etc are concerned. It is important to know how de-vices are connected to the microcontroller. Usually the manufacturer of board provides a manual or sche-matic to show the connections. In case our discussion differs in terms of connections, you can make appro-priate changes in your program to take the difference in account.

    Software required You need to install two basic software on your computer. A compiler and a programmer supporting soft-ware. As I mentioned earlier microcontrollers understand numbers, their commands are also numbers. Hu-mans on the other hand understand words. So software were made that accept English like commands and convert them into appropriate controller understandable commands. These software are called compilers. The syntax and structure of English like commands depends upon the programming language being used. There are a number of programming languages I common use. By far C is the most popular and most commonly used. For a beginner I would suggest using BASIC as a programming language. A number of compilers exist for BASIC language to compile the commands into controller understandable code. There are two popular compilers, PROTON BASIC, developed by Crownhill Associates and MikroBasic devel-oped by Mikroelectronica. Both of them have their fans, and fan-clubs. PROTON BASIC has very simple programming style, and has very few restrictions on style, it however lacks a structured programming ap-proach which pays in the long run.

    My previous texts have used PROTON BASIC as a programming language. In this book I shall give Mikro-Basic a try. The advantage of MikroBasic is that a demo version can be easily downloaded from their site. This demo version is not limited to the number of supported controllers. Its only limit is 2K code size. 2K

  • code is quite big for a microcontroller, and most of the basic learning projects remain well under 2K. Sec-ondly Mikroelectrica also makes C and Pascal compilers. The device related library remains almost same. So whatever you learn on MikroBasic, is also applicable to a large extent to MikroC as well. MikroBasic compiler and associated documentation can be downloaded from http://www.mikroe.com/eng/products/view/9/mikrobasic-pro-for-pic/ .

    Mikrobasic is an integrated development environment. This means the same software has an editor, a com-piler and many other supporting tools. MikroBasic supports their own programmer as an integrated devel-opment tool. Since we are using a different programmer, we shall not use that part of their software.

    Programmer Software As we are using JDM programmer, we need to download and install a supporting software. JDM is an open source design, so many free to download supporting programs are available. WinPIc800, ICPROG and PICPGM are some of the commonly used. We shall use PICPGM for our purpose. Nevertheless all have same functionality. If you have a different programmer or want to use a different software it does not mat-ter, as long as it supports your controller and accepts the compiled (.hex) file and transfers it to the control-ler.

    PICPGM You can download this free software from, http://members.aon.at/electronics/pic/picpgm/ . Although the number of supporting devices is some-what less, but it does support all com-monly used PIC microcontrollers. The beauty of this software is that it auto-matically detects the type of program-mer, the port where it is attached and the microcontroller that is connected. If everything is detected automatically it is for sure that the system has been properly connected and configured.

    Most of the times you do not have to do anything, except to file it. It will automatically detect the programmer and microcontroller. Browse the .hex file and click over program button. Yellow button on toolbar with light-ning icon.

  • N ow that we are ready to take-off, its better to have a brief tour of our working environment, so that we know where to find various tools, and how to make a basic project. Although Mikroba-sic is loaded with features and tools, we shall not discuss each and everything in this section. You can find very good documentation in the Mikrobasic manuals. We are using Mikrobasic Pro 2009 version. The exact look and experience may differ depending upon your particular release. Never-theless they all have same basic features, like a new model of a car, basically its a car and if you under-stand previous one surely you will understand this one as well.

    Traditionally programming consisted of many separate steps. You need an editor to write your program as a text file, then you need a compiler that will accept the source file and generate the appropriate target file. Then you need a system to transfer the generated file into the microcontroller. In case you need to revise the software he entire procedure is repeated again. On top of that there are certain other features that are di-rectly or indirectly related. An ordinary editor, like Notepad has no idea what you are writing. The intelli-gent editor of Mikrobasic however knows you are writing an application software for a particular microcon-troller, so it helps you by highlighting the keywords, variables and objects etc. Similarly there are other tools to help you write the code, so that you do not need to remember the exact syntax of a particular com-

    4 A Brief Tour of MikroBasic

  • mand.

    Mikrobasic is a user-friendly and intuitive environment. Indeed such a programming system is called Integrated Development Environment. Most of the commands and actions are common in windows envi-ronment therefore they do not need to be talked about. For example we all know what is Cut-Paste, how to open a file, locate a folder and save a file etc.

    The Mikrobasic screen looks haunting at the first glance. Having so many sections and modules. Hang-on they are all there to help you, you can customize the look according to your needs by dragging and drop-ping various dock able windows. All I need to introduce you is the fundamentally important parts.

    The main window in center is your text editor. It is here you will write your program. The panels on right

    and left are supporting panels that you will open when required. The panel below is message area where you will find various system messages, we shall talk about these messages as and when they appear.

    Most of the times our code can become quite big, and it makes sense to store it in different files. Instead of writing in the same one big file, it is better to store the parts of project in various files. In this way it is easier to find the code, and also to use the same code in other projects if required. Thus Mikrobasic and many other newer IDEs encourage the Project approach. A project con-sists of one or more than one files.

    So lets begin with a simple project, where we want a small program to blink the LEDs con-nected to PORTB. For now do not take the code seriously, what I want is to familiarize you with the basic procedure.

  • When you first fire Mikrobasic a default project already opens. Click over the Project menu and then over Close Project Group. The entire window will clear and there will be just blank IDE with no editor. Now click over Project menu and then on New Project. A new project wizard will appear. This will ask you a few questions about your project and set the necessary environment for you. Although you can set all those things yourself, or if you want to modify them later, this wizard approach is good to start.

    The first is a welcome screen. It has given you an idea what its going to do. That it will create a new project and setup your environment. I would suggest you create a new folder before that somewhere in your hard drive, lets call it PicProjects . Then for every project make a sub folder, lets say Blink for this project. The project wizard only makes files and might name those blink but if you create multiple projects files with similar names might be confused. So here I assume you have created a folder like: D:\PicProjects\Blink. Now click Next. This step is asking you to chose the micro-controller for which you are going to write the program. You will do this according to your particular controller. We are going to use an 18 Pin PIC microcontroller 16F819.

    In other projects we might chose 16F6128A, and in still others 18F452 depending upon the particular situation.

    It is important to tell the Mik-robasic about the microcontrol-ler that we shall be actually using. This is because it will select the appropriate registers for that particular controller, as

  • well as load the memory map fro various registers. For example two controllers can have PORTB, and this register will be called same when writing code, but the internal memory address within the microcontroller might be different. Thus when a compiled file (.hex) file is created the addresses of registers are sent, not names. That is why the .hex file created for one microcontroller may not work on other having similar source code.

    Click next, now it is asking for te Device clock speed. This is the speed of oscillator we are going to use. The default is 8MHz. Again you will need to consult your board. If it has a crystal oscillator, you got to know what speed crystal it is. Usually its written over it but many a times its so faint that you can not properly read it. The best guide is manual from the manufacturer.

    In case you have assembled the board yourself, then of-course you know what crystal you are using. I personally use a 20MHz oscillator to push the microcon-troller to its limits. As I had pre-viously discussed it not always best to use highest speed. It depends upon your application. Any way right now our board has a 20MHz crystal oscillator, so we change this value to 20.0 MHz.

    Next step is to chose the location where project files will reside, and the name of your project file. Notice I have selected my folder and named the project file as Blink. It has automatically given it the extension of .mbppi. This is a reserved extension of Mikroba-sic for its project file. The project file is actually a binder. That will contain links to many other files that are part of the project. S your project is not in this file, your actual code will be in separate files and even may be scattered in many different folders. This File will keep a link to those files.

    We shall not experiment with distributed files for now, and all our files related to a project will reside in the same folder. May it be a sin-gle file or more we are going to use this approach.

    The next step is asking you to Add a file to the project. It is here we add previously written files. For now since we do not have a file yet, just click next. In fact we are creating an empty project folder. Next step is asking you to chose the libraries. The concept of libraries is very beautiful and at the same time very powerful. Most advanced compilers may it be microcontroller related or PC programming related have

  • libraries. I shall talk more about li-braries later. For here I would just say that various programming appli-cations need to take into considera-tion a number of commonly used technologies. For example LCD, thi-sis commonly used in many applio-cations. In order to use an LCD prop-erly we need to write quite lengthy code. Need to know its commands, and their format and then send the data accordingly. All this complexity has been hidden from us by the Mik-robasic LCD library. So we are con-cerned only upto the level of how our LCD is connected and what we want it to show. The rest of code is gener-ated during .hex file creation by Mik-robasic. Thus presence of the LCD library has made our coding easier. The more libraries you have, natu-rally more facilities you have to work with. Another beauty of these libraries is that if you change the con-troller, use of library remains same. Even if you later opt to chose MikroC for example, it will also have almost same library. Since Microelectronics people make compilers for other controllers as well, for exam-ple 8051, Although the MikroBasic compiler for 8051 will be different, but will have the same environment and same libraries. Ok for now we want to include every library in our project. The code will not increase by this action, because only the code that is included in source file will get compiled. Including them here is only for reference. Click next, and final step is finish. Just finish it and your project is created with a new file in editor. Notice the file name in editor window is Blink.mbas this is our source file. Mbas is an exten-sion for Mikrobasic source code. It has automatically inserted a few lines of code. By default the first line has to have a directive called program and its name. In this case Blink. Then there has to be a label named

  • main:

    Notice a : after the word main. This word must be there and this indicates the starting point of your appli-cation. Whenever the program starts executing it will first locate the main: label and start program execu-tion from there, later it can be made to jump to other modules. So our code will start after the main: module. The last command end. Should be there to indicate where main code body is finished. You can write other callable procedures and functions below the end Statement.

    Now enter a program like this. Dont worry about the commands and what they say. They will be clear in a few moments. While writing a command if you press Ctrl+(Space key) a help will automatically appear you can go on typing the command and it will go on filtering finally you can find the one you are intending to write. This becomes helpful if you forget the exact command or its parameters. This window is called code assistant.

    Note Basic language is not case sensitive, whereas C is case sensitive. So in Mikrobasic PORTB and portb are same. It is however conventional and more user friendly to write the names of registers in capital case, and your local variables in small case.

    Now that we have written the source code, its time to save it. After saving we can generate the .hex file click over project and then Build. This will invoke the compiler and you will see a number of messages appearing in the messages window below the editor window. Look for the last line, saying Finished Suc-cessfully. That is it. You have successfully created a .hex file that can be transferred into 16F819 micro-controller.

    Now lets have a look at the folder where we created the project file. As you can see there a re a number of

  • files there including our project file, then the source file. Notice one important file, pointed by arrow, the Blink.hex file. This is the file that contains all the code necessary for executing our LED blinking program to 16F819 microcontroller.

    If you have reached so far, that is good, and this is the barely minimum that is required. Now if you want to modify the code, just change it in the editor and build again. Remember we are dealing with our source file through project, so if you close the Mikrobasic, you will open the project not file. Click over Project, and then open project chose your project file and there you are. Your code along with all settings is back. Burning the .Hex File into Microcontroller Lets move one step forward and transfer the .hex file into your microcontroller. I assume that you have already installed PICPGM software on your computer, connected the PIC programmer, I am using PIC PG-2 a JDM type programmer. The programmer in turn is connected to the development board with 16F819 in place. I am using In circuit program-ming technique, so I do not need to remove the controller from its motherboard.

    You can see in this picture that the programmer is connected through serial cable to the PC. Most PCs have one serial port and its named as COM1.

    On the other hand the Programmer is connected to a cable to the development board. The ar-rangement of pins on this header is fairly stan-dard as per Microchip guidelines. Make sure if you are using such an arrangement the pins la-

  • beled properly and have arrangement as per microchip guidelines.

    This picture shows our development board. Notice the cable from programmer, is connected to the In Cir-cuit Programmer Header. You can also see the crystal oscillator very clearly labeled as 20.000 MHz. After connecting these, you will find that power LED turns ON, even though we have not plugged in supply yet. This little 5V supply is coming from programmer. This is enough in most cases to program the microcon-troller, but if there are other ICs on board, the supply may not be enough. Therefore connect your power supply to the board and turn it ON while programming. Now we fire the PIC PGM. Notice it has detected the programmer as well as the controller in place. Click the yellow Program button and it will transfer the program into microcontroller program memory. In the end it will show a green message box indicat-ing a successful transfer. If the red box indicat-ing an error appears check your whole system.

    After the program is transferred, you have to un-plug the programmer from development board. This is because the programmer has still kept the MCLR pin in programming mode and due to this the program can not execute. Instead of removing the cable from board, I usually un-pug the serial cable from programmer. That effectively turns the programmer OFF and re-

    Easy PIC III Trainer Board for 18 pin PIC Microcontrollers

  • leases the MCLR pin. Turn The Power of your board OFF, remove the Serial Cable from programmer and turn the power of your board again.

    You should see the LEds Blinking at a rate of 1 second. This will be exact 1 second ON, and 1 Second

    OFF.

    Notice the LEDs B6 and B7 are somewhat dim than B4 and B5. This is because we have placed 220 Ohms resistors with LEDs on B4 and B5 (actually connected to RB4 and RB5) to limit the current drain from PIC microcontroller. However with LEDs on RB6 and RB7 we have placed 1.5K resistors. This had to be done to take advantage of In circuit programming. The In circuit programming also uses RB6 and RB7 to trans-fer data, see data sheet, these pins are also labeled as PGD and PGC. When a current draining device like LEDs is connected to these pins they tend to drain the programming signals and therefore microcontroller can not be programmed.

    Microchip recommends to keep this pins free if possible, otherwise use a 1.5 to 4.7K resistor. This will only limit current but still any other device requiring logical value like a transistor etc will not be affected.

    Well so far so good. What if your project is not producing optimum results? This definitely indicates some problem. Problem can be in your hardware or in your software. This is time to debug your application. Truly speaking best debugger is one which reads in the program status and microcontroller status from the actual board while program is working in real environment. This type of debugging requires a special hard-ware device called In circuit debuggers. Mikroelectronica and other companies have their own proprietary debuggers that can be used with their compilers. Microchip makes ICD-2, ICD-3 and PICKit-2, PICkit-3 for this job. Still if you just want to see how your program will execute, and want to see its logic flow, Mik-

  • roBasic has built in debugger. We shall talk about this in some later section.

    .

  • B ASIC is an old programming language. It was developed in 1964 at Dartmouth college, New Hampshire USA by John George kemeny and Thomas Eugene Kurtz. At that time programming a computer required lots of technical knowledge about the hardware and electronics. The idea of developing this language was to facilitate non-science students able to program computers and use them. A number of other programming languages developed like Fortran, Cobol, PL1 and so on they all did great job but vanished with time. BASIC stood the tests of time and still persists in quite advanced form for a number of platforms. Today BASIC is considered a family of High-Level programming languages.

    The science of computer programming has taken many changes, BASIC language has adapted these changes and therefore stands with many other competing languages, like C.

    Therefore truly speaking a programming language itself is a set of principles or rules to write a program. BASIC language therefore defines certain rules, and these rules remain same, weather we are programming a personal computer or a microcontroller.

    Lets come straight to microcontroller. A number of companies make BASIC language compilers for micro-controllers. They all have to follow the same basic principles as defined by the BASIC language. However they differ in two ways:

    1. Each compiler provides its own set of libraries, which contain useful functions and procedures to carry on everyday tasks. Some of these functions may be similar but differ in implementa-tion. For example every compiler would provide a facility to write data on an LCD display, but exactly how to implement it in user program will differ.

    2. BASIC language defines many standards, which have been evolved over a period of decades. These standards dictate the standards of programming technique. Not every compiler follows the latest standards. There are compilers with excellent library but they lack what is called Structured Programming

    MikroBasic is fairly advanced and it tries to adopt many advanced standards. It has an excellent library to support many commonly used procedures, as well as it follows structured programming technique. This chapter can not be a detailed tutorial on programming, but I would just mention that a structured program is more easy to maintain and extend.

    Microcontrollers have limited memory, indeed a few Kilobytes, therefore it is hard to implement every standard of programming as these standards require more memory. To some extent these standards are then applicable in microcontrollers with more memory, but in these smaller controllers like 16F819 with just 4K memory it is not expected that an object oriented model be implemented. Many procedural calls, from one procedure to another and from there to another result in storing the local variables and registers on a common memory place called Stack. The more stack space a controller has more deeply it can address the nested procedures. With limited stack space we have to keep in mind that we can not call too many procedures in a nested fashion.

    So programming Microcontrollers is a two way challenge, on one hand you have to achieve the results you want with limited computing capabilities. On the other hand you have to manage the available resources, limited program memory, limited variables storage and so on.

    Considering limited stack space, Recursive calls to the same procedure are not allowed in MikroBasic.

    It may not be possible to discuss each and every MikroBasic command in detail, here however a general outline will be given so that we can take a simple start. We shall talk about specific commands and issues

    5 MikroBasic Programming Language

  • as they will be encountered in the following chapters.

    I would however recommend you to go through the manual of MikroBasic compiler that will give more details on specific topics.

    MikroBasic organizes your program in the form of a project. A project is nothing but a collection of re-sources required to solve an issue. Ideally speaking this does not only include the code you are writing but also the help material, research articles and support libraries. Everything even your rough work is part of the project and must be kept and moved together. We usually assign a separate folder for each project and then keep the various files in that folder. MikroBasic Project includes all relevant files including your source code. When asked to compile only the files referenced in code will be used to produce single target file called .hex file.

    Many students ask, why we should have multiple code files, when we can write the code in one file. That is true, and indeed many beginners do the same way. However to be a professional you must be organized. The code is better organized in individual files, containing one specific part of the code. Similarly there are many projects where almost same code is required in various locations. Thus if you have already written, tested and debugged a code why to repeat it again.

    In order to keep it modular we tend to keep the code organized in different files. For example I have devel-oped a routine to accept numeric data and floating point data from the keypad, and pass it on to the program as integer or floating point variables. It took me pretty long to develop the algorithm, error testing etc. Now if I save this code as a separate file, like keypad.bas then I will just include this file in my every project, and I would not have to worry about this code again.

    So if a project is going to include so many code files, how will the compiler know where to start? This is done by the Main: keyword. There should be only one file that should contain this keyword. Usually this is also the specific file for your project as well. MikroBasic is very strict in following its program structure. A program consists of :

    A Header section

    A Declarations Section

    Procedures and Functions

    Main Program Body

    The Header section is the first part of program and contains keyword: Program this is followed by the name you have given to the program. Following this is the Keyword Include this describes external mod-ule files to be included in your code. If your program does not require external referenced files, this may be excluded. In files that do not contain the main section the Program keyword is replaced by Module. We shall see about these things where need arises. For now just remember your program will begin with Pro-gram keyword, and will contain the main keyword.

    Variables Variables are the main stay of any program. These are the structures which contain run-time data. Variables are defined and used in a program, but they get actual existence when the program starts execution within the target machine. Variables are created in RAM. In microcontrollers RAM is different from Program memory. Usually Program memory is reasonably large, but RAM is quite small. We have to be careful while using variables, as we can easily end up in consuming the precious RAM. Different microcontrollers differ in size of RAM they have. This is also an important factor in choosing the microcontroller for your application. For example Microcontroller A might have enough powers to handle a particular job, but when you compile the program, its usage of memory out-runs the RAM on this chip, so you have to choose an-other with more RAM, or re-design your program to accommodate smaller memory size.

    Any way , we were talking about variables. There are certain rules for using variables:

  • A variable must be declared before it is assigned a value or used. In MikroBasic there is a keyword Dim that is used to declare a variable.

    A Variable must have a unique name. It can be a single letter, a combination of letters and numbers and some special characters. The variable name however must always begin with a letter. It should not have space, or special characters like , &, * etc. Also a variable name should not conflict with similarly named MikroBasic command or Microcontroller special function register names.

    A variable must be defined as specific type at the time of declaration. The type means kind of data it will be supposed to contain. Although internally everything is as bits and bytes yet there are different ways of han-dling them. The compiler therefore requires you to inform it the data type the variable will hold. We shall talk more about data types as they are required, but for now just remember the commonly used data types: dim i, j, k As byte

    dim counter, temp As word

    Notice the keyword As after the list of variable names. Following this is the type of these variables.

    Life and Scope of Variables When a variable is declared within a module, procedure or a function, the variable is said to be private to that module. It is created when the program enters the module, and when the program leaves the module it is removed from RAM. The location is free for use by other variables to be created. The contents are cleared and variable name is released.

    Therefore if you declare a variable named count in a procedure, when the procedure exits you can not ac-cess the variable count because it is out of scope now. Moreover if you have another procedure and it also uses same variable name, there is no conflict, both will be handled separately.

    A Variable that is declared before the main statement is called Global variable. This variable is going to persist for the entire life of program. The variable is accessible to every module. However now modules can not declare their own private variable with this name, as it already exists.

    Arrays and Strings Arrays are special data types with same variable name for many variables. However each variable has a subscript number, which can be used to access an array variable. In this way many similar variables do not need to be declared separately and named separately. The key point is there should be a logical reason to group them.

    Dim Months as Byte[12] This statement will declare an Array of 12 variables. Each having name Months. Each variable will be able to hold one byte of data. However to refer a particular variable we need to provide it an index number.

    Type Size Range

    bit 1bit 0 or 1

    sbit 1bit 0 or 1

    byte, char 8bit 0 .. 255

    short 8bit -127 .. 128

    word 16bit 0 .. 65535

    integer 16bit -32768 .. 32767

    longword 32bit 0 .. 4294967295

    longint 32bit -2147483648 .. 2147483647

    float 32bit 1.17549435082 * 10-38 .. 6.80564774407 *

  • Since we have created 12 variables, they will have index numbers 0 .. 11. In our program we shall access them as Months[0], Months[5] etc. Strings are nothing but an array of characters. Although every character is internally stored as a number, but the compiler will not perform mathematical functions on these numbers. They are called characters. To de-clare a string we use string as type followed by its length in square brackets.

    Dim msg1 As String[16] Msg1=Hello World

    The string is internally stored as array of characters, plus one additional character called null. This contains number 0. to indicate end of string.

    Special Function Registers of PIC There are a number of registers located inside the microcontroller that modify the function and behavior of various modules. These are called special function registers. Although internally represented by specific memory locations, they have been given names in the datasheets. It is easier to talk about them using their names instead of locations. Most of the registers are common among many PIC microcontrollers so they have same name, some are specific or different and they tend to have different names.

    There is no need to declare the special function registers in MikroBasic. MikroBasic compiler already de-clares them for us when we chose appropriate microcontroller as part of project definition. MikroBasic de-clares them as Word type. Moreover they are declared as Global so they are accessible from every part of the program.

    Constants Constants are data whose value remain same throughout the program life. They are simply difficult to re-member therefore we give them a user friendly Name, like a variable. Unlike variables their value can not be changed. Once declared we can use them. Constants do not consume RAM. They are part of the program memory.

    Same rules apply for declaring constants as for variables. It is however traditional among programmers to name the constants in upper case. The data type is automatically calculated by the compiler at time of dec-laration, smallest size is chosen. const MAX as longint = 10000

    const MIN = 1000 ' compiler will assume word type

    const SWITCH = "n" ' compiler will assume char type

    const MSG = "Hello" ' compiler will assume string type

    const MONTHS as byte[12] = (31,28,31,30,31,30,31,31,30,31,30,31)

    Thus in a program with some maximum and minimum values, instead of using 10000 and 1000 again and again, we will use MAX and MIN in program. This will also facilitate if we decide to change the maximum and minimum values, instead of locating many places where we had written 1000 and 10000 we just change the constant definition, and thats it. Another danger in using raw values is wrong entry at certain position, or while changing the value to new one, missing it in some location. All this is avoided if we make a good programming habit of using constants, and also writing comments to elaborate whats in your mind.

    Comments Comments are special type of text that is meant for programmer only. This text acts as small on the spot

  • notes to help programmer remember and recall, what is happening in this part of code. Comments can be placed on entire line, and series of commented lines act as a block of notes. Comments can also be placed along side the code. To begin a comment just enter the character (apostrophe) and start writing the com-ment. A comment will continue on the same line. To continue it on the next line, you have to begin the next line with a new comment. Comments are stripped off during compilation and do not affect the object code generation.

    Literals Literals are special indicators used to inform the compiler about nature of some values being used in pro-gram. For example integer numbers can be represented in decimal, hexadecimal or binary form. Internally the value might be same, but physically they are written in different formats. Although it is not very diffi-cult to guess the nature of a number by looking at it, but it might become confusing at times. Consider the binary number 10, now in binary notation it is two, but some one might interpret and read it as ten, which is entirely different value. Therefore in order to remove this ambiguity, MikroBasic allows you to prefix the value with certain characters, to indicate the intended nature of value.

    A % sign is used before binary numbers, like %1011 is four bit binary number

    A $ sign is used to indicate a hexadecimal value, like $A0 is eight bit number in hexadecimal format. Peo-ple with C language background are used to using 0x as a prefix for hexadecimals. MikroBasic accepts this as well, so $A0 and 0xA0 are same thing. No prefix indicates a decimal number, thus a value 67 is simply sixty seven.

    Labels Labels are tags of text used to refer some specified location of code in the program. A program con contain as many labels as you want, but they must be unique. To define a label, all the rules used to define variables are implemented. The label however does not need to be declared first. Just write label name, followed by a colon : for example, AA: is a valid label. Now this section of code can be referred to by Goto AA . Notice when using the label name with Goto there is no : sign.

    Use of labels is not encouraged. In todays programming standards, what we call structured programming, people will frown if they see use of labels in the program. They are supported for two reasons, firstly for backward compatibility, and secondly since assembly language code can be mixed in MikroBasic, and as-sembly is non-structured language. It will certainly need use of labels. So we will use labels only very occa-sionally.

    Symbols Sometimes in a program using special function register names, or even their bits, might be repeated a lot. This might increase confusion as to remember what this register is doing. So we use symbols to represent those commands, or even registers. When the program is compiled, the compiler will actually replace those symbols with the equivalent defined code.

    Functions and Procedures It is customary to write the code in a linear top to down format. Since a program actually contains many logically different processes, like a portion might be calculating something, another getting user input and still another responsible for displaying the result on LCD. No doubt all these processes can be written in a single process, writing appropriate code where required. This approach however is criticized by many pro-gramming gurus.

    The reason is that you might be repeating same code again and again, thus if changes are required you have to apply at a number of places. Still more objectionable is that the compiler will generate more machine language code and therefore will consume more controller memory.

    Functions and procedures are parts of the program that are complete in themselves and have been designed to do a specific task.

    They can be given specific, meaningful names. All variables required by these sub-programs are private

  • and therefore will not interfere with each other. Once a function and procedure has been tested to work properly, you will not need to remember its internal workings. Now it will be dealt as a block of statements, referred only by the name. You may call them any number of times, even pass on parameters. Functions on the other hand also return a value back to the calling program.

    Using functions and procedures is considered a good programming practice. Therefore to ensure we stick to the best standards, we shall try to use this programming methodology wherever possible.

    There are still many more areas of MikroBasic that need to be addressed, these will need a complete book in itself. MikroBasic has its own very good programming reference available in PDF format. You must go through it to read more.

  • M any students and hobbyists love to make their own development boards. No doubt this is es-sential practice to make at-least one basic board yourself so that you know exactly how to hook-up the microcontroller in a circuit. After-all any project is not merely programming but has an equally important electronics hardware part as well. In this section we shall dissect the barely necessary microcontroller board on a breadboard, and write a simple program as we did earlier to blink the LED.

    Breadboard Basics I am sure most of you are already familiar with a breadboard, however just for completion of the topic and for our friends who are new to electronics let me give a brief tutorial. Also we shall define some best practices to make the breadboard project easier to handle, and share. If we are following standard practices, it is easier to share things.

    Breadboard is also called a solder-less board. Components can be easily inserted into the board. Underneath these holes are connected together. Thus there is no need to solder the components together. The Top and bottom Rows are connected together as two rails. These are used to power supply the different parts of project. It is customary to use lower rail (show n as blue line) as ground and upper rail shown with red as + supply. The columns shown in between are connected together as vertical columns. There is a groove in the middle that disconnects the columns above and below. Thus an integrated circuit can be inserted with half pins above and half below the groove.

    It is also customary to keep the notch of in-tegrated circuits towards left. This simulates most of the time with schematic to reduce the complexity. The upper and lower power rails are not connected together. You must connect them together using jumper wires. Some breadboards even have disconnected power rails in both upper and lower parts, to allow you four different types of power sup-plies in case your project needs. Since we will be working most of the times with sin-gle supply of 5V it will be more convenient to connect them together as one supply.

    I would like to mention here about jumper wires. I used to have lot of difficulty in in-serting the jumper wires and also to keep them in good contact, when I was a beginner. Use single core little hard, preferably No. 20-22 gauge wires.

    6 Hello World !

  • Do not use soft multi-core wires, as they are difficult to insert. As shown in this figure cut them into differ-ent legths and keep them in a container. You can find suitable container from stationary shops, where vari-ety of pencil boxes will suit this. Similarly make boxes for components like resistors, capacitors, transistors and ICs etc.

    Five Volts regulated Power Supply Most microcontrollers work at 5V power supply, although some require 3.3V, we shall be using 5V compliant microcontrollers in this book. Unfortu-nately power supply units are available in 1.5V in-crements. Using three 1.5V batteries in series will give 4.5V and is accepted as a source of supply. However as batteries will get consumed this voltage will drop and microcontroller project will misbe-have. A better solution is to have a 6 or 9V power supply, either in the form of a battery pack, or as a DC adapter, and then convert that supply to 5V regulated one using voltage regulator ICs. In case you are working with a development board, they usually have this thing built right on the board. In case you are working on breadboard, or make your own customized board on veroboard then you have to make your own.

    I would prefer to make the 5V supply on your breadboard and then not to dismantle it every time. Your breadboard should therefore always be ready for 5V circuits. A still better idea is to make your own stand-alone 5V supply unit, that can be used in many projects. PIC Microcontroller Basic Setup The basic setup of PIC Microcontroller can be as simple as just hooking up the 5V supply. I would however go for the more traditional setup that is standard. PIC microcontrollers have an MCLR pin. You will have to see the datasheet of your particular controller to find this pin. This pin when connected to ground (momentarily) will reset the microcontroller execution, and the program will restart again. Note this action does not erase the program from memory. In order to allow the program to run, this pin must be at logical

  • high or near 5V. You can simply connect it directly to +5V, also called VDD (+ 5V is also called VDD, and Ground VSS). Since many applications also use in circuit programming, and also use this pin to reset the controller, it is better to use a 10K resistor to connect it to VDD supply.

    Some Microcontrollers, like the 16F877 as shown has two pins for +5V supply and two for GND. Both of these sets must be connected to power supply.

    Oscillator All microcontrollers need a source of pulses to synchronize internal tasks. The processor will take one step forward in program execution every time a pulse is received. Therefore we have to provide a reliable source of these pulses. If pulses increase or decrease due to instability in oscillator circuit the program execution will be affected and many timing applications will not be accurate. We use Crystal oscillator for this pur-pose. A crystal oscillator is very stable over a wide range of physical conditions like temperature and pres-sure. The oscillators are available in various frequencies, like 4, 8, 10, 12, 20 and 40 MHZ or even more. You can choose any, but you have to know its frequency. We shall be using 20MHz Crystal oscillator in our projects. PIC microcontrollers have two pins named OSC1 and OSC2, consult your datasheet to locate them. The crystal oscillator can be connected to these two pins. There is no orientation of legs, it can be connected anyway you like.

    The faster the crystal is faster is program execution and response, this however also consumes more power. As per lab is concerned this is usually not a big issue. In your final projects, if the project is battery based, and very high speed is not requirement of your project use, a lower frequency crystals to conserver battery. In order to stabilize the oscillator two 22pf capacitors are used as shown in the circuit diagram shown above.

    Connecting LEDs Microcontrollers are designed to give out control signals. They are not meant to provide necessary power for the output device. You will therefore need an external driver circuit for that. We shall talk about driver circuits later in this book. Driving an LED is however simple and does not require much power. Usually

  • LEDs can be connected directly to the microcontroller pins. If you go through the PIC microcontroller data-sheet it says, each pin is capable of supplying 25mA of current. Since LEDs come in different forms, some consume more current where as others are more economical. It is therefore standard practice to place a cur-rent limiting resistor in series with the LED to protect the microcontroller I-O line from being damaged.

    The true value of this current limiting resistor depends upon the specifications of your particular LED. However the best bet is to use a 220 to 330 ohms resistor. I use 3mm small LEDs and a 220 Ohms resistor in series. Since resistor is in series it does not matter if it is placed before or after the LED.

    Current Sourcing and Sinking These are the two terms commonly used in microcontroller applications specially where LEDs are con-cerned. By current sourcing we mean that to be active microcontroller pin will be at logical high value, and the consuming device will get + supply from microcontroller pin. In Current sinking, the device gets + sup-ply directly from the power line, and microcontroller pin acts as GND. Thus when microcontroller pin gets logical low, the current flows from VDD, through the LED into PIC pin. The led will then glow when the pin is low. In current sourcing LED will glow when microcontroller pin is high.

    Breadboard Friendly Modules I would strongly recommend you to make the breadboard LED project yourself, as this is the most native form and you will gain a lot of con-fidence. In order to practice on breadboard time and again, you have to build this basic circuit. Many students and some commercial vendors make small modules that are breadboard friendly. These modules are made keeping in view their use on breadboard. These modules make your life a lot easier. They are truly a plug-n-play sort of thing. You Plug-in the mod-ules on breadboard, and treat them as one com-ponent. Then using jumper wires connect them together in the way you want them.

    You can see in this picture an Arduino based

    module with all necessary circuitry built. The module can be easily plugged into the breadboard and used to interface other parts. Other parts may be modules by themselves or built right on the breadboard.

    In our first few project we shall use this kind of modules on breadboard to make our life little easier. Later

  • we shall switch over to development board to make it further easier. The module shown here is from Micro-tronics Pakistan. This is based upon an 18 Pin PIC micro-controller, has 20 MHz Crystal Oscillator, an In circuit pro-gramming Header and I-O lines as well as supply lines as Breadboard plug-in header pins. The board requires 5V regulated supply. It has however a reversed polarity protec-tion diode on +5V supply line.

    We shall also use this breadboard friendly LED board that contains 8 LEDs along with current limiting resistors. The Inputs and common ground are provided as breadboard plug-in header. We shall also use the 5V regulator breadboard friendly module to supply necessary power to the power rails of the breadboard.

    PIC16F819 with 8 LEDs connected. Now I expect you to have your board ready with PIC16F819 and 8 LEDs connected to PORTB. If you have another controller like 16F877 or 18F452 it is OK. You just make the standard board with power, crystal etc. and connect 8 LEDs to PORTB. Except for definition of the controller to the MikroBasic rest of the project will be the same. The Breadboard friendly module I am using as an example has 16F819 microcon-

    troller at 20 MHz Oscillator. This figure shows the basic setup, There is a 5V regulator module taking power from a 9V battery. An 18 pin PIC16F819 microcontroller module. All I-O lines are snapped-in the breadboard. The +5V and GND lines are connected to power rails, underneath. This module has 20 MHz crystal oscillator. Notice the In Circuit programming header connected to the JDM programmer. The pro-grammer is serial based. The serial cable will be connected to programmer only when programming. When program is to be executed the serial cable, or programmer has to be disconnected, otherwise it will not free the MCLR (VPP) pin and program will not execute. We have connected the entire PORTB, 8 pins to the

  • respective LEDs on the LED module. The pin RB6 and RB7 are also named as PDC and PGD. These two pins are also used to transfer the new program into microcontroller. When a low resistance device like, an LED is connected to these pins, they may steal the data signals and programming fails. Therefore if you want to enable in circuit programming as well as want to use these pins for output, make sure that the de-vice connected does not steal the signals. Alternately you can use 1.5 to 4.7K resistors with the controlling device to limit this effect. Since our LED module has all 220 ohms resistors, we will unplug the RB7 wire while programming.

    Writing Your First Program Now we are all ready to write our first program and test it. Our First program will turn all the LEDs ON. You have already seen this program before in chapter 4. There is no harm in repeating something, and we shall take this as a beginning to more advanced programming. So Fire MikroBasic IDE, close anything that al