Introduction: Control Real World Devices With Your PC

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.

A related Instructable shows how to link two microcontrollers via the internet https://www.instructables.com/id/Worldwide-microcontroller-link-for-under-20/

Step 1: Gather the Parts

Parts list:

Picaxe 08M chip available from many sources including 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

The above companies also sell USB to serial devices which are useful for laptops which don't have a serial port. It is worth noting that some USB to serial devices don't work as well as others and it is worth getting one from one of the above suppliers as they have been tested for use with picaxe chips. The one that is known to work is http://www.rev-ed.co.uk/docs/axe027.pdf Of course, if your computer has a serial port (or an old serial port card) then this won't be an issue.

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

If this link does not work then search in Google for: visual basic express download

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.

Step 3: Build a Download Circuit

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 and this should only take a few minutes to build once all the parts are to hand.

I might also add that picaxes do run happily on 3 AA batteries. A 5V regulated supply is useful for running analog inputs as the reference voltages don't change, but for simple on/off circuits a regulated supply is not needed. The 5V reg can be left out in these situations.

Step 4: Protoboard Layout of the Download Circuit

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

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

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

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

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

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

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

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

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

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 https://www.instructables.com/id/Worldwide-microcontroller-link-for-under-20/

The next two pages also contain some examples of how to use different sensors and how to control different devices.

Dr James Moxham
Adelaide, South Australia

Step 14: Input Devices

The picaxe programmer contains some very useful help files, one of which is called "Interfacing circuits" and it is also available at http://www.rev-ed.co.uk/docs/picaxe_manual3.pdf

This shows how to control motors, sense the environment and other useful control.

In addition to these cirucits, there are a few that I use over and over again.

Temperature - the LM35 temperature sensor produces a voltage which can go straight into a picaxe and can be read with a readadc or readadc10 command.

Light - a light dependent resistor has a resistance that varies from a few hundred ohms in bright sunlight to over 5 megohms in pitch black. Measure the resistance at the light level you want to switch at and put the LDR in series with a resistor of about the same value. Eg I wanted to detect the lights of a car pulling into the carport to turn on some lights. The resistance was about 1M from indirect light so I put a 1M in series with the LDR.

Switch - some switches switch between 5V and 0V (a single pole double throw switch) but some just turn on and off. If a switch turns on it can send 5V to a picaxe chip but if it is off the picaxe pin would be 'floating' and could be any value. This circuit shows how to pull the input down to ground when the switch is off. This is the circuit to use for most pushbutton switches.

Potentiomter - a good old fashioned knob. Twiddle the knob and read the voltage into the chip.

There are all sorts of other electronic devices that create a voltage from 0-5V or can be easily configured to do so. Examples are magnetic sensors, humidity, speed, touch, infrared light, pressure, colour and sound. Sensors in general cost only a few dollars each.

Step 15: Controlling Devices

The picaxe help file contains a great explanation of how to control motors and lights. In addition I find there are a few circuits I use over and over.

The first is a simple transistor circuit. A picaxe chip can turn on a maximum of 20mA per pin which is good for turning on a LED but not much else. A 547 transistor increases the current to 100mA which is good for small light bulbs.

The second circuit shows a mosfet. Mosfets need virtually no current to drive them - only volts so they can be directly controlled by a picaxe. There are all sorts of mosfets available but my preference is one called the BUK555 60B http://www.ortodoxism.ro/datasheets/philips/BUK555-60A.pdf It can be directly driven from 5V (unlike some which need 10V) but the main advantage is it has an extremely low resistance when turned on - 0.045 ohms which is not much more than the resistance of the wires one would connect to it. This means it doesn't get hot when driving quite high loads which saves power and also saves on heatsink costs. As an example driving a 5amp load like a car headlamp; watts=current squared x resistance, so W=5*5*0.045=1.12 watts which would only need a heatsink like a 1inch square piece of thin aluminium.

The third circuit shows a relay. There are several parameters for all relays - the coil voltage, coil resistance and the load voltage and current. For instance a relay might have a 12V coil with a coil current of 30mA, coil resistance of 400 ohms and might be able to drive up to 240V at 1 amp. The coil current is more volts and amps than a picaxe can supply, so we use the transistor circuit to switch the coil. There is a diode included as well - this supresses the back EMF when the relay turns off. Back EMF is what creates the spark for a sparkplug so you don't want these high voltages anywhere in a circuit. The contacts will have a maximum current and volts - the current might be a few amps and the volts are often 240V so switching 12V or 24V will be well within range. If you are inexperienced with electronics don't play with mains voltages.

There are also small relays that have coil voltages of 5V or 6V. For these relays you may not need a seperate 12V supply but just watch the coil resistance as many of these have current draws of over 100mA. If so and you are using a 78L05 100mA 5V regulator you might want to change this to a 7805 regulator which can supply up to 1 amp.

Relays are particularly useful for switching AC - eg 24VAC garden sprinkler solenoids, 12VAC garden lights and in electrically noisy environments such as a car. They are also useful for controlling big loads, eg a picaxe supplying 20mA at 5V = 0.1W controlling a transistor 12V at 100mA=1.2W to a relay 24V 100mA =2.4W to a contactor driving a 3600W pump. If you want to control power like that then get an electrician to wire up a control box and give you two wires coming out (coil wires for a 12V relay) that you can control. This way the electrician can sign off on the power box and you can do all the electronics without having to worry about being electrocuted.

Another use for relays is a reverse control for a motor. Using pulse width modulation into a mosfet you can control the speed of a DC motor, and with a DPDT power relay you can change the direction. This is a simple way of controlling big motors like the ones used in 'robot wars'.

Please post a comment if you need help building something.