THE SOFTWARE, COMPILERS, AND EDITORS:PICBASIC PRO COMPILER

PICBASIC PRO COMPILER

The PICBASIC PRO Compiler (referred to as the PBP hereafter) provides all the func- tions needed to program almost the entire family of PIC microcontrollers in a BASIC- like environment. This means that it allows you to write programs that read the inputs and write to the outputs in a simple and easy to learn way. It means that communications are simplified and the time it takes to get an application running is reduced many fold. It means that the programs are easier to follow and to debug (though debugging can get quite complicated even on these seemingly simple devices). The compiler sup- ports only integer math, but that is not a big handicap when we are working with these limited microprocessors. You need to select a much more powerful microprocessor if

mathematics is a major need for your application. In our particular case, where we are running encoded DC motors, this inhibits the implementation of the differential func- tion in the PID loop, as you will see later on.

It also means that the programs that are developed are longer than assembly language programs and slower in their execution than assembly language programs. There are also complications that have to do with the use of interrupts that have to be addressed, but these are beyond the scope of this book.

All the exercises and examples provided in the text are based on the PBP compiler. We will not go over the detailed instructions for using each of the PBP instructions in the text. It is expected and will be assumed that you will have purchased the software and thus will have the manual for the compiler in hand. However, there are some commands that can be complicated to implement and we will spend time on these.

The compiler is kept current by microEngineering Labs for the latest MCUs released by the Microchip Technologies Corporation. The LAB-X1 uses the 16F877A MCU, and it is the MCU of choice though other MCUs that have a general pin-for-pin compatibility with this MCU may also be used. All the experiments and exercises in this book will use the PIC 16F877A only. The compiler addresses almost all the capa- bilities of this MCU, and we will cover the use of all the devices that are provided on the LAB-X1 board. (The 18F4331 is used for the encoder attached motors only.)

Detailed instructions for installing the software on your PC are provided in the compiler book. It is not necessary to install the software from a DOS prompt. It is much easier to install it under Windows with the Install.exe or equivalent file pro- vided in each package.

The software can be set up so that one mouse click will transfer the program from the editor to the PIC microcontroller and run the program in the PIC. In order to do this you have to add a couple of functional codes to the programmer operating system. These codes tell the programmer to load the program and execute it. Installing the software was covered in detail in Chapter 2.

A SIMPLE EXAMPLE PROGRAM USING PIC BASIC

A program that makes the LEDs blink on and off is usually the first program written by beginners. The purpose of the program is not to blink the LEDs but rather to allow you to go through the programming procedures in a simple and straightforward way and get a result that is easy to verify. Once you have the LEDs blinking, you will know that you have followed all the steps necessary to write and execute a program. Larger, more complicated programs may be much more difficult to write and debug, but they are no more difficult to compile, load, and run.

Following are the keystrokes for writing and running the Blink the LEDs program:

RUNNING SMALL MOTORS-0016

RUNNING SMALL MOTORS-0017

 

UNDERSTANDING THE MICROCHIP TECHNOLOGY PIC 16F877A:CONFIGURING AND CONTROLLING THE PROPERTIES OF THE PORTS

CONFIGURING AND CONTROLLING THE PROPERTIES OF THE PORTS

The PIC 16F877A provides 33 I/O pins distributed across five ports. Each of the ports has unique capabilities built into it. This chapter discusses the capabilities of each of the ports with special attention to these special properties.

The descriptions are cursory and are designed to provide a quick and ready refer- ence. Refer to the actual data sheet for detailed information on these ports. The data sheet provides information at a level that cannot be provided in a short introductory text like this.

PORTA

PORTA is a 6-bit wide bidirectional port with both analog and digital capability.

The general rule is that if a PIC device has any analog inputs built into it, it will come up as an analog input device on reset and startup. The PIC 16F877A has analog capability on PORTA (and PORTE), so it comes up as an analog device on startup. If you are going to use it as a digital device, you have to set register ADCON1 to

%00000111. This line of code will be seen in many of the programs in this book and is explained in Chapter 9 on using LCD displays. See Table 9.8 to see how to set the various lines in PORTA and PORTE to analog or digital. (%00000111 sets all the analog pins to digital; there are many other choices.)

The PIC 16F877A supports external access to only 6 of the 8 pins on this port. Each of the 6 pins may be set to function as an input or output by appropriately loading the TRISA register. A zero in this register bit sets the corresponding pin to function as an output and a one sets it to function as an input.

Thus setting the following:

TRISA=%00111000

would make lines A0, A1, and A2 outputs and lines A3, A4, and A5 inputs. The most significant two bits are ignored (and could be set to 1s or 0s) because PORTA has only six active lines. (However, the two ignored bits are used by the processor and can be read when necessary. We can omit this here. See data sheet, Page 43, for specific details on how Pins 6 and 7 are used by the in circuit debugger.)

