dragon’s lair electronics primer.pdf · introduction this paper was set up as an introduction to...

36
Dragon’s Lair Electronics Pic Primer

Upload: vanhanh

Post on 08-Aug-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Dragon’s LairElectronics

PicPrimer

Page 2: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

INTRODUCTION

This paper was set up as an introduction to programming Pic Microcontrollers using MicroEngineering Labs PicBasic Pro. when I started playing around with pics, I had a hard timefinding code that actually worked, I would type everything in exactly as shown, but nothingever seemed to work, at the time I thought it was something I was doing wrong, but now Irealize that it was not me but the code, that was wrong. Most of the code I could find wasmissing important information, like how to set the registers on the Pic, or the code was writtenfor PicBasic not PicBasic PRO, many of the “examples” on some website are like this.(anything with SYMBOL is PicBasic, PicBasic Pro uses VAR statements) I also found it nextto impossible to find any diagrams to show you how to hook things up to the Pic, so Idecided to write a small manual to help beginners with programming the Pics, the result is thismanual.

Here is a list of the parts (and some suppliers) you will need to do the projects in this manual

1 - Chip puller Circuit Test # CT-6201 - Solderless Breadboard & wire jumpers Circuit Test # MB-102J1 - 5 volt power supply Circuit Test # RP0530R-P1 - LCD Display Newark/Digikey AND491GST-LED2 - SPST Off-(On) momentary switches (switch1 & switch2 )1 - SPDT On-On switch (switch3)1 - PC mount 5 pin DIN socket1 - 4 mhz crystal oscillator1 - 20 mhz crystal oscillator2 - 15 to 20 pf (pico farad)ceramic capacitors1 - .22 uf (micro farad) ceramic capacitor1 - 5k potentiometer Newark/Digikey Bourns 91A1A-B28-B151 - 10k trimpot for LCD contrast Newark/Digikey Bourns 3386P-1-10310 - 220r resistors10 - 4k7 resistors8 - 5 mm LEDs (any color)1 - 5 mm Infrared Emitter (LED)1 - Infrared Photo module (36 khz detector) Newark/Digikey Vishay TSOP18361 - Buzzer Mode # 61-223-01 - Small speaker1 - hobby servo1 - Pic16F6281 - Pic12F675A piece of straight header pins (Mode # 36-140G-0) Solder this into the holes of the LCDdisplay, then you can just plug the display into your prototyping board.Most items should be available at any electronics supplier, Digikey, Mouser, Radio Shack etc.Try to get the Bourns pots, they have straight pins that will plug right into the board, also try tofind switches that can be plugged into the board, otherwise solder some of the jumper wires tothe pins, so you can plug them into the board.

Pictures of some of the finished projects can be seen at

www.dragonslair.ca

Page 3: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Reading Registers

Interpreting the registers can be a bit confusing at first, but once you get used to them, they arefairly easy to figure out. The TRIS ant PORT registers are pretty basic, the TRIS register iseither an input (1) or an output (0)TRISA = %00000000 sets all the pins (bits) of PORTA to outputs andTRISA = %11111111 sets them all to inputs, as we stated earlier, the pins all default toinputs at power up. You can also set the pins individually -TRISA.5 = 0 would set pin 5 to an output, and leave the rest as inputsThe PORT register is either Low (0) or High (1), low being grounded (off), and high being +5v(on)PORTA = %00000000 sets all the pins on PORTA as low,You can also set them individually -PORTA.5 = 1 sets pin 5 to a high (on) stateThe rest of the registers are a little more complicated, each bit controls a different aspect of theregister. In our programs we used the CMCON and OPTION_REG registers, so I will use themas examples.If you look at the OPTION register for the PIC16F628 (page 20 of the data sheet) you can seewhat each bit controls, we wanted to enable the internal pull-up resistors on PORTB, so welook at theoption register and see that bit 7 is the one that enables them, so we ad the lineOPTION_REG.7 = 0to turn them on. If you check the “SUMMARY OF REGISTERS ASSOCIATED WITHPORTB” (page 41 of the data sheet) you can see what all the register bits default to. In thecase of the OPTION register they all default to “1”, so we could also use the formatOPTION_REG = %01111111 to enable the internal pull-ups.In the case of the CMCON register, we want to disable the comparator module. If you check theCMCON register (page 53 of the data sheet) you will see that we have to set 3 bits to changethe comparator mode (bits 0-1-2 ), now we go to the comparator modes chart (page 54 of thedata sheet) and see that to turn the comparators off, we have to set bits 0-1-2 to “1” If youcheck the “SUMMARY OF REGISTERS ASSOCIATED WITH PORTA” (page 34 of the datasheet), you will see that the CMCON register defaults to all “0” so we use the formatCMCON = %00000111 to disable them. If you only need to change 1 bit, then just specify itOPTION_REG.7 = 0, if you need to change more than 1 bit, then change the bits you need to,and leave the rest at their default settings CMCON = %00000111

Design Considerations

When designing electronic circuits for the Pic Microcontrollers, there are a few things you cando to minimize problems.The first thing is to have a good power supply, I always use a small bridge rectifier at my powerinputs, a DB101 works well here, it can handle any voltage we will be using, and is rated up to1 amp current draw, this way it does not matter if someone hooks the power up backwards, oruses an AC power source. From there I go into a LM1705 voltage regulator, they are rated up to30 volts and 1 amp (with heatsink). Be sure to use adequate filtering on the power supply.You should always place a .1uf capacitor between the +5v and ground on the chip, keep it asclose to the pins on the chip as possible, this will help to filter out small spikes that could affectthe operation of the microcontroller. I don’t generally use them on the prototyping board, unlessI am having problems, but I always use them when I make my circuit boards.

Page 4: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

The solderless breadboard has power rails down each side Red = + , Blue = -The breadboard has a slot down the middle that divides it into 2 parts with power rails on eachside Each row of 5 holes perpendicular to the center slot are connected, which means that youwould plug your Pic in so that it straddles the slot, then you would have 4 points left to connectto each pin. The power rails are connected for the full length.

NEVER CONNECT THE PIC TO ANYTHING OTHER THAN +5V AND GROUND

Here is a picture of basic setup #3on the proto board. I mounted theproto board to a piece of plexi-glass and added binding posts forthe power connections.The littleboard on the left is a 5v powerregulator, so I can use any powersupply on it.

Basic Pic MicrocontrollerSetups

There are a few ways you can set up your Pic, mostpics default to OSC “XT” and MCLR to “enable”

1 - Power and ground, set OSC to “INTRC I/O” andMCLR to “DISABLE” This is the simplest way forwiring, but you have to remember to set your configu-ration bits at programming time, use this method to getthe maximum number ofusable I/O pinsThe internal oscillator is fixed at 4mhz

2 - Power, ground and Master Clear, set OSC to“INTRC I/O” Use this method if you don’t want toworry about setting MCLR at programming time, or ifyou want to have an external reset button

3 - Power, ground, Master clear and anexternal oscillator, Set OSC to XT or HSUse this method if you want to use an externaloscillator and have an external reset.The external oscillator can be anything from 4mhz to20mhz (this is the method we will be using)Alternately, you can use a ceramic resonatorinstead of the crystal oscillator, in which case you donot need the 20pf capacitors, connect the two outsidepins of the resonator to the osc1 and osc2 pins, and thecenter pin to ground.(the resonator has the capacitorsbuilt in)

