maths with Python 7: Data logging from Arduino

This small project will help me later when I introduce a Matlab script I’m preparing, so stay tuned to the blog!

Today I’m going to do a simple example of data logging with Python and Arduino (my old Duemilanove). The Arduino is going to read a signal from a sensor and is going to report that value through the serial port. The Python script is going to scan the port from time to time and get the latest value. It’s not a clean implementation and can be improved, but it is an easy example.

But first, remember similar projects.

imag39691

Arduino + LCD MD216-01 Rev.A

awesome

Father and Daugther

2013-10-09-202855_1824x984_scrot

Raspberry Pi 001: Setup and Run first Arduino-Python project.

And of course, all the Python projects:

maths with Python

maths with Python 2: Rössler system

maths with Python 3: Diffusion Equation

maths with Python 4: Loading data.

Raspberry Pi 001: Setup and Run first Arduino-Python project.

Raspberry Pi 002: Pi Camera, start up scripts and remote desktop

maths with Python 5: Double Compound Pendulum Chaotic Map

maths with Python 6: Twitter API – Tweepy for social media and networks (with Gephi)

So, let’s begin.

Step 1. As a sensor I’m going to use a photodiode. Basically a photodiode works absorbing light and turning it into a voltage. To find out which terminal is the positive, simple connect the photodiode to a voltmeter and apply some light.

IMAG4205_BURST010

This model in particular is not very good for visible light (usually these models are designed to work at certain ranges, so maybe this one has its maximum sensitivity at IR or UV), but it will work.

Attach the photodiode between ground pin (GND) and Analog Input A0.

IMAG4199_BURST004

In this way we are going to read the voltage generated by the photodyode and detect the amount of ligth in the room.

Step 2. Program the Arduino to read an analog input and write the value to the serial port. We already did it in the post (Raspberry Pi 001: Setup and Run first Arduino-Python project). But just in case, this is a simple program that reads pin A0 and writes the value (in volts) to the serial port.

int sensorPin = A0;    // select the input pin for the photodiode
int sensorValue = 0;  // variable to store the value coming from the sensor

void setup() {
Serial.begin(9600);// initialize serial communications at 9600 bps:
}

void loop() {
sensorValue = analogRead(sensorPin);  // read the value from the sensor:
// Convert value to volts and print the results to the serial monitor with 4 digits precision:   
Serial.println(sensorValue*(5.00/1023.0),4);  
delay(20);   // stop the program for for 20 milliseconds:                
}
 

Upload the program to the Arduino and you will be ready. Just in case, check the serial monitor to see that the Arduino is sending the values and simply putting your hand over the sensor test if the values change.

duemilanove

Step 3. Write a Python code that reads the serial port, gets the last value and stores it.

import csv
import serial
import time

#First we create a name for the CSV file that is going to be date and time
name=time.strftime("%Y_%m_%d_%H_%M_%S", time.gmtime())
#Open the file
f=open(name+'.csv', 'wt');
#Initialize the CSV writer to write data into file
writer = csv.writer(f,delimiter='\t')

#Now we write a few lines to swhow how to write data
writer.writerow(['[Header]'])
date=time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
writer.writerow(['date='+date])
writer.writerow(['Column1=Time'])
writer.writerow(['Column2=Voltage'])
writer.writerow(['[Data]'])

#Open the serial port. From the Arduino program we know the Arduino is in com3,
#and we selected 9600 as baudrate
ser = serial.Serial('com3',9600,timeout=1)

#For some reason, when the serial port is initialized,
#its first value is not real, so just read it and discard
kk=ser.readline();

#We are going to take 250 data points
for t in range(250):
    #Read last string from serial port
    kk=ser.readline()
    #String is in the form <value>\r\n we only need the <value>
    kk2=kk.split('\r',1)
    s=kk2[0]
    #We put each data point in a new row of the data file.
    writer.writerow((t*10,s))
    #waits 10 seconds for next data point
    time.sleep(10)

#When finish, close the file and the serial port.
f.close();
ser.close();

 

When we run this script it generates a data file that looks like this:

python_arduino

Now you can import the data into any program you like, for instance Open Office Calc.

python_arduino_data_logging

Hope you find this interesting. Now you can try things like reading humidity sensor for a week, or saving home temperature, or any other idea you get.

Advertisements

3 thoughts on “maths with Python 7: Data logging from Arduino”

  1. Hi!! how can I do the same project using only the Raspberry Pi?
    what changes I need to make the code?

    1. Hi Matheus,
      I think the Python code should run in a Raspberry Pi without any problem. Maybe you need to install the Arduino drivers and that’s all.
      Please, let us know if you try and how it goes.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s