Note The % symbol means that this is a binary number. We will use this binary notation throughout the book because it makes it easier to see what each bit is being set to. Bit 7, the most significant bit, is on the left, bit 0 the least significant is on the right).

The specific functions of the pins are controlled with the ADCON1 (the first A to D control) register.

All the pins have TTL level inputs and full CMOS level output drivers. This makes it easy to connect these lines directly to standard logic components, meaning that usu- ally no intermediate resistors are needed between components if TTL or CMOS com- ponents are connected.

PORTA designations are somewhat complicated. Pins A0, A1, A2, A3 (skip A4), and Pin A5 can be configured as analog inputs by setting the ADCON1 register. Pin A3 is also used as a voltage input for comparing with the analog voltage inputs. Pin PORT A4 is used for the TIMER0 input and is then called T0CK1. This is Pin 6 of the PIC, and it is used as the input pin for TIMER0 only when configured as such. It is a Schmitt-triggered input with open drain output. Open drain means that it acts like the contacts of a tiny relay that go to 0 volts when closed but float when open and not connected to anything. Schmitt-triggered inputs have increased noise immunity.

The two registers that control PORTA are TRISA and ADCON1.

ADCON1 controls the A to D and voltage reference functions or PORTA. The setting of the various bits selects a complicated set of conditions that are described in detail in Table 9.8. (In the preceding discussion when ADCON1 was set to %00000111, we were accessing this feature.)

Pin A4 has special needs when used as an output. It can be pulled down low but will float when set high. It must be pulled up with a (10K to 100K) resistor to tie it high. This pin has an open drain output rather than the usual bipolar state of the other pins. This pin is skipped in the A to D conversion table.

PORTB

PORTB is a full 8-bit wide bidirectional port.

Internal circuitry (built into the MCU) allows all the pins on PORTB to be pulled up to a high state (very weakly) by setting pin 7 of the Option Register (OPTION_REG.7) to 0. These pull-ups are disabled on startup and on reset.

Pins B3, B6, and B7 are used for the low voltage programming of the PIC. Bit 3 in TRISB must be cleared (set to 0 or pulled down to 0) to negate the pull-up on this pin to allow programming to take place. See Pages 42 and 142 in the data sheet for more information on the B3 pin. It is important to keep this in mind because if for any reason Pin B3 cannot be made low it will not be possible to program the device.

Pins B4 to B7 will cause an interrupt to occur when their state changes if they are configured as inputs and the appropriate interrupts are configured. Pins that are configured as outputs will be excluded from the interrupt feature. The interrupts are controlled by the INTCON (Interrupt Control) register. This PORTB interrupt capability has the special feature that it can be used to awaken a sleeping MCU.

Pin B0 has separate (external) interrupt functions that are controlled through the INTEDG bit which is bit 6 of the OPTION_REG. (See the data sheet for more infor- mation.) External interrupts are routed to the PIC through this pin.

The three registers that control PORTB are TRISB, INTCON, and the OPTION_ REG.

OPTION_REG controls the optional functions of PORTB as follows:

N Bit 7 of OPTION_REG sets the pull-ups; programming uses

N Bit 6 of OPTION_REG sets edge selection for interrupts; programming uses

N Bit 5 of OPTION_REG sets the clock selection

N Bit 4 of OPTION_REG sets Timer 0 input pulse edge condition

N Bit 3 of OPTION_REG sets the pre-scaler option; used in low voltage programming

N Bit 2 of OPTION_REG sets pre-scaler value N Bit 1 of OPTION_REG sets pre-scaler value N Bit 0 of OPTION_REG sets pre-scaler value

PORTC

PORTC is a full 8-bit wide bidirectional port.

All the pins on PORTC have Schmitt-trigger input buffers. This means that they are designed to be more immune to noise on the input lines.

The alternate functions of the PORTC pins are defined as follows:

N Pin C0 I/O pin or Timer1 oscillator output or Timer1 Clock input

N Pin C1 I/O pin or Timer1 oscillator input or Capture 2 input or Compare 2 output or Hardware PWM2 output

N Pin C2 I/O pin or Capture 1 input or Compare 1 output or Hardware PWM1 output

N Pin C3 I/O pin or Synchronous clock for both SPI and I2C memory modes

N Pin C4 I/O pin or SPI data or data I/O for I2C mode

N Pin C5 I/O pin or Synchronous serial port data output

N Pin C6 I/O pin or USART Asynchronous transmit or synchronous clock

N Pin C7 I/O pin or USART Asynchronous receive or synchronous data

Special care has to be taken when using PORTC’s special function capabilities in that certain of these functions will change or set the I/O status of certain other pins when in use, and this can cause unforeseen complications in the function of other capabilities. See the data sheet for details.