Page 5: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Setup

To get your board ready, run a wire from the +5v post to the 5v rail (the red strips) on each sideof the breadboard, then run a wire from the ground post to the ground rail on each side of thebreadboard (the blue strips) we will be using this setup for all our projects, so you can leavethem connected.

Flash That LED!

For our first project we will make an Led flash on and off , some of you may think this is adumb program, but bear with me, you will learn a lot of techniques and concepts in this section,that can be applied to other programs, here is the schematic. We will be using an external oscil-lator and master clear for this one.

Place a wire from VDD to the +5v power rail and another from VSS to the ground railUse the 4mhz crystal for now, plug it into your board at osc1 and osc2 and plug a 20pf capaci-tor from osc1 to ground and osc2 to ground, then take a 4k7 ( yellow-violet-red) resistor fromthe MCLR pin to the +5v power rail, next take a 220 ohm resistor from Portb.0 to the + side ofa LED and put the - side of the LED to the ground rail.

Page 6: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Now for the programming, start MPLab and open a new project, go to Configure / Device andselect 16F628 as your processor, don’t worry about any configuration bits for now.

The first thing we have to do is set our TRIS register, The 16F628 has two PORTS so it has twoTRIS registers TRISA and TRISB, the Pic defaults to all pins as inputs, we are not usingPORTA so we will not worry about it right now, we will be using PORTB.0 as our outputso we have to set it as so.Each PORT on the 16F628 has 8 bits marked as PORTx.0 to PORTx.7.

TRISB = %00000000 ‘ this will set all of PORTB to outputs (any text after a ‘ is a commentand is not used by the compiler)

Alternately, you could just set the port we are using to an output, there are 2 ways of doing this

TRISB = %11111110 orTRISB.0 = 0

Notice that PORTB.0 is the last one in the list? each port has 8 bits numbered from 0-7but they are listed in reverse order, thus they read like this

PORTB.7-6-5-4-3-2-1-0TRISB.7-6-5-4-3-2-1-0

All the ports and registers are read this way, it’s just one of the things you have to get used to.

Now that we have our ports configured, we can write our program. There are a couple ofways to do this, we could set the port bit to a high state -

PORTB = %00000001 orPORTB.0 = 1

Or we could use the PicBasic Pro command HIGH

HIGH PORTB.0

Which method you use will depend largely on what you are using the other pins on the port for.If you are only turning on the LEDs, then the first method is the best, with this method youcan control all 8 pins on a port with one command.If you are using any of the other pins as inputs, or to control other things, then you should usethe second or third method.Using the HIGH command works well if you originally set the pin as an input, because it willautomatically set the pin as an output.For our program we will be using the first method, but if you like try each one.So now our program looks like this -

TRISB = %00000000 ‘ set PORTB to all outputsPORTB = %00000001 ‘ turn on the led hooked to PORTB.0

Page 7: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Notice the comments? it is a good idea to comment all your code, so you know what it is doing,it makes it easier to find problems later.Now that the LED is on, what do we do?Lets leave it on for 1 second, then turn it off. We do this with the PAUSE command

PAUSE 1000

PAUSE is stated in milliseconds 1000 milliseconds = 1 secondSo now our LED will come on for 1 second, then turn off.Our code now looks like this -

TRISB = %00000000PORTB = %00000001PAUSE 1000

Now lets make it flash on and off continuously, we do this by creating a loop in a subroutineA subroutine starts with a label, a label can be anything you want followed by a colon (:) exceptfor words reserved by PicBasic Pro (see the PicBasic Pro manual)

TRISB = %00000000 ‘ set PORTB to all outputsLoop: ‘ This is a label for our subroutinePORTB = %00000001 ‘ turn on LED on PORTB.0PAUSE 1000 ‘ wait 1 secondPORTB = %00000000 ‘ turn off LEDPAUSE 1000 ‘ wait 1 secondGOTO Loop ‘ go back to the beginning and start over

GOTO tells the program to go back to the subroutine “Loop”Now the program will cycle until you turn off the powerThat’s it, compile this, program your pic and watch your LED flash.When you program your Pic you must first set the configuration bits, in MPLab go toConfiguration\Configuration bits and set oscillator to XT and Master Clear to Enable,leave everything else alone

Now lets make it a little more interesting, first we will add some more LEDs,run a wirefrom each of the PORTB pins to an LED, hook them up in order PORTB0-7 to LED 1-8Notice that I kept the LEDs away from the Pic, (you want to be able to get the Pic out easily forprogramming) and that I ran all the LED grounds to the same strip, and used one resistor fromeach strip to ground.

Page 8: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Lets program in an interesting pattern and make it run a bit faster.

TRISB = %00000000 ‘ set PORTB to all outputs

Loop:PORTB = %10000001 ‘ turn on the two outside LEDsPAUSE 250 ‘ wait 1/4 secondPORTB = %01000010 ‘ turn off the two LEDs and turn on the next twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00100100 ‘ turn off the two LEDs and turn on the next twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00011000 ‘ turn off the two LEDs and turn on the last twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00100100 ‘ start back the other directionPAUSE 250 ‘ wait 1/4 secondPORTB = %01000010 ‘ continue going backPAUSE 250 ‘ wait 1/4 secondGOTO Loop ‘ go back to the beginning and start over

Notice that by using the PORTB = % we can control all 8 LEDs with 1 line of code.If you look at the 1s, you can see the pattern, the LEDs will start at the outside and move to thecenter then back to the outside. Compile this and program it to your pic.

Now that it’s going, how do we shut it off?Again, there are a couple of things we can do, we could just add an off switch, or we couldprogram it to cycle a specified number of times, and then turn of by itself.First, lets just add an off switch

Run a wire from PORTA.2 to a momentary switch and from PORTA.1 to a momentary switch,and take the other side of the switches to ground, then place a 4k7 (yellow-violet-red) resistorfrom the +5v power rail to PORTA.2 and PORTA.1. The 4k7 is called a “pull up resistor” it isused to hold the pin in a “high”(1) state, when the button is pressed it grounds the pin, putting itinto a “low”(0) state.

Page 9: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

We can use these different states to tell the program to do something.We use IF/THEN statements to read the pins and tell the program what to do

IF PORTA.0 = 0 THEN quit ‘ if switch1 is pressed the go to subroutine quitquit:stop ‘ stop the currently running program

Before we can use any of the PORTA pins, we will have to configure the PORT.PORTA has built in comparators and defaults to having them on, so first we need to turn themoff we do this by setting the comparator bit to off.

CMCON = 7

All the PORTS default to inputs, but it does not hurt to specify it

TRISA = %11111111

Now we add these to our program so it looks like this

TRISA = %11111111 ‘ set PORTA to all inputsTRISB = %00000000 ‘ set PORTB to all outputsCMCON = 7 ‘ turn off the comparators

