The Free Site   |  vBuddy - make friends, share photos, blogs, have fun   |  Cheap Web Hosting - starting at $5

Controlling and sensing real world devices using a PC and Picaxe Microcontroller

This Instructable shows you how to interface a PC and microcontroller. This demo will sense the value of a pot or any analog input and also control a servo. Total cost is under $40 including the servo. The servo turns on a microswitch and then the microswitch turns on a lamp. In a practical application the pot could be a temperature sensor and the servo could be turning on a heater. The servo could be replaced with a relay or other power controller. The picaxe is programmed in a simplified version of basic and the interface uses VB.Net. All software is available for free.

Step 1: Gather the parts

Complete_Circuit.jpg (59807 bytes)

Parts list:

Picaxe 08M chip  available from many sources includnig Rev Ed http://www.rev-ed.co.uk/picaxe/ (UK), PH Anderson http://www.phanderson.com/ (USA) and Microzed http://www.microzed.com.au/ (Australia)

Protoboard, servo, microswitch, 9V battery, 4xAA batteries and holder, tag strip, 10k resistor, 22k resistor, 33uF 16V capacitor, 0.1uF capacitor, 7805L low power 5V regulator, 10k pot, wires (solid core telephone/data wire eg Cat5/6), 6V lightbulb, D9 female socket and cover, 2 metres of 3 (or 4) core data wire, battery clips

Step 2: Download and install some software

We will need the VB.Net and the picaxe controller software.

VB.Net (Visual Basic Express) is available from   http://msdn2.microsoft.com/en-us/express/aa718406.aspx

The picaxe software is available from http://www.rev-ed.co.uk/picaxe/

You will need to register with microsoft to get the download - if this is a problem use a fake email or something. I actually found it helpful giving my real email as they send occasional updates.

 

Picaxe_Download.jpg (93600 bytes)

Step 3:  Build a download circuit

DownloadSchematic.jpg (52436 bytes)

This download circuit uses a picaxe chip, a couple of resistors, a regulator and a 9V battery. More information is available in the picaxe documentation.

Step 4: Protoboard layout of the download circuit

Download_Photo.jpg (58463 bytes)

This photo shows the download cable which is simply a D9 plug and a couple of metres of some multi core cable. Most modern PCs have a D9 serial port connection. A PC built before about 1998 might have a 25 pin connector. I soldered about 1cm of solid core wire onto the end of the flexible wires and then put heatshrink around this - the solid core wires go into a protoboard much better than flexible wires.

Step 5: Download the picaxe program.

Picaxe_Source_Code.jpg (47782 bytes)

Click on the blue arrow to download. If it doesn't download there are some debugging suggestions in the picaxe instruction manual. You can try downloading a simple program to turn a led on and off to check the chip works. This program as it is does nothing until it is connected to a PC as it is waiting for the PC to send it something. If it downloads ok then it is working and the chip is programmed and the next step is to reconfigure the chip as a serial interface chip.

Copy and paste the code below. To view it with color syntax look in View/Options/Editor. The color conventions are similar to VB.Net

main:serin 3,N2400,("Data"),b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13
readadc 1,b1' read the pot then send this back
serout 0,N2400,("Data", b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13)
select case b0' read data bit b0
case <140' if <140 then set servo to one position
servo 2,120
pause 1000' pause a second
else
servo 2,160
pause 1000
endselect
low 2' turn off the servo as serin does this anyway
goto main

Step 6: Reconfigure the circuit as a serial interface circuit

RunningSchematic.jpg (58137 bytes)

Two subtle changes have been made to the picaxe circuit. The 22k resistor that used to go to leg 2 now goes to leg 4. And leg 2 has been grounded. The only purpose of leg 2 is to receive programming data from the PC so once the chip is programmed it can be tied to ground. If you go back to programming the chip to correct bugs etc then disconnect leg 2 from ground and reconnect the 22k to leg 2. The picaxe talks back to the PC via leg 7 so this does not need to change.

A pot has been added and the servo has been added. The servo is not really necessary and a led and a 1k resistor would work fine and/or any circuit you wish to connect. I just used a servo to show how clicking something on a screen can make something actually move.

The servo is run off its own power supply. This separate power supply would not be needed if the picaxe were just turning leds on and off.

The picaxe is ready to go - now we need some VB code.

Step 7: Write some VB interface code

VBNewProjectSelectWindowsApplication.jpg (159878 bytes)

Once VB.Net is installed run it and select File/New Project and select Windows Application.  You can click File/Save All right at the beginning and save to wherever you like and then in the future either start the project from within VB.Net or by clicking on a .sln file that will be created.

Step 8: Design the VB.Net form

VBScreenshot2Toolbox.jpg (75105 bytes)

VB creates a new blank form called Form1.vb. You can change the name of this now or later or just leave it as Form1 if the project is simple. We will leave it as it is. To add some control we need to open the toolbox which is circled in green. The toolbox can be opened and closed whenever it is needed - usually the first step is to add the controls then close the toolbox and work on code. You can leave it open all the time but it does take up a bit of screen.

Step 9: Add A Timer

VBscreenshot3Timer.jpg (104752 bytes)

We have scrolled down the toolbox and selected a timer. Double click on the timer to add it. A picture of a clock called Timer1 will appear at the bottom of the screen and over at the right the timer properties are highlighted. You can edit these or they can be changed in the text body of the code. We will leave them as they are and change them in the body of the text.

As an aside, the toolbox does look a bit daunting but only a few are needed for most programs - these would include Buttons, Text boxes, Labels, Timers, Picture boxes, Check boxes and Radio boxes. Perhaps open a new program and have a play with a few sometime.