The register that controls PORTC is the TRISC register. No other registers are involved. DEFINEs are used to control certain functions. (Using the DEFINEs is cov- ered in the PROBASIC PRO compiler language manual. This is the manual for the language we will be using to program the PIC 16F877A. The manual is provided, as a part of the compiler documentation, by microEngineering Labs.)

The speaker on the LAB-X1 board is connected to pin C1, so the use of this pin is limited because the noise generated by the speaker when this pin is used can be very irritating. Since this is one of the lines that allows the generation of continuous back- ground PWM signals (HPWM 2), it compromises the clean use of this pin unless the speaker is removed. However, I recommend that you avoid modifications to the board if you can. The load of the tiny speaker loads the pin and can compromise a few other uses but is okay for most uses.

PORTD

PORTD is a full 8-bit wide bidirectional port.

All the pins on PORTD have Schmitt-trigger input buffers. This means that they are designed to be more immune to noise on the input lines.

PORTD can also be configured as a microprocessor port by setting PSPMODE TRISE.4 to 1. (Note that you are specifying bit 4 of PORTE here internally; there is no external pin 4.) In this mode all the input pins are in TTL mode.

The alternate function of the PORTD pins are defined as follows:

N Pin D0 or parallel slave port bit 0 N Pin D1 or parallel slave port bit 1 N Pin D2 or parallel slave port bit 2 N Pin D3 or parallel slave port bit 3 N Pin D4 or parallel slave port bit 4 N Pin D5 or parallel slave port bit 5 N Pin D6 or parallel slave port bit 6 N Pin D7 or parallel slave port bit 7

The registers that control PORTD are the TRISD register and the TRISE register. TRISE controls the operation of the PORTD parallel slave port mode when Bit PORTE.4 is set to 1. (Again, only pins E0, E1, and E2 are available external to the MCU on PORTE.)

Slave port functions as set by PORTE when Bit PORTE.4 is set to 1 are as follows:

N Bit TRISE.0 direction control of Pin PORTE.0 / RD / AN5 N Bit TRISE.1 direction control of Pin PORTE.1 / WR / AN6 N Bit TRISE.2 direction control of Pin PORTE.2 / CS / AN7 N Bit TRISE.3. NOT USED

N Bit TRISE.4 Slave port select, 1 = Port selected, 0 = Use as standard I/O port

N Bit TRISE.5 Buffer overflow detect, 1 = Write occurred before reading old data, 0 = No error occurred

N Bit TRISE.6 Buffer status, 1 = still holds word, 0 = has been read

N Bit TRISE.7 Input buffer status, 1 = full, 0 = nothing received

Read the data sheets to get a better understanding of these operations. The preced- ing list is a very quick overview and is intended only to alert you and to give you an idea of what the possibilities are.

PORTE

PORTE is only three external bits wide and is a bidirectional port. The other bits are internal and are used as mentioned in the PORTD section (to which they are related). The pins on PORTE can be configured as analog or digital.

All the pins on PORTE have Schmitt-trigger input buffers.

The alternate function of the PORTE pins are defined as follows:

N Pin RE0 direction control of Pin PORTE.0 / RD / AN5 N Pin RE1 direction control of Pin PORTE.1 / WR / AN6 N Pin RE2 direction control of Pin PORTE.2 / CS / AN7

TIMERS

The three timers in the PIC 16F877A allow the accurate timing and counting of chronological events. Timers are discussed is much greater detail in Chapter 6, which is devoted exclusively to timers and counters. A fourth timer provides a watchdog function. Each timer occupies a 1- or 2-byte location in the memory.

Some of the timers have pre-scalers associated with them that can be used to multi- ply the timer setting by an integer amount. As you can imagine, the scaling ability is not adequate to allow all exact time intervals to be created. You also have to consider the uncertainty in the frequency of the clocking crystal, which is usually not exactly what it is stated to be and may drift with its temperature. This means that though fairly accurate timings can be achieved with the hardware as received, additional soft- ware adjustments may have to be added if more accurate results are desired. You do this by having the software make a correction to the timing every so often. (This also means that an external source that is at least as accurate as the result you want is needed to verify the timing accuracy of the device created.)

The three timers in the microcontroller are clocked at a fourth of the oscillator speed, meaning that a timer using a 4 MHz clock gets a counting signal at 1 MHz.