Loop:IF PORTA.2 = 0 THEN quit ‘ if switch1 is pressed the go to subroutine quitPORTB = %10000001 ‘ turn on the two outside LEDsPAUSE 250 ‘ wait 1/4 secondPORTB = %01000010 ‘ turn off the two LEDs and turn on the next twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00100100 ‘ turn off the two LEDs and turn on the next twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00011000 ‘ turn off the two LEDs and turn on the last twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00100100 ‘ start back the other directionPAUSE 250 ‘ wait 1/4 secondPORTB = %01000010 ‘ continue going backPAUSE 250 ‘ wait 1/4 secondGOTO Loop ‘ go back to the beginning and start over

Quit:PORTB = %00000000 ‘ turn off all LEDs

Now when we press the switch the program will stop running, since the command to check thebutton is at the beginning of our loop, you will have to hold the button down until the currentcycle is complete, if you like, you could add the same line to the middle of the program so itwould check twice on each cycle.

Now lets program one button to turn it on, and another to turn it off, we use the same commandfor both actions, but now we have to put them in their own subroutine

Page 10: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Now our program should look like this

TRISB = %00000000 ‘ set PORTB to all outputsTRISA = %11111111 ‘ set PORTA to all inputsCMCON = 7 ‘ turn off the comparators

Start:IF PORTA.1 = 0 THEN Loop ‘ if switch1 is pressed then start the programgoto start ‘ keep checking the button until it is pressed

Loop:IF PORTA.2 = 0 THEN quit ‘ if switch2 is pressed the go to subroutine quitPORTB = %10000001 ‘ turn on the two outside LEDsPAUSE 250 ‘ wait 1/4 secondPORTB = %01000010 ‘ turn off the two LEDs and turn on the next twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00100100 ‘ turn off the two LEDs and turn on the next twoPAUSE 250 ‘ wait 1/4 secondIF PORTA.2 = 0 THEN quit ‘ if switch2 is pressed the go to subroutine quitPORTB = %00011000 ‘ turn off the two LEDs and turn on the last twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00100100 ‘ start back the other directionPAUSE 250 ‘ wait 1/4 secondPORTB = %01000010 ‘ continue going backPAUSE 250 ‘ wait 1/4 secondGOTO Loop ‘ go back to the beginning and start over

Quit:PORTB = %00000000 ‘ turn off all LEDsGOTO Start ‘ go back and wait for someone to press the start button

We added the start subroutine so the program would wait for someone to press the buttonbefore it would start, then we had to add the GOTO to the Quit subroutine so that the programwould go back to the beginning and wait for someone to turn it back on, we also repeated thecommand to check the stop button in the middle of the loop, so that we would not have to waitso long for it to stop.

Now lets program it to run the loop 10 times, and then turn off by itself.

To do this, we will use FOR / Next statements, but first we will have to declare the variablewe will use

i var byte

This creates a variable called “i” that is 1 byte,

FOR i = 1 TO 10 ‘ count from 1 to 10NEXT i ‘ go back for the next countNow we add these lines to the beginning and end of our program

Page 11: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

TRISB = %00000000 ‘ set PORTB to all outputsTRISA = %11111111 ‘ set PORTA to all inputsCMCON = 7 ‘ turn off the comparators

i Var byte ‘ create variable i to hold our count

Start:IF PORTA.1 = 0 THEN Loop ‘ if switch1 is pressed then start the programgoto start ‘ keep checking the button until it is pressed

Loop:FOR i = 1 TO 10 ‘ count from 1 to 10IF PORTA.2 = 0 THEN quit ‘ if switch2 is pressed the go to subroutine quitPORTB = %10000001 ‘ turn on the two outside LEDsPAUSE 250 ‘ wait 1/4 secondPORTB = %01000010 ‘ turn off the two LEDs and turn on the next twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00100100 ‘ turn off the two LEDs and turn on the next twoPAUSE 250 ‘ wait 1/4 secondIF PORTA.2 = 0 THEN quit ‘ if switch2 is pressed the go to subroutine quitPORTB = %00011000 ‘ turn off the two LEDs and turn on the last twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00100100 ‘ start back the other directionPAUSE 250 ‘ wait 1/4 secondPORTB = %01000010 ‘ continue going backPAUSE 250 ‘ wait 1/4 secondIF i = 10 Then Quit ‘ if the count has reached the end, then resetNEXT i ‘ go back for next count

Quit:PORTB = %00000000 ‘ turn off all LEDsGOTO Start ‘ go back and wait for someone to press the start button

Now our program will run 10 times and then stop and reset itself, although we can still turn itoff before the end of the count if we want to. notice we also took out the GOTO at the end, theNEXT i statement performs the same function in this case.The IF/Then statement at the end checks to see if the end of the count has been reached, and ifit has the program jumps to the Quit subroutine. If we did not put this in, the program wouldjust stop, and you would have to turn off the power in order to reset it.OK, now lets create 2 patterns that we can select between. First take a wire from PORTA.3 toone side of a SPDT switch (on-on) and another from PORTA.4 to the other side , then take a4k7 (yellow-violet-red) resistor from PORTA.3 to the +5v rail and from PORTA.4 to the +5vrail, then take a wire from the center of the switch to the ground rail.To select between the two patterns, we use IF / THEN statements in a separate subroutineand put our second pattern in a subroutine called Loop2

Start:IF PORTA.2 = 3 THEN LoopIF PORTA.3 = 4 THEN Loop2

Page 12: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Here is what our code looks like now

—— Note, this program is to large to compile under the demo version of PicBasic Pro ——

TRISB = %00000000 ‘ set PORTB to all outputsTRISA = %11111111 ‘ set PORTA to all inputsCMCON = 7 ‘ turn off the comparators

i var byte ‘ declare variable i

Begin:IF PORTA.1 = 0 THEN Start ‘ if switch2 is pressed then start the programgoto Begin ‘ keep checking the button until it is pressed

Start:IF PORTA.3 = 0 THEN LoopIF PORTA.4 = 0 THEN Loop2

Loop:FOR i = 1 TO 10 ‘ count from 1 to 10IF PORTA.2 = 0 THEN quit ‘ if switch1 is pressed the go to subroutine quitPORTB = %10000001 ‘ turn on the two outside LEDsPAUSE 250 ‘ wait 1/4 secondPORTB = %01000010 ‘ turn off the two LEDs and turn on the next twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00100100 ‘ turn off the two LEDs and turn on the next twoPAUSE 250 ‘ wait 1/4 secondIF PORTA.2 = 0 THEN quit ‘ if switch1 is pressed the go to subroutine quitPORTB = %00011000 ‘ turn off the two LEDs and turn on the last twoPAUSE 250 ‘ wait 1/4 secondPORTB = %00100100 ‘ start back the other directionPAUSE 250 ‘ wait 1/4 secondPORTB = %01000010 ‘ continue going back

Page 13: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

PAUSE 250 ‘ wait 1/4 secondIF i = 10 Then Quit ‘ if the count has reached the end, then resetNEXT i ‘ go back for next count

