BioMomo
Posts: 11
Joined: Thu Jun 13, 2013 8:36 am

From Arduino to Raspian via Python... Easyest way ?

Fri Jun 14, 2013 9:51 am

Dear happy people of the happy world of raspberry...

As i'm intending to be one of yours, I'm still a really new user trying to learn from the magic world of programmation.
(As i'm not fluent in english, i'll do my best ;) )

I did a small program through Arduino IDE to read pulses from a water-meter.
One pulse is send for each liter passed through the wate-meter and IDE arduino is writing a "1" in the IDE consol window (Serial.print("1")).
I would like to import this information from Python to a file .txt for exemple.

I'm just working on it : i'll have to do something looking like that...

http://www.benk.ca/node/10

Code: Select all

#!/usr/bin/python
'''
by Ben Kenney - July 2012
This program reads data coming from the serial port and saves that data to a text file. It expects data in the format:
"photocell_reading,thermistor_reading"
It assumes that the Arduino shows up in /dev/ttyACM0 on the Raspberry Pi which should happen if you're using Debian.
'''
import serial
from time import strftime
from datetime import datetime, time

ser = serial.Serial('/dev/ttyACM0',9600)

startTime = datetime.now()
try:
	while 1:
		line=ser.readline().rstrip()
		light,temp2=line.split(",")
		now = datetime.now()
		elapsedTime = now-startTime
		elapsedSeconds = (elapsedTime.microseconds+(elapsedTime.days*24*3600+elapsedTime.seconds)*10**6)/10**6
		print("%s,%s,%s,%s"%(now.strftime("%Y-%m-%d %H:%M:%S"),elapsedSeconds,light,temp2))
		f=open('tempLog.dat','a')
		print >>f,("%s,%s,%s,%s"%(now.strftime("%Y-%m-%d %H:%M:%S"),elapsedSeconds,light,temp2))
		f.close()
except KeyboardInterrupt:
	print "\ndone" 
I was wondering :
  • i'll have to creat a file (as in this exemple) "tempLog.dat" to export datas, but where ? in the ~/pi/src (where is my python script file) or in the /dev/ttyACM0 (which is the place where Arduino send values), or event somewhere else i don't know about ?
  • infact, do you advise me the use of pyserial (is it really easyer) ?
Thanks for your help...

cae2100
Posts: 143
Joined: Tue Jan 08, 2013 10:35 am
Contact: Website

Re: From Arduino to Raspian via Python... Easyest way ?

Fri Jun 14, 2013 10:35 am

pyserial is very easy to use, and will serve your purpose very well. This is a good start on how to use it with examples and such:
http://playground.arduino.cc/interfacing/python

As for saving stuff to a file, here's a small example script that I keep around to help me remember saving/loading files in python:

Code: Select all

fob = open('chirp.cfg', 'w')    #open file to write to it
blahvar = raw_input()
print fob.write(blahvar)
fob.close

fob=open('chirp.cfg', 'r')    #open file to read it back
varable = fob.readline()
print varable
fob.close
Hope that helps
If it isnt smoking and blown into pieces, it's not pushed far enough yet. :P
http://cae2100.wordpress.com

BioMomo
Posts: 11
Joined: Thu Jun 13, 2013 8:36 am

Re: From Arduino to Raspian via Python... Easyest way ?

Fri Jun 14, 2013 10:57 am

Thanks for your help...
For start i just use the first code on http://playground.arduino.cc/interfacing/python

Do you know where i can define the name of the Arduino output i want to read ? i wrote "Serial" but i don't know where it refers to...

Code: Select all

import Serial
ser = serial.Serial('/dev/ttyACM0', 9600)
print ser.readline()
So when i start the script i receive the following message :

Code: Select all

 
Traceback (most recent call last):
  File "ext.py", line 1, in <module>
    import Serial
ImportError: No module named Serial
Cheers !

Oops, i didn't see you wrote something more in your last post (thanks for that), i'll give a look after lunch ;)

cae2100
Posts: 143
Joined: Tue Jan 08, 2013 10:35 am
Contact: Website

Re: From Arduino to Raspian via Python... Easyest way ?

Fri Jun 14, 2013 11:10 am

be careful because python is case sensitive. use

Code: Select all

 import serial
instead of

Code: Select all

import Serial
also, you assign the serial port in this line here:

Code: Select all

ser = serial.Serial('/dev/ttyACM0',9600)
just change the "/dev/ttyACM0" to whatever one you want, which ttyACM0 is standard for arduino uno, or ttyUSB0 for other arduino boards with the FT232 chip on it.
If it isnt smoking and blown into pieces, it's not pushed far enough yet. :P
http://cae2100.wordpress.com

BioMomo
Posts: 11
Joined: Thu Jun 13, 2013 8:36 am

Re: From Arduino to Raspian via Python... Easyest way ?

Fri Jun 14, 2013 12:41 pm

Hi,

I checked : ttyACM0 is right in my case....

I also changed the Serial to serial but it seems the probleme is from my understanding of "serial"...

Code: Select all

pi@raspberrypi /dev $ python ext.py
Traceback (most recent call last):
  File "ext.py", line 1, in <module>
    import serial
ImportError: No module named serial
I don't really know what serial refers to...
My Arduino is connected and sending message through the Arduino IDE (USB) to my raspberry... Results can be seen in the IDE consol...
in IDE i do this :

Code: Select all

Serial.print(litres);
where "litres" is my number of liters which passed through the water-flow since the start of the program...
Any ideas ???

cae2100
Posts: 143
Joined: Tue Jan 08, 2013 10:35 am
Contact: Website

Re: From Arduino to Raspian via Python... Easyest way ?