Very simply stated, an 8-bit timer will count from 0 up to 255 and then flip to 0 and start counting from 0 to 255 again. An interrupt occurs every time the timer reg- isters overflows from 255 to 0. You respond to the interrupt by doing whatever needs to be done and then resetting the interrupt flag. On timers that permit the use of a prescalar, the prescalar allows you to increase the time between interrupts by multi- plying the time between interrupts with a definable value in a 2-, 3-, or 4-bit location. On timers that can be written to, you can start the counter wherever you like to change the interrupt timing; on timers that can be read, you can read the contents whenever you like. For example, a 1-second timer setting with a prescalar set to 16 would provide you with an interrupt every 16 seconds. You will have 16 seconds to do whatever you wanted to do between the interrupts before you will miss the next interrupt.

If you needed an interrupt every 14.5 seconds, you would use a timer set to 0.5 seconds and a prescalar of 29, if 29 was specifiable (which it is not here). So not all time intervals can be created with this strategy because there are limits as to what can be put in the timer and what can be put in the prescalar when you are using 8-bit registers and specific oscillator speeds.

Pre-scalers The value of the scaling factor that will be applied to the timer is deter- mined by the contents of 2 or 3 bits in the interrupt control register. These bits multiply

the time between interrupts by powers of 2 as explained in Chapter 6. Pre-scalers and post-scalers have the same effect on the interrupts: they delay them.

Watchdog Timer A watchdog timer sets an interrupt when it runs out to tell you that for some reason the program has hung up or otherwise gone awry. As such, it is expected that in a properly written program the watchdog timer will never set an inter- rupt. This is accomplished by resetting the watchdog timer every so often within the program. The compiler does this automatically if the watchdog timer option is set. Setting the option does not guarantee a program that cannot hang up. Software errors and infinite loops that reset the timer within them can still cause hangups.

Counters Both Timer0 and Timer1 can be used as counters. Timer2 cannot be used as a counter because it has no internal or external input pin. The timers and the counters are covered in detail in Chapter 6.

The following address and web sites may be used to contact Microchip Technologies. The website provides downloads for the data sheets.

Microchip Technology Corporation, Inc. 2355 West Chandler Boulevard Chandler, Arizona 85224-6199

phone: (480) 792-7200

fax: (480) 899-9210

Website: www.microchip.com

microEngineering Labs maintains a very useful and helpful web site that will also be a tremendous aid to you as you learn about the PIC microcontrollers by using their LAB-X1. They can be reached at:

microEngineering Labs Inc. Box 60039

Colorado Springs, CO 80960-0039 or:

microEngineering Labs 1750 Brantfeather Grove

Colorado Springs, CO 80960 phone: (719) 520-5253

fax: (719) 520-1867

e-mail: support@microengineeringlabs.com Website: www.microengineeringlabs.com/index.htm

 

CONTROLLING THE OUTPUT AND READING THE INPUT

In this chapter we will learn how we interface an MCU to the real world by first learn- ing how to create outputs with the microprocessor and then learning how to read inputs into the microprocessor. In following chapters we will combine the outputs and the inputs to control the operation of small motors of all kinds.

All the programs that we will be discussing are provided on the support web site for this book. You can copy them from the site to run them. The exercises listed at the end of various chapters are designed to increase your familiarity and competence with the 16F877A. The answers to them are not provided.

In preparation for writing programs, set up the LAB-X1 so that it can be pro- grammed with one mouse button click or by pressing F10 as is described in detail in Appendix A.

The I/O that uses ICs in the seven empty sockets on the LAB-X1 board is covered separately in Chapters 7 and 8. These chapters also cover one wire memory, A to D converters, and a number of thermometric devices.

The I/O that uses the serial port (as RS232 or RS485) is covered in Chapter 8. Specifically, this covers communications between the PIC 16F877A and personal computers.

We will learn about input and output by writing simple programs that control the outputs and read the inputs. We will learn how to control the outputs first because this can be done directly from the software without need for any input or any external hardware. Once we can control the output, we will learn how to read the inputs and make them interact with the output.

The following are output programs to be developed:

N A program to blink one LED on the bar graph.

N Blink all eight LEDs in the bar graph consecutively.

N Dim and brighten one LED.

N Write “Hello World” to the LCD on its two lines.

N Write binary and decimal values to the LCD.

N Output a simple tone on the speaker.

N Output a telephone tone signal on the speaker.

N Advanced: Move an R/C servo back and forth.

The following are input programs to be developed:

N A program to read the first column, first row button, and turn on one LED while this button is down.

N Read the entire keyboard and display the binary value of the row and column read on the LCD.

N Read the keyboard and display decimal key number on the LCD.

N Read one potentiometer and display its 8-bit value on the LCD in binary, hex, and decimal notation. Also display the binary value on the bar graph.

N Read all three potentiometers on the LAB-X1 and display their values on the LCD.

N Advanced: Use the three potentiometers on the LAB-X1 to control an R/C servo.

Control the location of the center position, the limit position of the end positions, and the rate of movement. Use three switches on the keypad to move the servo clockwise, center the servo, and move it counterclockwise.

 