Loop2:IF PORTA.2 = 0 THEN quit ‘ if switch1 is pressed the go to subroutine quitPORTB = %10000000 ‘ turn on the first LEDPAUSE 100 ‘ waitPORTB = %01000000 ‘ continuePAUSE 100 ‘ waitPORTB = %00100000 ‘ continuePAUSE 100 ‘ waitPORTB = %00001000 ‘ continuePAUSE 100 ‘ waitPORTB = %00000100 ‘ continuePAUSE 100 ‘ waitPORTB = %00000010 ‘ continuePAUSE 100 ‘ waitIF PORTA.2 = 0 THEN quit ‘ if switch1 is pressed the go to subroutine quitPORTB = %00000001 ‘ last LEDPAUSE 100 ‘ waitPORTB = %00000010 ‘ start going backPAUSE 100 ‘ waitPORTB = %00000100 ‘ continue backPAUSE 100 ‘ waitPORTB = %00001000 ‘ continue backPAUSE 100 ‘ waitPORTB = %00010000 ‘ continue backPAUSE 100 ‘ waitPORTB = %00100000 ‘ continue backPAUSE 100 ‘ waitPORTB = %01000000 ‘ continue backPAUSE 100 ‘ waitGOTO Loop2 ‘ repeat the pattern forever

Quit:PORTB = %00000000 ‘ turn off all LEDsGOTO Begin ‘ go back and wait for someone to press the start button

That's our program, so now when you press the start button, the program looks to see whichposition switch3 is in, then runs the appropriate pattern. The first pattern is our original one thatoscillates from the outsides to the center, the second pattern sweeps back and forth (the “NightRider” lights) you can change the speed of the lights by changing the value of PAUSE. You canvary the speed by using a 5k potentiometer and the POT command.Connect a wire from PORTA.0 to the center of the potentiometer, then place a .22uf capacitorfrom one side of pot to the ground rail, it does not matter which side you put the capacitor on,but if you find that it seems to be working backwards, move the capacitor to the other side.First of all, we will have to declare a few more variables.

Page 14: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

adval Var byte ‘ create adval to store result from pottime Var Word ‘ create time to store delay time

Notice that the “time” variable is a word, if your variable is going to be larger than 255, youmust declare it as a word sized variable.

Here is how we read the pot

POT PORTA.0,scale,adval ‘ Read position of potentiometer to adval time = adval * 10 ‘ multiply adval and place in timeIF time < 25 THEN ‘ set a minimum timetime = 25ENDIF

Scale will depend on the R/C (resistance/capacitance) of your pot and capacitor, I found that thecombination of a 5k pot and a .22uf capacitor works well with a scale of 161.Now we replace the number after the PAUSE command with the variable “time”, now PAUSEwill look at the value of “time” and use that number.We will place this at the beginning of each of our LED subroutines, that way the program willadjust the speed at the beginning of each loop.

—— Note, this program is to large to compile under the demo version of PicBasic Pro ——

TRISB = %00000000 ‘ set PORTB to all outputsTRISA = %11111111 ‘ set PORTA to all inputsCMCON = 7 ‘ turn off the comparators

i var byte ‘ declare variable iadval Var byte ‘ create adval to store result from pottime Var Word ‘ create time to store delay time

Begin:IF PORTA.1 = 0 THEN Start ‘ if switch2 is pressed then start the program

Page 15: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

goto Begin ‘ keep checking the button until it is pressed

Start:IF PORTA.3 = 0 THEN Loop ‘ check the position of switch3 andIF PORTA.4 = 0 THEN Loop2 ‘ run the appropriate subroutine

Loop:POT PORTA.0,161,adval ‘ Read position of potentiometer to adval time = adval * 10 ‘ multiply adval and place in timeIF time < 25 THEN ‘ set a minimum time of .25 secondstime = 25ENDIF

FOR i = 1 TO 10 ‘ count from 1 to 10IF PORTA.2 = 0 THEN quit ‘ if switch1 is pressed the go to subroutine quitPORTB = %10000001 ‘ turn on the two outside LEDsPAUSE time ‘ waitPORTB = %01000010 ‘ turn off the two LEDs and turn on the next twoPAUSE time ‘ waitPORTB = %00100100 ‘ turn off the two LEDs and turn on the next twoPAUSE time ‘ waitIF PORTA.2 = 0 THEN quit ‘ if switch1 is pressed the go to subroutine quitPORTB = %00011000 ‘ turn off the two LEDs and turn on the last twoPAUSE time ‘ waitPORTB = %00100100 ‘ start back the other directionPAUSE time ‘ waitPORTB = %01000010 ‘ continue going backPAUSE time ‘ waitIF i = 10 Then Quit ‘ if the count has reached the end, then resetNEXT i ‘ go back for next count

Loop2:POT PORTA.0,161,adval ‘ Read position of potentiometer to adval time = adval * 10 ‘ multiply adval and place in timeIF time < 25 THEN ‘ set a minimum time of .25 secondstime = 25ENDIF

IF PORTA.2 = 0 THEN quit ‘ if switch1 is pressed the go to subroutine quitPORTB = %10000000 ‘ turn on the first LEDPAUSE time ‘ waitPORTB = %01000000 ‘ continuePAUSE time ‘ waitPORTB = %00100000 ‘ continuePAUSE time ‘ waitPORTB = %00001000 ‘ continuePAUSE time ‘ waitPORTB = %00000100 ‘ continuePAUSE time ‘ waitPORTB = %00000010 ‘ continue

Page 16: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

PAUSE time ‘ waitIF PORTA.2 = 0 THEN quit ‘ if switch1 is pressed the go to subroutine quitPORTB = %00000001 ‘ last LEDPAUSE time ‘ waitPORTB = %00000010 ‘ start going backPAUSE time ‘ waitPORTB = %00000100 ‘ continue backPAUSE time ‘ waitPORTB = %00001000 ‘ continue backPAUSE time ‘ waitPORTB = %00010000 ‘ continue backPAUSE time ‘ waitPORTB = %00100000 ‘ continue backPAUSE time ‘ waitPORTB = %01000000 ‘ continue backPAUSE time ‘ waitGOTO Loop2 ‘ go back to the beginning and start over

Quit:PORTB = %00000000 ‘ turn off all LEDsGOTO Begin ‘ go back and wait for someone to press the start button

———————————————————————————————

That’s the end of our LED tutorial, you might think “that was fun, but what use is it”, well, I’lltell you, you can use the same programs to control just about anything, all you need to do isreplace the LED with what you want to control, for example

- replace the LED with a transistor which in turn is activating a relay that can turn on anything you like.- replace the LED with a transistor which in turn is controlling a Triac, for high speed switching of AC currents.- replace the LED with a motor driver for controlling robots

I have used this same basic program to build a Stage lighting controller with 8 lightsand 6 different patterns, LED Displays, traffic light controllers and wig-wag light controllersfor model railroaders, my own little obstacle avoiding robots, and numerous other projects.

Page 17: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Buzzers & Noises

The Pic is also capable of making noise, there are a couple of ways of doing this. The simplestway is to just apply power to a buzzer. Clear of your breadboard and setup your Pic the sameway as we did in the LED project, power, ground, the oscillator, and the 4k7 resistor to theMCLR pin, then run a wire from PORTA.0 to the + side of the buzzer and another from the -side of the buzzer to the ground rail, now we write our program.

‘ Program to activate a buzzer using a Pic16F628

TRISA = %00000000 ‘ set PORTA to all outputsPORTA = %00000000 ‘ set PORTA to all lowCMCON = 7 ‘ turn of the comparators

PORTA.0 = 1 ‘ turn on buzzerPAUSE 2000 ‘ for 2 seconds

Program this into your Pic and give it a listen, we can also do this the other way, take the wirefrom the + terminal of the buzzer and move it to the +5v power rail and run the - wire toPORTB.0, now let’s change our program.