Step 10: Add a couple of buttons

VBScreenshot4Button.jpg (114154 bytes)

Click on the button tool and draw the size of the button on Form1. We are going to need two buttons, a picture box and a label. Go ahead and add these - the next screenshot shows these all drawn in. Size and position is not important and you can rename them later if you like.

Step 11: Form with all the controls added

vbscreenshot5allcontrols.jpg (89500 bytes)

Form1 is now laid out. The box next to Button2 is a small picture box. You can put pictures in this but we are just going to use it to indicate which button has been pressed by changing it from red to green. Label1 displays the picaxe registers.

Step 12: Add some code

vbscreenshot6ViewCode.jpg (89250 bytes)

Over on the right circled in green are several useful buttons - the second from the right is the View Code button and the right button is the View Designer. In practice when writing code one goes back and forth between these views. Generally if one is in Designer mode double clicking on an object such as a button brings up a spot in the Code View to add some code or takes one to the piece of code that runs when the button is pressed. In this way the program flow becomes quite intuitive - the user clicks on things and bits of code run and change the screen and so on.

For our purposes though we are going to cheat and paste in a whole slab of working code.

The code view will have Public Class Form1 ...End Class - highlight this and delete it. Now take all of the code below and paste it in.

Imports System.IO

Imports Strings = Microsoft.VisualBasic ' so can use things like left( and right( for strings

Public Class Form1

Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Integer) ' for sleep statements

Dim WithEvents serialPort As New IO.Ports.SerialPort ' serial port declare

Dim PicaxeRegisters(0 To 13) As Byte ' registers b0 to b13

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Timer1.Enabled = True ' put this in code as defaults to false when created

Timer1.Interval = 5000 ' 5 seconds

PictureBox1.BackColor = Color.Red ' set to position 'red'

Array.Clear(PicaxeRegisters, 0, 13) ' probably not needed as array declared blank

End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

' timer ticks every 5 seconds

Call SerialTxRx() ' talk to picaxe

End Sub

Sub SerialTxRx()

Dim LabelString As String ' string to display byte values

Dim DataPacket(0 To 17) As Byte ' entire data packet "Data"+14 bytes

Dim i As Integer ' i is always useful for loops etc

Label1.Text = "" ' clear the text on the screen

For i = 0 To 3

DataPacket(i) = Asc(Mid("Data", i + 1, 1)) ' add the word "Data" to the packet

Next

For i = 0 To 13

DataPacket(i + 4) = PicaxeRegisters(i) ' add all the bytes to the packet

Next

If serialPort.IsOpen Then

serialPort.Close() ' just in case already opened

End If

Try

With serialPort

.PortName = "COM1" ' Most new computers default to com1 but any pre 1999 computer with a serial mouse will probably default to com2

.BaudRate = 2400 ' 2400 is the maxiumum speed for small picaxes

.Parity = IO.Ports.Parity.None ' no parity

.DataBits = 8 ' 8 bits

.StopBits = IO.Ports.StopBits.One ' one stop bit

.ReadTimeout = 1000 ' milliseconds so times out in 1 second if no response

.Open() ' open the serial port

.DiscardInBuffer() ' clear the input buffer

.Write(DataPacket, 0, 18) ' send the datapacket array

Call Sleep(300) ' 100 milliseconds minimum to wait for data to come back and more if data stream is longer

.Read(DataPacket, 0, 18) ' read back in the data packet array

.Close() ' close the serial port

End With

For i = 4 To 17

LabelString = LabelString + " " + Str(DataPacket(i)) ' turn into a text string

Next

Label1.Text = LabelString ' put the text string on the screen

Catch ex As Exception

'MsgBox(ex.ToString)' uncomment this if want to see the actual error message

Label1.Text = "Timeout" ' will display this if picaxe not connected etc

End Try

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

PictureBox1.BackColor = Color.Red ' change the box to red

PicaxeRegisters(0) = 120 ' an arbitrary value for the servo

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

PictureBox1.BackColor = Color.Green ' box to green

PicaxeRegisters(0) = 160 ' arbitrary value for the servo

End Sub

End Class

Step 13: Run the program

VBScreenshot7Running.jpg (53021 bytes)

Power up the picaxe if it isn't powered up. Run the vb.net program by clicking on the green triangle at the top of the screen near the middle. To the right of the run triangle are a pause button and a stop button, or the program can be stopped by clicking on the top right x or with File/Exit if you have added a menu. The program can be compiled if you like but for debugging let's leave it running within VB.

The timer is sending out bytes every 5 seconds so it takes 5 seconds for the display to come up.

The label1 is displaying a dump of the 14 picaxe registers. These are sent to the picaxe and then send back again. It almost certainly isn't necessary to send all 14 and your code can be changed to suit. The second byte with a value of 152 is the value of the pot which changes from 0 to 255.

If button1 is clicked it sends a value of 120 in the first byte and if button2 is clicked it sends 160 and the picaxe program decodes these and moves the servo.

This code shows how to send data and get data back from a microcontroller. The microcontroller can turn on all sorts of devices - I have about 30 round my house running sprinklers, lights, security, detecting cars in driveways, turning on a number of 3.6Kw pumps and sensing the level of water in tanks. Picaxes can be daisychained on a common bus and can even communicate with each other via radio links.

It is also possible to upload and download data from websites and hence use the internet to connect devices anywhere in the world - more on this in a future tutorial!

Dr James Moxham

Adelaide, South Australia