THE SOFTWARE, COMPILERS, AND EDITORS:PICBASIC PRO TIPS AND CAUTIONS

PICBASIC PRO TIPS AND CAUTIONS

1. To get context sensitive help, move the cursor over a PICBASIC command, click to set cursor and press F1.

2. All the programs assume the PIC is running at 4 MHz. To change the default setting (for example, to 20 MHz), simply add DEFINE OSC 20 at the top of your program and set the jumpers on the LAB-X1 accordingly. It is good practice to always specify the oscillator speed in a program. Beginners should start with 4 MHz designs. The LAB-X1 is set up to run at 4 MHz as received from the factory. See the PBP manual for further details of assumptions and conventions used by the software. The defined OSC speed has to match the hardware crystal for the software to work correctly.

3. Before you can use the LCDisplay on the LAB-X1, ADCON1 must be set (to %00000111) and you must pause about 500 ms to allow the LCD to start up before issuing the first command. You may not need a pause, or a shorter pause may be specified if there are a lot of time consuming instructions before the first LCDOUT instruction is executed. (Other values of ADCON1 can also be used depending on how you want the A and E ports configured. See discussion in Chapter 9 on using the LCD.)

4. I have used binary notation (%01010101) throughout the book to set relevant bytes and registers so that you can readily see which bit is being set to what. The compiler

accepts hexadecimal and decimal notation just as willingly. Binary notation does not permit a space after the % sign and all eight bits must be specified.