TRISA = %00000000 ‘ set PORTA to all outputsCMCON = 7 ‘ turn off comparators

PORTA.0 = 0 ‘ turn on buzzerPAUSE 2000 ‘ for 2 seconds

So as you can see, we can control the buzzer by either setting the pin high (applying power) orby setting it low (grounding it)

Another way of creating a sound is to use the FREQOUT command, but first, connect a wirefrom PORTA.1 to the + side of a speaker, and another from the - side to the ground rail.

Page 18: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Our code looks like this

FREQOUT PORTA.1,2000,1000 ‘ send a 1khz tone for 2 seconds

Now let’s add this to our existing program

TRISA = %00000000 ‘ set PORTA to all outputsPORTA = %00000000 ‘ set PORTA all low

PORTA.0 = 0 ‘ turn on buzzerPAUSE 2000 ‘ for 2 secondsFREQOUT PORTA.1,2000,1000

Now you will get a beep from the buzzer and a tone from the speaker, now let’s activate themmanually. We used PORTA for our outputs so that I can show you another feature that some ofthe Pics have. On the 16F628 PORTB has built in pull up resistors (PORTA does not havethem) so you do not have to use the 4k7 resistors that we used on the LED project to hold thepin in a high state. To enable them, we have to set another register

OPTION_REG.7 = 0

Now let’s setup our board, leave the speaker and buzzer as is back up with the + going toPORTA.0 now run a wire from PORTB.0 to switch1 and another from PORTB.1 to switch2,then run a wire from the other side of the switch to the ground rail.We will be using the same IF/THEN statements we used before.

‘ Program to activate a buzzer or play a tone through a speaker with a Pic16F628‘ using two pushbuttons

TRISA = %00000000 ‘ set PORTA to all outputsTRISB = %11111111 ‘ set PORTB to all outputs

Page 19: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

PORTA = %00000000 ‘ set PORTA all lowCMCON = 7 ‘ turn off comparatorsOPTION_REG.7 = 0 ‘ enable PORTB internal pull-ups

Loop:IF PORTB.0 = 0 THEN ‘ if switch1 is pushed PORTA.0 = 1 ‘ sound buzzer PAUSE 2000 ‘ for 2 secondsENDIF

IF PORTB.1 = 0 THEN ‘ if switch2 is pushed FREQOUT PORTA.1,2000,1000 ‘ send 1khz tone to speaker for 2 secondsENDIFGOTO Loop ‘ go back and wait for a button to be pressed

You can also use the PicBasic Pro SOUND command in place of FREQOUT.

IF PORTB.1 = 0 THEN ‘ if switch 2 is pressed SOUND PORTA.1,69,83 ‘ send out a note for approx 1 secondEndif

The SOUND command sends out 128 tones which range from 78 to 10,000 HZ,(a standard 88 key piano has a range of 27.5 to 4,186 HZ)See the PicBasic Pro manual for more information

There you have it, sounds can be very useful in a program, or just fun. For example, say youwant to know when your program reaches a certain point, just program it to beep when it getsthere. One of my robots beeps whenever he bumps into something, just to let you know howannoyed he is.

Page 20: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Using The LCD

In this section we will learn how to hookup and write to a 2x16 LCD screen, this setup workswith any LCD that uses the Hitachi 44780 controller. I use the AND491GST-LED LCDdisplay. First of all, clear your Pic of everything but the power connections, oscillator and the4k7 resistor to MCLR. If you have not soldered the header pins into the LCD, do it now, thenplug it into the board and run the following connections

PIC LCDPORTA.0 (RA0) to DB4PORTA.1 (RA1) to DB5PORTA.2 (RA2) to DB6PORTA.3 (RA3) to DB7PORTA.4 (RA4) to RS- also place a 4k7 pull-up resistor from PORTA.4 to +5vPORTB.3 (RB3) to EnableGround to RWGround to GND+5v to VDDGround to VO - to adjust the LCD contrast, run VO to the center of a 25k trimpot, thenrun one side of the pot to ground and the other to +5v (this is how it is done in the picture )

Picbasic Pro assumes that this is how the LCD will be connected, so as long as we use thesepins, we do not have to set anything, if you wanted to use different pins you would have to setup DEFINES to tell PicBasic Pro how you hooked it up.(see the PicBasic Pro manual for moreinformation, and a schematic of this hookup)

The LCD is initialized the first time it is written to, so we usually start with a command to clearthe screen.

LCDOUT $FE,1 ‘ clear LCD screenPAUSE 500 ‘ wait 1/2 second for screen to initialize

Page 21: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Then we can go on with the rest of our commands, any literal text you want to send to the LCDmust be enclosed in “quotes “

LCDOUT “Hello” ‘ print Hello on the first line

If you want to center the text, you would tell the LCD to start at a specific space, in this caseyou would start 6 spaces from the left. All commands must be preceded by $FE, the command$80 tells the LCD to print on the first line, so-

LCDOUT $FE,$80 +6,”Hello”

- tells the LCD to print Hello on the first line, starting 6 spaces from the left, the command $C0tells the LCD to print on the second line, so-

LCDOUT $FE,$C0 = 6,”World”

- will print World on the second line, directly under the first line.

Now let’s put the whole thing together

TRISA = %00000000 ‘ set PORTA to all outputsTRISB = %11110000 ‘ set PORTB 0-3 to outputs and 4-7 to inputsCMCON = 7 ‘ turn off comparatorsOPTION_REG.7 = 0 ‘ enable internal pull ups on PORTB

LCDOUT $FE,1 ‘ clear LCD screenPAUSE 500 ‘ wait 1/2 second for screen to initializeLCDOUT $FE,$80 + 6,”Hello” ‘ print Hello in the middle of the first lineLCDOUT $FE,$C0 + 6,”World” ‘ print World in the middle of the second linePAUSE 5000 ‘ display for 5 secondsLCDOUT $FE,1 ‘ clear LCD screenEND ‘ stops program

You can also print variables to the LCD

LCDOUT $FE,1,b1 ‘ clear screen and print variable b1

The problem here is that b1 will be printed as a hex number, to have it printed as an ASCII(readable)character, put a # sign in front of it

LCDOUT $FE,1,#b1

Here is a little program that will count from 1 to 254 using alternate lines on the LCD display,then start over.

TRISA = %00000000 ‘ set PORTA to all outputsTRISB = %11110000 ‘ set PORTB 0-3 to outputs and 4-7 to inputsCMCON = 0 ‘ turn off comparatorsOPTION_REG.7 = 0 ‘ enable internal pull ups on PORTB

Page 22: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

b1 var byte ‘ create variable b1

LCDOUT $FE,1 ‘ clear LCD screenPAUSE 500 ‘ wait 1/2 second for screen to initializeb1 = 0 ‘ give b1 an initial value of 0

Loop:b1 = b1 + 1 ‘ increment value of b1 by 1LCDOUT $FE,$80,#b1 ‘ send character out to line one of the LCDPAUSE 1000 ‘ wait 1 secondb1 = b1 + 1 ‘ increment value of b1 by 1LCDOUT $FE,$C0,#b1 ‘ send character out to line two of the LCDPAUSE 1000 ‘ wait 1 secondIF b1 > 254 THEN ‘ if count has reached the end - b1 = 0 ‘ start overENDIFGOTO Loop ‘ go back to the beginning and continue counting

