Introduction: Automate Your Science Experiments

About: Dr James Moxham is a general medical practitioner in Blackwood, Australia. His interests include general family medicine, medical politics, microcontrollers and tending a rose garden. He lives on a property wi…

Automate your next science experiment for under $20 with a datalogger and free up time for more important things like this French Kissing Instructable https://www.instructables.com/id/How-to-French-Kiss/

Step 1: Datalogging for Dummies

Your teacher has asked you to measure the temperature of a cup of hot water as it cools down. You need to measure the temperature every minute, record the data and make some conclusions. Boring! Why not measure everything automatically with a datalogger and export the data directly into an Excel spreadsheet? Now your graphs will look professional, no one can say you didn't do the measurements properly and, most importantly, you will have freed up some precious time!

This example measures temperature, but can easily be changed to measure things like light, volts, current, speed, rotation, acceleration, soil moisture or any number of other variables. We are using the picaxe as a cheap way of interfacing multiple analog and digital inputs to an RS232 port, though these chips can do a lot more than that - see https://www.instructables.com/id/Control-real-world-devices-with-your-PC/

Parts list

You will need:
1 computer
1 picaxe chip 08M ($3)
Breadboard
Components - resistors, capacitors, temperature sensors, regulator, wires.
Free copies of the picaxe programming software and VB.Net

The 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)

The RS232 plug is a D9 female plug. If you are doing a lot of experiments and don't want to keep reaching behind the computer, you can make an "extension lead" using male and female IDC 9 pin plugs and a metre or so of ribbon cable.

The picaxe has been configured in a slightly unusual download circuit which doubles as both a programming circuit and a communications circuit. Flick the switch to go between programming and communications (or just short leg 2 to ground on a protoboard to run in communication mode).

The LM35 devices output millivolts equal to degrees in centigrade. Looking at the writing on the case, the pins are numbered 1,2,3.

Step 2: Build the Circuit

This is a quick and simple breadboard and is certainly not the neatest breadboard you will see on Instructables. But there is a reason for this. Note that the wires are looped rather than flat on the board. Flat looks neater, but if you lay them flat the wire ends up bent at 90 degrees and eventually breaks off at that point. Sometimes it is hard to get the broken bit out of the hole. This design is messier, but the wires last longer. The red and black wires on this board have actually been building circuits for the last 23 years!

Not shown is the other end of the D9 plug but this is straightforward to wire up. Just be careful with the output from the PC which is pin 3 on the D9. This wire has -12V on it most of the time and this voltage will zap other components if you accidentally connect it in the wrong place.

Step 3: Download Free Software

If you haven't already got VB.Net (or any of the .Net languages), grab them from Microsoft while they are being given away! These are programs that used to cost $600 or more. The link is http://msdn2.microsoft.com/en-us/express/aa718406.aspx The whole .Net framework is a group of different languages like C, Java and VB that are gradually converging into one language, so learning one means you are well on the way to learning the others. The download is over 60Mb so set it going while you get on with other things.

Download the picaxe programming system http://www.rev-ed.co.uk/picaxe/

Install the software. With the picaxe software, have a quick scan through the three files in the Help. You don't need to understand everything but it is helpful to get a quick idea of the circuits and the instructions. Picaxe Basic and VB.Net are rather similar languages if you stick to the simple instructions.

Step 4: Program the Picaxe Chip

We are writing a very simple program - all this does is wait for a signal from the PC and then reads the voltages on some pins and sends the data back. Copy and paste this code and download it by clicking on the blue triangle. If no error messages come up then the chip is programmed. (If you want to check the chip actually works, you can write a simple program to flash a led as per instructions in the help file.)

If you are really stuck at this stage, ask for some help at the picaxe help forum http://www.picaxeforum.co.uk/

Code:

main:serin 3,N2400,("Data"),b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13
readadc10 1,w0' read the analog value on pin1 (physical leg 6)
readadc10 2,w1
serout 0,N2400,("Data", b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13)
goto main

Once the picaxe is programmed, flick the switch on the board to "Run", or short leg 2 to ground. If you don't do this nothing terribly bad will happen but the picaxe won't run properly as it will think the data instructions are a new program being downloaded.

Readadc10 reads data in 10 bit resolution, which is 1023. With a 5V supply, this means that 1V will read as 1023/5 or 205. If the LM35 is reading 24C then it will have a 240mV output, or 0.24V which will come into the spreadsheet with a value of 49. You will need to do some maths in the spreadsheet to convert back to temperature eg (100*5*49)/1023.

Step 5: Design the Form in Visual Basic

If you are unfamiliar with VB.Net then read this Instructable https://www.instructables.com/id/Control-real-world-devices-with-your-PC/ which describes creating a VB program in more detail.

