Introduction: Automate Your Science Experiments
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.
18 Comments
12 years ago on Introduction
I'm trying to do this with VB 2010 Express, and it seems like the "Form1_Load" section is never being executed (and, as a result, nothing else is either). Has anyone else had/conquered this problem?
If I create a button that launches the "Form1_Load" module, this program works just fine. I am guessing that something has changed with the nomenclature of events that are supposed to happen on load? I do not have very much experience with VB so maybe I am missing something very silly.
Reply 12 years ago on Introduction
Sorry about this - when I wrote this in vb2008 I was thinking that one day it would become obsolete. I didn't think it would happen this fast! Many versions of basic are not backwards compatible (eg vb6 to .net).
I wonder if you could start with a brand new project in 2010, create a form, compile that and see if it at least loads the form automatically. If that works, then copy things one bit at a time into the new program. Maybe create the buttons from within the new program and then copy the code for that button. So you are creating all the objects like buttons, text boxes in vb2010 and hopefully they will all tie together.
Reply 12 years ago on Introduction
I think it has to do with the "handles" section of the function header. There is probably a handily named construct like "Handles Form1.Load" that I just needed to find and put on the end there. (Haha, I just googled it, and it appears that my guess was exactly right!)
When I gave Form_Load a button-click trigger, everything ran perfectly. I cranked up the refresh rate a little bit (although I noticed my setup did not like anything much faster than 2 seconds) and now everything is working perfectly. Thank you!
13 years ago on Step 1
So why is there two LM35s on this circit. is it to take an average?
Reply 13 years ago on Step 1
One LM35 might be recording the outside temperature and one recording the inside temperature. The main reason is to show that the picaxe has more than one A to D converter.
Reply 13 years ago on Step 1
Oh thanks. I really like this circuit. I saw it today first and all ready have the parts I will need in my cart. I never thought of the two LM35 for that action. Then again, thanks for the quick response.
Reply 13 years ago on Introduction
Glad to help. If you have any problems either post here or over in the picaxe forum http://www.picaxeforum.co.uk/forumdisplay.php?f=2
14 years ago on Introduction
Good job! I'm looking for circuits like this. I need to measure two different temperatures to calculate relative humidity and log this on a computer. There are R.H. sensors that could do this, but over 95% they don't work fine. The picaxe microcontrollers are very interesting and, since they are programmable in BASIC, easy to use. This instructable will help me a lot, thanks!
14 years ago on Introduction
I'am new to breadboards, could the author of this datalogging stuf send me a more detailed way how to connect the different compenents into the bread board? I couldn't rebuild it from the picture...
Reply 14 years ago on Introduction
If you look at the breadboard in the photo, start from the middle. The 5 holes going up are all connected to each other. Similarly the 5 holes going down are connected to each other. Then along the top is two rows - these go all the way from one side to each other and are connected. So you get two power supply rails at the top, two power supply rails at the bottom, and then those vertical connections going up and down. See http://en.wikipedia.org/wiki/Breadboard and the third picture down on the right. (except there is no horizontal connection down the middle like on that board).
Personally I think it is easier to copy it from the schematic than from the photo of the breadboard. Let me know if this helps, cheers, James Moxham
14 years ago on Introduction
OMG, I HAD TO SEE THIS, IT HAD BEAKER!!!!!!! FOR THAT, I GIVE YOU A THUMBS UP!
15 years ago on Introduction
Alright! I've been looking for something of this genre for some time now. Thanks!
15 years ago on Introduction
cool
15 years ago on Introduction
I'm guessing that the PICAXE has some kind of built in logic level converter so that the serial interface works? Nice little instructable, perfect for beginners to electronics!
Reply 15 years ago on Introduction
Yes it does have a level converter, of sorts. The circuit limits the current and actually works with other chip families as well. I've been using the same circuit for over 2 years into a 74HC04 gate with no problems. You could use 1488/1489 or Max232 chips if you want a true robust RS232 connection but this isn't really necessary.
Reply 15 years ago on Introduction
Ah ok. Some serial ports can be quite picky. Out of preference I tend to use Sipex logic level converters rather than Maxim ones. Although of late I have been using a Lantronix XPort to read in data from my microcontroller projects through an ethernet interface, highly recommended!
15 years ago on Introduction
Woah-- looks complicated.
The first picture = hilarious. ;-)
15 years ago on Introduction
Oh, just noticed. If you get wires stuck in bread board you should just be able to take off the tape or sticky pad at the back and use another bit of wire to take out the bits that's stuck