That’s the basics for using the LCD, The data sheet for your LCD should list all thecommands you can use with the LCD,and the PicBasic Pro manual also lists some of the morecommon commands.You can also read from the LCD using the LCDIN command, but since you have to write tothe LCD before you can read from it, I have not really found much use for it yet. In orderto use the LCDIN command, you have to connect the RW line from the LCD to a pinon the PIC, but I’ll leave that for you to experiment with.

Leave the LCD connected for the next project.

Page 23: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Infrared Emitter & Detector

This section assumes your infrared detector will receive a signal at a frequency of 38khz, so inorder for us to use it, we must modulate our infrared LED at the same frequency, if yourdetector is on a different frequency, you will have to adjust the pulse rate accordingly. The Pic16F628 has hardware PWM (pulse width modulation) built in, once it is set, it will send acontinuous pulse out PORTB.3 (CCP1) independent of any other programming, let’s set up ourboard for the next experiment, in addition to the LCD setup (you did leave it on the boardright?) add the following connections to your board.

PORTB.3 (CCP1) to IR LED +ground rail to IR LED - use 220 ohm resistor from IR LED to groundPORTB.7 (RB7) to IR DET OUTground rail to IR DET GND+5v rail to IR DET VSSPORTB.0 (RB0) to LCD ENABLEPORTB.4 (RB4) to + side of a LED, take the - side through a 220 ohm resistor to ground

Since we will need PORTB.3 for our PWM output, we needed to move the LCD ENABLE lineto PORTB.0, so we will have to setup a define to tell the program what we have done, Nowthat we have our LCD reconfigured and our PWM set up, we can start on our program, wewill set it up so that a LED will light up when we detect an infrared signal, and the LCD willdisplay if we have a signal or not.

DEFINE LCD_EREG PORTB ‘ set LCD ENABLE portDEFINE LCD_EBIT 0 ‘ set LCD ENABLE bitTRISB = %00000000 ‘ Set PORTB to outputsTRISA =%11111111 ‘ set PORTA to inputsCMCON = 7 ‘ turn off comparatorsPR2 = 24 ‘ Set PWM for approximately 36KHzCCPR1L = 13 ‘ Set PWM Duty-Cycle to 50%CCP1CON = %00001100 ‘ Mode select = PWM

Page 24: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

T2CON = %00000100 ‘ Timer2 ON + 1:1 prescaleOPTION_REG.7 = 0 ‘ enable internal pull-ups on PORTB

LCDOUT $FE,1 ‘ initialize the LCD and cear the screen

Loop:IF PORTB.7 = 1 THEN ir_off ‘ check to see if infrared is being detectedIF PORTB.7 = 0 THEN ir_on

ir_off: ‘ if infrared is not being detectedPORTB.4 = 0 ‘ turn off the LEDLCDOUT $FE,$80 + 6,1,“Not” ‘ then print NotLCDOUT $FE,$C0 + 4,”Detected” ‘ Detected , on the LCDPause 50 ‘ wait 1/2 secondGOTO Loop

ir_on: ‘ if infrared is being detected ,PORTB.4 = 1 ‘ turn on the LEDLCDOUT $FE,$80 + 4,1,“Detected” ‘ then print Detected on the LCDPause 50 ‘ wait 1/2 secondGOTO Loop

The Pause 50 command just helps to stablize the LCD display, try it with and without the Pausestatement, to see the difference

To test your program place something between the IR LED and the IR DET and watch yourLED and LCD screen. If you are using a Pic that does not have PWM built in, you can send asignal out any pin with the PWM command (see the PicBasic Pro manual for more information)

NOTE some photo modules will output a voltage when they detect an infrared signal and others will turn off a voltage when an infrared signal is detected, so if you find that your readings are backwards just reverse the PORTB.7 settings in the Loop: subroutine. As written this program works with detectors that turn off a voltge when they detect an infrared signal

Infra red emitters and detectors are used for many applications, for example,

- place them on either side of an opening and have them trigger a buzzer if someone walks through the beam.- use them as “eyes” for robots so they can detect objects before actually hitting them- use them for wireless communications (like your TV remote)

Page 25: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

MIDI

This section is geared toward those of you who are interested in music and MIDI (Musical In-strument Digital Interface) Even if you are not interested in MIDI work through this section, asit will show you how to use the serial output of the Pic. I am not going to go into the specificsof MIDI, you can find all the info on that at,

http://www.midi.org/

Instead I am just going to show you that the Pic is capable of MIDI, and in the process, you willlearn how to build your own MIDI volume pedal c/w sustain.To test this program you will need a MIDI interface on your computer, and a program to moni-tor the MIDI activity, there are a few such programs on the internet, just do a search for “midimonitor”, I use a program called MidiSpy, you can download a time limited demo version totest your program with.

For this project, due to the high speed of MIDI, we will be changing our oscillator from the4mhz we have been using to a 20mhz, here is the pinout.

Some of the pins have other uses, but I have only listed the ones that apply to our project, seethe data sheet for more information. We will also be using a new command HSEROUT ,whichis the command to send data out the hardware serial port on the Pic.

Put this together on your breadboard, be sure to use the 20mhz oscillator and the 4k7 resistor onthe MCLR, then make the following connections

Run a wire from PORTB.2/TX to pin 5 of the midi out jackPlace a 220 ohm resistor from pin 4 of the midi out jack to +5vRun a wire from pin 2 of the midi out jack to groundRun a wire from PORTB.0 to one side of switch1, and the other side to groundRun a wire from PORTA.3 to the center of a 5k pot

Page 26: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Place a .22uf capacitor between ground and left side of the potNow that everything is hooked up, we can start on our program, you should be getting the ideaof how these programs are laid out by now, so I will list the complete program first, and givethe explanations afterwards.

‘ PicBasic file for midi volume pedal with sustain switch using a Pic16F628‘ Use with 5k pot and .22uf capacitor‘ set osc to HS when programming

DEFINE OSC 20 ‘ set oscillator to 20 mhzDEFINE HSER_TXSTA 24h ‘ enable high speed transmit registerDEFINE HSER_BAUD 31250 ‘ set the baud rateTRISA = %11111111 ‘ set porta to inputsTRISB = %11111001 ‘ set portb to inputsCMCON = 7 ‘ turn off comparatorsOption_Reg.7 = 0 ‘ enable internal pull-up resistors on PORTB

sendval Var byte ‘ create sendval to store byte to be sent (0-127)swonoff Var byte ‘ create variable for footswitch 1 valuepotval Var byte ‘ create variable to store current controller pot value

Loop: ‘ check pedals to see if they are on or offIf PORTB.0 = 0 Then Gosub swon EndifIf PORTB.0 = 1 Then Gosub swoff Endif

Pot PORTA.3,161,sendval ‘ Read position of potentiometer to adval (0-127) If sendval <> potval then ‘ if pot value has changed from it's current setting, potval = sendval ‘ then update the current setting Hserout [176,7,potval] ‘ send value out the serial port as midi volume Endif

Page 27: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Goto loop ‘ continually scan pots and switches for changes