5. A single quotation mark (‘) when copied from a Word file and pasted into the MicroCode Studio editor will be interpreted as a (`) and will therefore not properly start the comment part of the line. All these have to be changed in the editor after pasting. Pasting from the editor into Word does not exhibit the same effect. If you use a semicolon (;) for the comments, this problem does not occur.

6. All the named registers can be called by name when using the compilers. The register names are the same as those used (defined) by the manufacturer in the data sheets and are the same across the entire family of PIC microcontrollers if they provide the same function. Uppercase or lowercase names can be used. The DEFINEs must be stated in uppercase only and the spellings in the DEFINE lines are not always checked by the compiler! Be very careful when entering DEFINEs into your program.

7. Circuits and segments of circuits are provided throughout this book to show you how to connect up to the hardware when you design your own circuits. If you have access to AutoCAD you can use the diagrams in the files on the support web site to cut and paste into your own designs.

A FREE DEMO BASIC COMPILER

A free version of the PIC Basic Pro compiler by microEngineering Labs can also be downloaded from the microEngineering Labs web site. This is a fully functional com- piler with the limitation that programs are limited to 30 lines of code. This is enough to allow you to test the compiler and any instruction that you might have a special interest in. This version can give you a good idea of the power and ease of use of the language. Try it.

 

UNDERSTANDING THE MICROCHIP TECHNOLOGY PIC 16F877A:THE POT COMMAND

THE POT COMMAND

The compiler provides the POT command to make it easy to read the resistive load placed on a pin. See the PICBASIC PRO manual for details. In order to use this com- mand, it is necessary to set up the connection to the Lab-X1 as follows:

1. Set up the MCU for analog mode.

2. Select the pin to be used for input.

3. Select what the excitation voltage source will be (internal or external).

There are only 16 pins that may be used with the POT command, and they are the 16 pins that have been assigned the aliases from PIN0 to PIN15. These are assigned in the include file BS1DEFS.BAS. For the 16F877A, these are the pins on PORTB (0 to 7)

and PORTC (8 to 15). There are different designations for the different MCUs based on the pin count. See Section 4.11 in the PICBASCIC PRO manual for a discussion of how the pin numbers are assigned for each PIC device.

The POT command is:

POT pin, scale, NBR.

The value of these variables is as follows:

N Pin is the pin number we have been discussing.

N Scale is the adjustment for various RC constants. If the RC constant is large, the value of scale should be small. Scale is determined experimentally with a potenti- ometer in place of the resistive load. At the low end of the resistance the value of scale should be 0, and at the high end it should be 255.

N NBR is the variable the result will be placed in.

Values between 5 and 50K ohms may be read with a 0.1 L F capacitor as shown in the Compiler manual under the POT command.

CAPACITANCE

Capacitance can be measured by determining how long it takes to charge a capacitor through an accurately calibrated resistor or by setting up an oscillator with the two components and measuring its frequency.

VOLTAGE

Voltage is measured by setting up an appropriate dividing network with precision resistors and measuring the voltage across an appropriate resistance.

FREQUENCY

The PIC 16F877A can measure frequencies directly. The timers and counters within the MCU are used to set the measurement intervals and counting hardware.

READING SWITCHES

Switches can be read from the lines of any port that is set up as an input port. Debouncing must be performed either in hardware or in software to avoid false read- ings. (See BUTTON command in the PICBASIC PRO manual.)

Make sure that other hardware that may be connected to the pins does not interfere with the switch function and its detection.

Reading Switches in a Matrix

Switches arranged in a matrix can be read by setting and reading the rows and columns in the matrix. The technique activates a row of buttons at a time by making it high or low and then seeing if any of the columns has been affected. A detailed description

of how this is done is in Chapter 5, which discusses the keyboard of the LAB-X1 in detail.

 

GETTING STARTED:THE PROGRAMMERS

THE PROGRAMMERS

microEngineering Labs offers three programmers. One uses the parallel port, one uses the USB port, and the third uses the serial port. The operation of the three pro- grammers is almost identical as far as the user interface is concerned. In this book we will use a USB programmer for all our experiments; this is what I used. The new USB programmer is more convenient to use than the other programmers because it does not need a power supply; it gets its power from the USB port. An important bonus is that it frees up the COM port for use with the computer (the parallel pro- grammer does this also).

BUILDING A PROGRAMMER

There are a number of plans on how to make inexpensive programmers on the internet, but I am not going to recommend any of them because I have not built any of them.

USING THE PROGRAMMERS

The USB programmer does not need a power supply or wall transformer. It gets its power from the USB port. Using a USB port frees up the serial port for your experi- mentation and this is important because most of the new computers have only one serial port. The PC serial port connects to the LAB-X1 serial port for certain uses.

For the serial port and parallel port programmers, first plug the 16-V power cord connector into the programmer and then into the wall socket. The USB programmer needs to be connected but does not need a power supply connection. If you do not have power to the programmer when you start the programming software, the soft- ware will not be able to see the programmer and an error message will be displayed: the software will report that it could not find the programmer.

It is best to start the programmer software from the MicroCode Studio Editor win- dow. If you do it this way the microcontroller being used is selected automatically and the program you are working on in the MicroCode Editor window is transferred auto- matically to the compiler software and onto the MCU on the LAB-X1 board. It can all be set up to be a one-click operation. See Appendix A.

If you are programming an MCU that is not on the LAB-X1, insert the microcon- troller into the programming socket immediately before you begin programming the microcontroller. This applies only if you are programming a loose microcontroller. If you are programming a microcontroller plugged into the LAB-X1, it can be left in the board all the time.

Caution The only exception for the parallel port programmer is that the B7 pin is pulled low by this programmer and will interfere with your program if you are using the B7 pin. If you are going to be using this pin, you must unplug the program- mer between programming sessions.

The sequence to create a program inside a microcontroller is as follows:

1. Write program in the MicroCode Studio Editor environment.

2. Compile the program.

3. Program the device.

4. Use the device.

The last three steps can be combined into one keystroke. See Appendix A.

 

UNDERSTANDING THE MICROCHIP TECHNOLOGY PIC 16F877A:USING THE A TO D CAPABILITIES OF THE PIC 16F877A

USING THE A TO D CAPABILITIES OF THE PIC 16F877A

A to D conversions will be discussed in more detail in Chapter 5. There are a number of basic measurements that you can make with the LAB-X1 board by using its analog-to-digital and other capabilities. These form the basis for the inputs that you can use to control the motors. The resolution of the A/D conversion can be 8 or 10 bits. Still higher resolutions are available if you use ICs that go in empty socket U6. The measurements that we make can be used to determine the following:

N Resistance N Capacitance N Voltage

N Frequency (not an A to D function, of course)

Resistance is measured by measuring how long it takes a resistor to discharge a capacitor that has just been charged. The measurement is as accurate as the value of the capacitor. The measurement parameters may need to be adjusted in real time to get a usable reading (meaning that the value of the two components has to be selected to get a reading in a reasonable time with reasonable accuracy).

If the relative position of the wiper on a variable potentiometer is required, the A to D conversion capabilities of the LAB-X1 can be used to read the potentiometer wiper position (not the resistance). The A to D converter always measures the voltage across the device that you connect to the analog input port. You have the choice of reading the value to a resolution of either 8 or 10 bits. If you are reading an 8 bit A to D value, the value across the resistance is divided into 256 divisions and the reading will always be between 0 and 255. If you are doing a 10-bit A to D conversion, the value will be between 0 and 1023, but since one byte can hold only 8 bits, the remaining 2 bits have to be read from another register. This is explained in greater detail in Chapter 5 in the section on setting up A to D conversions for the IC in socket U6.

 

INTRODUCTION TO MICROENGINEERING LABS’ LAB-X1 EXPERIMENTAL BOARD:ANOTHER INTERESTING BOOK AND A FAST INTERNET CONNECTION IS A MUST

ANOTHER INTERESTING BOOK

David Benson of Square 1 Electronics wrote a very interesting and useful book on the PIC 16F84A called Easy Microcontrol’n (this book used to be called Easy PIC’n) that supports these investigations. It taught me a lot of things I did not know and had not even thought about. In this workbook you will reap some of the benefits of my learning expe- rience. I recommend that you get a copy of Easy Microcontrol’n to support your use of the PIC 16F84A. It has a lot of very useful information in it and will save you a lot of time and headaches. However, the book is comparable to a first course at the commu- nity college level, and I found it too dry, with the emphasis on doing things without a BASIC compiler. A BASIC compiler is the easy to use tool of choice in this workbook because of our interest in getting things done in a hurry as opposed to becoming PIC/ MCU experts in assembly language. The emphasis here is more in applied results rather than rigorous foundation level learning of assembly language programming. This does not in any way negate the usefulness of Benson’s book to those interested in understand- ing and using the PIC 16F84A and similar microcontrollers.

Caution All the programs in Benson’s book are in Assembly Language.

A FAST INTERNET CONNECTION IS A MUST

You absolutely must have an Internet connection because so much of the information you need is on the Internet. It is very helpful to have more than a standard phone line connection so get the fastest connection you can afford. A cable modem is strongly recommended. If you and a couple of neighbors can get together and form a local area network (LAN) and share a wireless (Wi-Fi) modem setup, it becomes a really inex- pensive way to get fast Internet service. The Wi-Fi signals have no problem reaching all the apartments in a small building and sometimes even the house next door. Amplifiers and repeaters are available to increase signal strength where necessary.

DOWNLOADING DATA SHEETS

One of the first things you need to download is the data sheets for the PIC 16F87X. You will in all probability end up using the smaller and less expensive PIC 16F84A for a lot of your initial projects, so it might be a good idea to download the information for that microcontroller while you are at it. As mentioned before, these files are avail- able from the Microchip web site and the information is free. However, the two docu- ments are about 400 pages all together, so you probably will not want to print it all out. You will, however, want to print some of the more commonly used information so you can refer to it whenever necessary. The rest should be stored on your computer so that you can call it up or search for what you need when you need it.

The Microchip Technology Corporation website is at www.microchip.com.

Finding what you need will be under “support” on their web site, and it is easy to download. Just follow the instructions provided on the site.

 

GETTING STARTED:LOADING THE SOFTWARE

LOADING THE SOFTWARE

The following software will be provided with the various components that you will acquire as you learn about using microcontrollers based on the experimental boards provided by microEngineering Labs.

N PICBASIC PRO compiler software and book.

N USB port programmer (or whatever programmer you are using) software and book

N MicroCode Studio (the editor) on CD ROM or downloaded from the Internet.

The DOS environment is archaic and can be difficult for users not familiar with it. You do not have to deal with DOS to use and enjoy the hardware and software that we will be using. Everything can be done from the Windows environment.

Note If you need to use DOS, there is a chapter at the beginning of the manual that tells you what you will need to do.

The PICBASIC PRO compiler manual covers the use of the software in the DOS environment. I suggest that you ignore the first pages of the book and instead read the following section on how to run everything under the Windows environment. Once you are familiar with how the system works, you can go back and learn how to use the software in the DOS environment. There are a number of things that the DOS environ- ment provides that can be useful and you will want to know about these as you get more and more proficient in your use of the microcontrollers.

USING THE SOFTWARE IN THE WINDOWS ENVIRONMENT

The first question that needs to be answered in almost every endeavor is always: “What do I need, what do I have to do, and what will it cost me to get the job done?” Accordingly, we will address this now.

Let’s assume that you already have an IBM-PC with a suitable Windows operating system and that you know how to use it. Your computer needs the following capabilities to allow you to access the hardware and software that you are going to use it with.

In this book I will deal exclusively with the IBM-PC in a Windows environment. The software is not available for the Macintosh. Here is what you need:

N A 3.5 inch floppy drive or CD ROM (as of this writing some of the software is provided on 1.4 Mb, 3.5 inch floppies only and you must read it off a diskette for the system to work right. You cannot copy the software to a CD ROM and work from there; it will not work.) If your software comes on CDs, you can ignore this.

N A hard disk with about 5 MB of free space for software storage and as a general workspace.

N A serial port (COM1 or COM2) if you will be using the new serial programmer, and a USB port if you will be using the USB programmer. The USB programmer has the advantage of not needing a wall transformer based power supply because it takes its power from the USB port.

N LAB-X1 Experimenters board ($195); 16F877A microcontroller (not part of Lab-X1) ($10).

N USB programmer ($120).

N PICBASIC PRO compiler ($250).

N Miscellaneous motors and electronic items for experimentation ($70) allowance.

The allowance for the motors and electronic parts also covers the need to purchase memory- and time-based components that are socketed for but are not listed. You may decide that you do not need to experiment with some of these at this time. The allow- ance provides for almost everything you need for your motor experiments.

microEngineering Labs also provides a number of other preassembled boards for experimentation and educational purposes that you should be aware of:

N Lab-X1 Experimenter’s board, which we are discussing

N Lab-X2 Experimenter’s board for custom circuits N Lab-X20 Experimenter’s board for 20-pin devices N Lab-3 Experimenter’s board for 18-pin devices

N Lab-4 Experimenter’s board for 8 and 14-pin devices

N Lab-XT Experimenter’s board for telephone technology–related investigations

N Lab-XUSB Experimenter’s board for building USB interfaces and peripherals

In this book we will consider the LAB-X1 only. This board provides a 2-line by 20-character display, which is very useful in the learning environment because it can allow you to see what is going on in the system as you experiment (if you program your programs to do so). Since almost all the microEngineering Labs boards provide similar features, learning transfer to the other boards is high.

Start out by opening a new folder on your desktop and labeling it LAB-X1 Tools. You will store everything that has to do with all your projects in this folder. You are opening this folder on the desktop now, but you can move it to wherever you like in the future. For now, you don’t have to make a decision about where to locate the

folder, and it is right in front of you when you start your computer and the desktop appears.

Open the LAB-X1 Tools folder and create new folders, one for each of the items or applications we will be working with in this folder. Name these folders as follows:

N MicroCode Studio

N USB Programmer (or whichever programmer you decide on)

N PICBASIC PRO compiler

N LAB-X1 and related information Then follow these steps:

1. Put the MicroCode Studio CD in the disk drive and open it.

2. Copy all files to the MicroCode Studio folder.

3. Eject the CD and put it away in a safe place.

4. Put the programmer diskette in the disk drive and repeat the steps that were taken above for the software in this package. Repeat the process for all the diskettes.

5. Put a shortcut for the MicroCode Studio program on your desktop. This is the only shortcut you need when you want to create programs for your MCUs. All other functions of the system can be accessed from the window of this editor.

As a general rule, you will never see the compiler as such. It is called from the MicroCode Studio Editor screen, it works on compiling the program it is asked to compile, and then it disappears into the background ready for the next compilation request. The errors that are displayed after a compilation are generated by the com- piler. If all goes well, there are no errors and you get a message telling you that the compilation was successfully performed. The new hex file just generated will appear in the directory listing the next time you open a file. The hex file will have the same name as the text file that it was compiled from. The PICBASIC PRO compiler manu- al covers how all this is done in more detail.

Source file Untitled.bas

hex file Untitled.HEX

It should be noted that the hex file is not created until all the syntax errors the com- piler can find have been eliminated by you. After a successful compilation of the code there may still be errors in the programming itself that will need to be addressed as you debug your work. Now go to the microEngineering web site (www.microEngi- neering Labs.com/index.htm) and download the information on the LAB-X1 experi- menter board to your computer and put it in the LAB-X1 Tools folder. There are a number of very useful example programs in these files, and cutting and pasting from these to programs that you are writing will save you a lot of time. These programs are also on the support web site.

If you are familiar with and have information for the Basic Stamp, it would be a good idea to also add these files to this folder so that all your microcontroller information is

in one place. If you have a CD burner on your computer (and if you do not you should get one), it is well worth your time to now copy the entire unadulterated LAB-X1 Tools folder to a CD for safekeeping. Data on a CD is much more secure than the data on a floppy drive and the best time to make a copy of it is right now before you make any changes to any of the data that you received from the vendors.

For the purposes of general discussion and experimentation, we will always call the example program that is being manipulated Untitled and the text file that is the body of the program will be called Untitled.bas.

This is the file that the compiler compiles for the microcontroller you are using to create the hex file.

The hex file that is created from this program by the compiler will be referred to as Untitled.hex. We do it this way because every time you compile and run a program the system automatically saves the program to disk at the same time. This means you lose the old program and cannot go back to it. If you are working with a complicated program, this can become a real problem because there are lots of good reasons to go back to the way things were. To avoid this pitfall, every time you load a program from disk, first save it as Untitled.bas and then play with it all you want. When you have a viable program, save it to the name that is appropriate for it. Then load the next pro- gram and change its name to Untitled.bas, and so on. I even recommend that you save each version of your program with a version designation so that you work on Blink. bas as Untitled.bas and resave it to disk as BlinkV1.0.bas; then you work on BlinkV1.0.bas as Untitled.bas and resave it as BlinkV1.1.bas, and so on. Though there is some tedium in doing this, I can assure you that it will save you a lot of headaches in the long run.

Note The hex files created by the PBP compilers can be loaded into the PIC microcontrollers with other software/loaders. It is not imperative that hardware programmers be used.