Fri Jun 14, 2013 6:56 pm

you may not have pyserial installed, some distros dont have it installed by default that Ive found. to install it, just type/paste this in in a terminal window/command line:

Code: Select all

sudo apt-get install python-serial
That seems to be your issue.
Also, the varable that you're using for the serial in your program isnt Serial, it's ser, you can set it here:

Code: Select all

    ser = serial.Serial('/dev/ttyACM0',9600)
The serial.Serial() stuff is just setting up the serial port to use it and setting it to be controlled.
If it isnt smoking and blown into pieces, it's not pushed far enough yet. :P
http://cae2100.wordpress.com

BioMomo
Posts: 11
Joined: Thu Jun 13, 2013 8:36 am

Re: From Arduino to Raspian via Python... Easyest way ?

Mon Jun 17, 2013 7:58 am

Thanks for your answers...
I did as you said (and install the python-serial).
But even if my variable is called ser in the IDE program it always tells me the following error message :

Code: Select all

pi@raspberrypi ~/src $ [i]python3.2 extract.py
  File "extract.py.save", line 8
    print ser.readline()
    ^
IndentationError: unexpected indent[/i]
Someone told me it might come from the readline function which might be troubles and that i could use ser.readline(eol='/n')...
http://stackoverflow.com/questions/3437 ... ne-timeout
I don't really understand what iit changes and means but i'm working on it...
Bye and thanks,
Julien

cae2100
Posts: 143
Joined: Tue Jan 08, 2013 10:35 am
Contact: Website

Re: From Arduino to Raspian via Python... Easyest way ?

Mon Jun 17, 2013 8:08 am

the indentation error is from things not being indented as they should be. try uploading your whole code using code tags, and Ill go through and fix everything for you and see where the issues are.
If it isnt smoking and blown into pieces, it's not pushed far enough yet. :P
http://cae2100.wordpress.com

User avatar
winkleink
Forum Moderator
Forum Moderator
Posts: 288
Joined: Mon Nov 07, 2011 9:12 am
Location: UK
Contact: Website

Re: From Arduino to Raspian via Python... Easyest way ?

Mon Jun 17, 2013 8:13 am

IndentationError: unexpected indent[/i]
Not sure on getting the code to work but Python is very picky about indents which is what the above error message is related to.
Check your indents to make sure they are all consistent.
I know I got into trouble mixing the IDE and geany for Python as they were set differently.
Twitter:Winkleink
Google+: Winkleink

BioMomo
Posts: 11
Joined: Thu Jun 13, 2013 8:36 am

Re: From Arduino to Raspian via Python... Easyest way ?

Tue Jun 18, 2013 10:12 am

Thanks for your answers...
I friend of mine told me it might come from the "()" after some statements and the use of Python 2.7 or 3 (and 3.2)...
So i did it using more "()" and with Python 2.7 and it finally worked...

Code: Select all

#! /usr/bin/python2.7
import serial
f = open ('output', 'w')
ser = serial.Serial('/dev/ttyACM0', 9600)
x=ser.readline()
f.write(x)
f.close()
Right now i still have a lot of work...

Do you have any idea how should i proceed if i want in the same time be able to open the "output" file in order to use it and while not stopping the prgram i'm running (which is writting in "output").
I don't want to have to start each time my "test.py" script each time i read his "output" file...

A "while" might be useful? shoud i use a "output_bis" in order to write in it if my "output" isn't available...?

Sorry for my bad scriptoman language (and my english as well)...

sprinkmeier
Posts: 410
Joined: Mon Feb 04, 2013 10:48 am
Contact: Website

Re: From Arduino to Raspian via Python... Easyest way ?

Tue Jun 18, 2013 11:55 am

Code: Select all

#! /usr/bin/python2.7
import serial
# memory filesystem, data lost when power goes off, but doesn't wear out your SD card
DIR='/dev/shm'
# your home directory
import os
DIR=os.path.expanduser('~')
# pretty much anywhere else is going to be readonly to a normal user like "pi"
# install apache, let pi own this directory and access the data as "http://rasperrypi/data/output"
DIR='/var/www/data' 
# open serial port
ser = serial.Serial('/dev/ttyACM0', 9600)
# loop forever
while 1:
    # read a line
    x=ser.readline()
    # append to output file (reading this file from another program while writing to it shouldn't be a problem)
    # the "with" syntax makes sure the file is closed
    with open (DIR + '/output.log', 'a') as w:
        w.write(x)
    # write to a file ...
    with open (DIR + '/output.new', 'w') as w:
        w.write(x)
    # ... and then rename it to atomically update the output file
    # this guarantees any program reading "output" will get the new data, or the old, but never nothing.
    os.rename(DIR + '/output.new',DIR + '/output')

BioMomo
Posts: 11
Joined: Thu Jun 13, 2013 8:36 am

Re: From Arduino to Raspian via Python... Easyest way ?

Tue Jun 18, 2013 4:35 pm

Thanks very much, I might use it for my next project. Right now it finally worked well. I did it with a friend who finally decided to use Syslog... :

Code: Select all

#! /usr/bin/python2.7
import serial
import sys
import time
import datetime
import re

from logging.handlers import SysLogHandler
import logging

logger = logging.getLogger()
logger.addHandler(SysLogHandler('/dev/log'))
logger.addHandler(logging.FileHandler("filename.log"))

def update():

        rawdata = ser.readline()
        data = re.sub('[^A-Za-z0-9 ]+','',rawdata)
        if len(data) > 0:
                logging.warn(" "+data)

ser = serial.Serial('/dev/ttyACM0', 9600)
Thanks

Return to “Python”