After creating a new vb.net project the first step is to create a form. This form has a picture box, 4 labels, a text box and a rich text box. It also has a timer (not shown) which needs to be dropped on the form as well. The picture box is next to label1 and can be any size. The properties of all these objects are defined in the code on the next page.

Step 6: Write the Code

Switch from "View Designer" to "View Code" which are the two right most buttons under "Solution explorer" at the top right of the screen. Note the location of these two buttons as they are very useful.

Copy and paste the code below. The formatting including the colour of the text will reappear as in the screenshot above.

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
Dim ModifyFlag As Boolean
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 ' every 10 seconds
PictureBox1.BackColor = Color.Gray ' start with the comms boxes gray
ModifyFlag = False ' if modify a value manually then skip download
RichTextBox1.Multiline = True ' so can display more than one line
Label1.Text = "Picaxe communications; red=not working, green=ok"
Label2.Text = "Location of data file"
Label3.Text = "Date and time"
Label4.Text = "Picaxe registers"
TextBox3.Text = "c:\Datafile.csv" 'name and location of data file
Call DisplayPicaxeRegisters() ' display the 14 registers
End Sub
Sub SerialTxRx()
Dim DataPacket(0 To 17) As Byte ' entire data packet "Data"+14 bytes
Dim i As Integer ' i is always useful for loops etc
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
PicaxeRegisters(i - 4) = DataPacket(i) ' move the new data packet into the register array
Next
PictureBox1.BackColor = Color.GreenYellow ' working
Catch ex As Exception
PictureBox1.BackColor = Color.Red ' not working
End Try
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Call SerialTxRx() ' send to the picaxe and read it back
System.Windows.Forms.Application.DoEvents() ' so windows doesn't hang
Call DisplayPicaxeRegisters() ' refresh registers on the screen
Call SaveRegistersToLocalFile() ' save numbers to file
Label3.Text = Now ' refresh date and time on screen
End Sub
Sub DisplayPicaxeRegisters()
Dim i As Integer
Dim registernumber As String
RichTextBox1.Multiline = True ' so can display more than one line in the text box
RichTextBox1.Clear() ' clear the text box
For i = 0 To 13
registernumber = Trim(Str(i)) ' trim off leading spaces
If i < 10 Then
registernumber = "0" + registernumber ' add 0 to numbers under 10
End If
RichTextBox1.AppendText(registernumber + " = " + Str(PicaxeRegisters(i)) + Chr(13))
Next ' chr(13) is carriage return so new line
End Sub
Sub SaveRegistersToLocalFile() ' save register array in a local text file
' use a file with extension .csv for excel (comma seperated)
Dim i As Integer
Dim DateTime As String
Dim LineOfText As String
FileOpen(1, TextBox3.Text, OpenMode.Append) ' open the text file named in the text box
For i = 0 To 13
LineOfText = LineOfText + Str(PicaxeRegisters(i)) + ","
Next
DateTime = Now
LineOfText = LineOfText + DateTime ' add the date
PrintLine(1, LineOfText)
FileClose(1) ' close the file
End Sub

End Class

Step 7: Run the Program in VB

If you have done all the steps you will have a picaxe chip that has been programmed and leg 2 of the chip is connected to ground. The chip will be waiting to get a signal from the PC.

So, go ahead and compile and run the VB program by clicking on the little triangle (highlighted with an orange circle).

Every 5 seconds (time delay set by the timer interval of 5000), the vb program sends a request for all the picaxe registers. It then gets the values back and saves them in a file called Datafile.csv. A .csv file is a comma separated file which can be read with programs like Excel and (free) OpenOffice. Near the bottom of the vb program is a line of code FileOpen(1, TextBox3.Text, OpenMode.Append) which appends data one line at a time into a file. We could have used openmode.output but that would open the file and delete the old file. More complex programming might save all the variables into an array and then save it all at once.

If you don't like the dataset then delete the file manually before running the program again. Just note that if you open up the file in Excel to see what it looks like and the vb program is still running it will generate an error as it won't be able to write to the file when another program has it open.

Step 8: Read the Data

Open the datafile.csv. This contains the raw data. Column "O" will have #### in it as the text is too wide but you can read this column by making the column wider.

Step 9: Produce a Graph

You can write formulas in excel and copy them down a column, so in this case you might want to insert a formula in cell b1 that converts the raw value in column a1 into a temperature. The formula is =A1*100*5/1023. Click on this cell, hold down the shift key and click the down arrow till all the column is highlighted. Now go to Edit/Fill/Down to copy this formula all the way down.

To graph this column, highlight it (using shift/arrow down) and then go to Insert/Chart. Select a line chart, and you now have a graph.

Make sure you calibrate the temperature against a thermometer that you know is accurate. For true accuracy, embed the sensor in epoxy resin and then dip it in iced water and boiling water and note the readings.

Once you have had fun datalogging you can start using the picaxe to control servos and turn on and off solenoids and really automate your experiments.