swon: If swonoff = 0 Then ‘ check to see if sustain is off swonoff = 127 Hserout [176,64,swonoff] ‘ turn on sustain EndifReturnswoff: If swonoff = 127 Then ‘ check to see if sustain is on swonoff = 0 Hserout [176,64,swonoff] ‘ turn off sustain Endifreturn

————————————————————————————

Notice how we put some notes at the beginning of our program to let us know what chip we areusing, and any other special instructions, this helps to remind us what this program was writtenfor.We also had to set up some DEFINES to tell the program that we are using a 20mhz oscillator,and to enable the serial port and turn off the comparators, we then set up variables for the potand switch. We have a separate subroutine for for the on and off positions of the switch so thatthe program will not send commands everytime it scans the pot or a switch, but only when thereis a change in the pot value or switch position.I found that a 5k pot and a .22uf capacitor with a scale value of 162, gives us the proper rangeto keep it within the MIDI spec, (MIDI values are in the range of 0 -127) you may have toadjust the scale value a little to compensate for differences in pots and capacitors.When you program the Pic, go to the configuration menu, and set the oscillator to HS to enablethe high speed register.You can add as many foot controllers and switches as you have I/O pins, so if you are using a40 pin Pic, you can control a lot of stuff, do an internet search on “midibox” and see what somepeople have come up with.

Page 28: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Servos

Hobby R/C servos use pulse width modulation PWM to determine the position of the servo,each manufacturer implements it a little differently, so you may have to play around with thevalues to get it to work with your particular servo, the values we are using here should workwith Futaba S3004 servos. For this experiment we will be using a 12F675, mainly, so I canshow you the differences between this series of Pics and the others.The registers on the 12F series of Pics are different from the others, here is a list comparing thetwo

12Fxxx 16Fxxx TRISIO <> TRISA GPIO <> PORTA

The 12F675 can use an internal or external oscillator, and has analog inputs. These Pics onlyhave 6 I/O pins (one of which one is input only), so they cannot do as much as the 18 pinPics we have been using up until now, but for small projects that do not require a lot of I/O,they are perfect. and since they only have 1 port, they are simple to program.

Here is the pinout of the 12F675

GP3/MCLR can only be used as the master clear or as an input, it cannot be used as an output.For our experiment we will be using the internal oscillator , so we do not need to add one.Place the Pic on your breadboard and hook a wire to power and ground.Next run the wires as follows

From servo To

White GPIO.0 (GP0) Red +5v Black ground

Page 29: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

To make things easier, I usually cut 3 pieces of wire so I can just plug the servo into the board,that way you do not have to cut the plug off your servo.That’s all we need to hook up, now we can write the program -

‘ This is a program to rotate a servo motor left to right‘ using a PIC12F675/629 or 12C509‘ Set Oscillator to Internal RC No Clock‘ Servo position is determined by the width of the pulse‘ You may have to play with the maximum and minimum values‘ to get the proper sweep for your particular servo

TRISIO = %00111110 ‘ set GPIO.0 to output and the rest to inputsANSEL = %00000000 ‘ (675 only) set all pins to digitalCMCON = 7 ‘ (675/629 only) turn off comparators

pw VAR byte ‘ define variable pw

Main:pw = 20 ‘ set initial pulse widthPULSOUT GPIO.0,pw ‘ start at extreme rightPAUSE 2000 ‘ wait 2 seconds before starting

sweep:PULSOUT GPIO.0,pw ‘ start servo sweep right-to-leftPAUSE 18 ‘ set frequencypw = pw + 1 ‘ continue sweeping servo until it reaches the far leftIF pw > 200 THEN back ‘ if at end of sweep, start backGOTO sweep ‘ if not at end, continue sweep

Back:PULSOUT GPIO.0,pw ‘ start servo sweep left-to-rightPAUSE 18 ‘ set frequencypw = pw - 1 ‘ continue sweeping servo until it reaches the far right

Page 30: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

IF pw < 20 THEN sweep ‘ if at end of sweep, start backGOTO back ‘ if not at end, continue sweep

——————————————————————————————-

Here we did the same thing as our last project, we listed some comments at the start ofthe program to tell us what it is for, and what settings we need. ANSEL is used to enableor disable the analog inputs, and CMCON turns off the comparators.The pulsewidth is expressed in milliseconds, so we start with a value of 20ms, whichcorresponds to the servo’s right position, and go to 200ms, which corresponds to the servo’sleft position, this will give you about a 180 degree sweep. Now the servo will sweep backand forth until you turn it off.

Now lets use a couple of switches to control it, first connect a wire from GPIO.1 to one side ofa momentary switch and connect the other side of the switch to ground, do the same for GPIO.2

Now our program looks like this

‘ This is a program to rotate a servo motor left to right with 2 switches‘ using a PIC12F629 or 12F675‘ Set Oscillator to Internal RC No Clock and Master Clear to Internal‘ You may have to play with the maximum and minimum values‘ to get the proper sweep for your particular servo

TRISIO = %00000110 ' (675/629) set GPIO.1&2 to input and the rest to outputANSEL = %00000000 ' (675 only) set all pins to digitalCMCON = 7 ' (675/629) turn off comparatorsOPTION_REG.7 = 0 ' enable global internal pullupsWPU = %00000110 ' enable internal pullup for gpio.1&2

Page 31: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

pw var byte ‘ create variable to hold pulse width valuepw = 105 ‘ start at center

Check:If gpio.1 = 0 then left ‘ if switch1 is pressed go leftIf gpio.2 = 0 then right ‘ if switch2 is pressed go rightgoto check ‘ keep checking switches until one is pressed

Left:If gpio.1 = 1 Then Check ‘ if switch1 is released go back to checking switchespw = pw + 2 ‘ increment pw by 2 for each cycleIf pw > 200 then Check ‘ if limit is reached then go back to checking switchesGoto Left ‘ go back and continue moving left

Right:If gpio.2 = 1 Then Check ‘ if switch2 is released go back to checking switchespw = pw - 2 ‘ decrement pw by 2 for each cycleIf pw < 20 then Check ‘ if limit is reached then go back to checking switchesGoto Right ‘ go back and continue moving right

You will notice that we had to use 2 commands to enable the internal pull-up resistorsOPTION_REG.7 = 0 enables the global internal pull-ups and WPU = %00000110 enables theindividual pins (in our case pins 1 & 2)When you press one of the buttons, the servo will turn in that dirction until you release thebutton. The servo will center itself the first time you press a button after power up, thencontinue in the direction the button is for.

Now let’s control the servo with a potentiometer, this will also show you how to use theanalog inputs on the Pic12F675. First of all remove the switches from your board, leave theservo hooked up as is, then connect one side of a 5k pot to +5v and the other side toground, and the center to GPIO.1

Page 32: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Here is the code -

' This is a program to rotate a servo motor left to right with potentiometer' using a 12F675' Set Ocillator to Internal RC No Clock and Master Clear to Internal' You may have to play with the maximum and minimum values' to get the proper sweep for your particular servo

DEFINE ADC_BITS 10 ‘ set number of bits in sampleDEFINE ADC_SAMPLEUS 50 ‘ set sampling time in microseconds

TRISIO = %00000010 ' set gpio.1 to input and the rest to outputsANSEL = %00010010 ' set gpio.1 to analog, and sample clock to Fosc8ADCON0 = %10000111 ' enable ADC-1, right justified, voltage reference to VDDCMCON = 7 ' turn off comparators

pwin var word ' create variable to hold value from ADCpwout var byte ' create variable for outgoing pulse width

Check:ADCIN 1,pwin ' read pot and place value in pwin (0-1024)pwout = pwin / 5 ' divide pwin by 5 and place in pwout (0-205)If pwout < 20 Then pwout = 20 ' set maximum right positionEndifIf pwout > 200 Then pwout = 200 ' set maximum left positionEndifPulsout gpio.0,pwout ' send pulse width to servoPause 18 ' set frequency to approx 50hzGoto Check ' go back to reading pot

The DEFINE statements tell the program the number of bits in the sample (10 bitsfor the 12F675) and the sampling time in microseconds.We then enabled the analog input on gpio.1 and set the sampling clock, then we set whichAnalog to Digital Converter (#1) we would use. The 10 bit conversion will give us a range of0-1024 and our servo wants to see a range of 20-200, so we divide the sample by 5 to giveus a range of 0-205, which is close enough for our perposes. We set a maximums so thatthe servo does not try to go past it’s stop points. Since we are not using any of the otherpins for inputs, we did not bother enabling the pull-up resistors.

Did you notice the difference in how we used the pot here compared to the Midi project?in the Midi project we where using digital inputs, in order to read the pot the Pic first sends outa pulse and then times the discharge of the capacitor through the pot, to tell the pot’s position .In this example, we are using an analog input that can read a voltage directly, and convert it intoa digital number, so we just use the pot to vary the input voltage.

Page 33: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Robotics

In this section I am going to give you all the code to program a Pic16F628 to operate a smallobstacle avoiding robot, I’ll also show you the wiring for the Pic, but you will have to come upwith your own motor driver circuit, do an internet search for “H bridge motor driver” or “Beamrobots”, you should be able to find plenty of schematics and pictures to show you how to buildone, the one I use the most is based on the Microchip TC4424 motor driver chip, it is a fairlysimple circuit and you only need 1 chip per motor.

DO NOT CONNECT THE PIC DIRECTLY TO THE MOTORS ON YOUR ROBOT

You must use some type of motor driver with the Pic, even small motors draw more power thanthe Pic can handle. For sensors I use small microswitches, you can either connect a wire“antenna” to them, or connect them together as a “bumper” (old guitar strings work well forthis) here are the connections to the Pic.

—— Note, this program is to large to compile under the demo version of PicBasic Pro ——

‘ This is a program to operate a tracked or 2 wheeled robot using a Pic16F628‘ Basic direction controls, forward/reverse, right/left with object detection‘ Set oscillator to INTRC I/O when programming

TRISA = %11100011 ‘ Set PORTA to inputs, ports 2,3,4 to outputsTRISB = %00000000 ‘ set PORTB to outputsCMCON = 7 ‘ turn off comparators

Start:Portb = %00000000 ‘ set portb all low (forward/stop)Pause 3000 ‘ wait 3 seconds before startingFreqout Portb.0,50,50000 ‘ chirpPorta.2 = 1 ‘ turn on left eyePorta.3 = 1 ‘ turn on right eyePause 1000 ‘ wait 1 second

main:

Page 34: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

Portb = %01010000 ‘ both motors forwardPorta.2 = 0 ‘ flash each eye alternatelyPorta.3 = 1Pause 200Porta.2 = 1Porta.3 = 0Pause 200If Porta.1 = 0 Then right ‘ if left switch is activated, turn rightIf Porta.0 = 0 Then left ‘ if right switch is activated, turn leftGoto main ‘ start over

right:Porta.2 = 1 ‘ turn on both eyesPorta.3 = 1Freqout Portb.0,50,50000 ‘ chirpPortb = %00000000 ‘ stop for .5 secondsPause 500Portb = %10100000 ‘ backup a bitPause 100Portb = %01100000 ‘ turn rightPause 500Freqout Portb.0,50,50000 ‘ chirpGoto main

left:Porta.2 = 1Porta.3 = 1Freqout Portb.0,50,50000Portb = %00000000 ' stop for .5 secondsPause 500Portb = %10100000 ' backup a bitPause 100Portb = %10010000 ' turn leftPause 500Freqout Portb.0,50,50000 ' chirpGoto main

—————————————————————————————————

This is actually fairly straight forward to build, there are only a few considerations.

- there are two control wires for each motor driver, and make sure your motor driver can handle the maximum stall current your motors can draw.- since one motor is technically running in reverse, you need to hook one motor up backwards so that they will be turning in the same direction- you will need pull up resistors on Porta.0 and Porta.1, I just took a 4k7 resistor from +5v to the N/C terminal of each microswitch, and ran the N/O terminals to ground.- remember to place a 220R resistor between Porta.2 and Porta.3 and the LEDs, or from the LEDs to ground.

For those of you who would like to try building a small robot, here is a program you can use to

Page 35: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

test your motor functions, before adding any sensors or switches, this way if you have anyproblems later you will know it is not your motor drivers. This program is also small enough tocompile under the demo version of PicBasic Pro.

‘ This is a program to operate a tracked or 2 wheeled robot, using a Pic16f628‘ Basic direction controls, forward/reverse, right/left‘ Robot will run a fixed pattern

TRISA = %111111 ‘ Set PORTA to inputsTRISB = %00000000 ‘ set PORTB to outputsCMCON = 7 ‘ turn off comparators

Main:Portb = %00000000 ‘ set portb all low (forward/stop)pause 3000 ‘ wait 3 seconds before startingPortb = %01010000 ‘ both motors forwardpause 3000 ‘ for 3 secondsPortb = %10010000 ‘ turn leftpause 700 ‘ turn approx. 90 degreesPortb = %01010000 ‘ straighten outpause 3000 ‘ go forward for 3 secondsPortb = %00000000 ‘ all stoppause 500 ‘ wait .5 secondsPortb = %10100000 ‘ both motors reversePause 2000 ‘ backup for 2 secondsPortb = %10010000 ‘ turn rightPause 700 ‘ turn approx. 90 degreesPortb = %10100000 ‘ straighten outPause 1000 ‘ continue in reverse for 1 secondPortb = %00000000 ‘ all stoppause 1000 ‘ wait 1 secondPortb = %01010000 ‘ both motors forwardpause 4000 ‘ go forward for 4 secondsPortb = %00000000 ‘ all stoppause 1000 ‘ wait 1 secondPortb = %01100000 ‘ turnPause 1500 ‘ around 180 degreesPortb = %00000000 ‘ all stopgoto main ‘ repeat the pattern

You can use this program to test your robot’s directional control, depending on how fast yourrobot is, you may have to play with the timing, to get it to turn properly. On Ziggy, thisprogram runs normally, he just rolls around according to the pattern, but when I use the sameprogram on my test “tank” he spins around instead of turning, and actually pulls wheelies whenhe starts backward (due to the weight of the battery)

The robots on the website can use either one of these programs, so if you build one, add theLEDs, speaker and switches, you can always activate them later.

Page 36: Dragon’s Lair Electronics Primer.pdf · INTRODUCTION This paper was set up as an introduction to programming Pic Microcontrollers using Micro Engineering Labs PicBasic Pro. when

NOTES