sandpiper42
Posts: 4
Joined: Sat Feb 23, 2013 3:27 am

Problem reading from serial with Python script

Sat Feb 23, 2013 3:49 am

I am relatively new to raspberry and I'm trying to connect it to an Arduino using the raspberry USB.
I have determined that the raspberry serial port is /dev/ttyUSB0 and from the Python console I can send the following commands one at a time:

import serial
ser=serial.Serial('/dev/USB0', 9600, timeout=1)
ser.write('1')
(echo '1' on terminal screen)
# When arduino receives a single character it returns a temperature reading and I read it from rasberry as follows:
print ser.readline()
(echo '21.23' on terminal screen)

Everything above works as expected from the console (ie the raspberry receives and prints the temperature value), but when I build a Python script and with the exact same lines of code and run it from the terminal it prints a line feed. I have tried adding a pause between writing and reading to the arduino to no avail. I am scratching my head on this one.

Note: I have tried unplugging all USB devices from the raspberry except the arduino and using ssh from my PC, and various combinations thereof including USB keyboard on raspberry & no ssh. Same result - it will work from python console, but not a python script.

Any ideas? Thanks.

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

Re: Problem reading from serial with Python script

Sat Feb 23, 2013 7:18 pm

try to use the code tags, it makes it alot easier to diagnose problems, also, change serial.readline() to serial.read() instead, may do what you want.

Code: Select all

import serial
ser=serial.Serial('/dev/USB0', 9600, timeout=1)
ser.write('1')        #(echo '1' on terminal screen)
# When arduino receives a single character it returns a temperature reading and I read it from rasberry as follows:
print ser.read()
(echo '21.23' on terminal screen)
If it isnt smoking and blown into pieces, it's not pushed far enough yet. :P
http://cae2100.wordpress.com

sandpiper42
Posts: 4
Joined: Sat Feb 23, 2013 3:27 am

Re: Problem reading from serial with Python script

Sun Feb 24, 2013 3:17 am

Thanks for the tip re: code tags.

I tried serial.read() as you suggested but still doesn't work.

Investigated a little more and found that using serial.open() immediately following the serial.Serial statement does work and problem seems to be fixed.

sandpiper42
Posts: 4
Joined: Sat Feb 23, 2013 3:27 am

Re: Problem reading from serial with Python script

Mon Feb 25, 2013 11:55 am

I spoke too soon. It worked for a short time. Now it is back the way it was when I reported the issue - ie not working.

I have verified that the script works one line at a time in Python console and I have also confirmed that I can send the same data back and forth between the arduino and raspberry in Minicom.

Why doesn't the Python script work as expected? The script runs without error but prints a blank line (line feed) instead of the expected result. I have fitted an LED on the arduino which flashes when receiving data from raspberry. It flashes as expected when I run the python script from raspberry with the ser.write() statement.

paul42
Posts: 26
Joined: Mon Nov 26, 2012 5:38 pm

Re: Problem reading from serial with Python script

Mon Feb 25, 2013 12:35 pm

Try a small pause after serial= line.

Code: Select all

import time
time.sleep(.2)
I would use ser or some other name not serial for the port, otherwise could be confusing.

-rst-
Posts: 1316
Joined: Thu Nov 01, 2012 12:12 pm
Location: Dublin, Ireland

Re: Problem reading from serial with Python script

Mon Feb 25, 2013 2:37 pm

Looks (here http://pyserial.sourceforge.net/shortin ... rial-ports) like the open() is not required.

Can you verify what exactly the Arduino returns as reponse (especially is there a newline character included)? And how fast does it respond? And might be worth checking the communication speed is the correct one...

As read() reads only one byte, it's most likely not the best choice - readline() expects a newline at end of line, but with the timeout defined when opening the port should work (returns when newline read or timed out) - maybe try a bit longer timeout in case Arduino is slow to respond...

So maybe:

Code: Select all

import serial
ser=serial.Serial('/dev/USB0', 9600, timeout=3)
ser.write('1')
temp=ser.readline()
print temp
http://raspberrycompote.blogspot.com/ - Low-level graphics and 'Coding Gold Dust'

sandpiper42
Posts: 4
Joined: Sat Feb 23, 2013 3:27 am

Re: Problem reading from serial with Python script

Wed Feb 27, 2013 3:15 am

I've tried what you suggested but to no avail. The arduino returns a number in the form "20.12\r\n". I am using the println() command form the arduino. I have posted a snippet from the arduino code below. The arduino is reading humidity data too but I have commented that out for now until I get the basics working.

The arduino responds immediately. The only delay is the timeout of course. I have also tried longer delays & timeouts.

Code: Select all

void setup(){
  Serial.begin(9600); // open serial at 9600 bps
  pinMode(redled, OUTPUT);     
}

void loop(){
  if (Serial.available() > 0) {
    Serial.read();
    //these can take a bit to get the values (100ms or so)
    float temperature = getTemperature();
    float humidity = getHumidity();

    // Send measurements to serial port
    Serial.println(temperature);
//  Serial.println(humidity);
  
    // Flash LED to indicate measurement taken
    digitalWrite(redled, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(100);                   // wait for a second
    digitalWrite(redled, LOW);    // turn the LED off by making the voltage LOW
  } 
}

-rst-
Posts: 1316
Joined: Thu Nov 01, 2012 12:12 pm
Location: Dublin, Ireland

Re: Problem reading from serial with Python script

Wed Feb 27, 2013 1:42 pm

With that response from Arduino (ends with a newline, which the readline() expects), the above code should work... :roll:
http://raspberrycompote.blogspot.com/ - Low-level graphics and 'Coding Gold Dust'

Cromarty
Posts: 64
Joined: Thu Jan 03, 2013 5:03 pm
Location: Godalming, South-east UK
Contact: Website

Re: Problem reading from serial with Python script

Sun Mar 10, 2013 8:48 pm

If you stick a comma after a print in Python it doesn't print a carriage return:

print "One",
print "Two",
print "Three",
print "Four"

Result:

One Two Three Four ,carriage return>
--
Michael Ray
Analyst/Programmer
Surrey, UK
4xB, 1xB+,
Creator and admin of:
raspberry-vi@freelists.org
Ham radio call: G4XBF
'Suddenly I am become death, destroyer of SD cards'

IanH2
Posts: 79
Joined: Tue Dec 18, 2012 10:17 am

Re: Problem reading from serial with Python script

Mon Mar 11, 2013 2:09 pm

I'm not sure what Arduino you've got, but you may find that opening the serial port is causing it to reset - and for a time (500ms or more) after reset the Arduino bootloader will be running, not your temperature-reading sketch. If you're typing things in at the console, you won't notice this because the bootloader will have finished before you got to read anything.

So I'd try putting a time.sleep(2.0), after you've opened the port, before you try to talk to your sketch. If that helps, you may find the time delay can be reduced, depending on what bootloader you've got.

Also, you may find you need to call flushInput() on the serial port at the start, to discard old data left lying about in the buffers by whatever was running previously.
-----
https://github.com/IanHarvey

skbeez
Posts: 3
Joined: Mon Feb 18, 2013 6:21 am

Re: Problem reading from serial with Python script

Sun Mar 17, 2013 6:05 pm

I see an error. Try using "/dev/ttyUSB0" instead of "/dev/USB0"

sshjason
Posts: 1
Joined: Wed Apr 15, 2015 6:55 pm

Re: Problem reading from serial with Python script

Wed Apr 15, 2015 7:05 pm

I had the exact same problem and wanted to post what worked for me. There seems to be a delay on the Arduino side when first connecting and after writing. Replace with a for loop if you are not certain that you need to read back data. If this does not work, try extending the time after opening the serial connection.

Code: Select all

import serial
import time

def read_serial(ser, len):
    while True:
        if ser.inWaiting() > 0:
            break;
        time.sleep(0.5)
    return ser.read(len)

device = "/dev/tty.usbserial-A103QDVG"
buadrate = 9600
ser = serial.Serial(device, buadrate, timeout=1)
time.sleep(2) #wait for the Arduino to init

ser.write("Hello\n") #On the Arduino I'm reading with: Serial.readStringUntil('\n');
print "read: %s" % read_serial(ser, 32)

Tejass
Posts: 1
Joined: Wed Jan 17, 2018 6:19 am

Re: Problem reading from serial with Python script

Wed Jan 17, 2018 6:37 am

Hi, i have raspberry pi zero w and am working with SIM800l. My problem is i have connected sim800l with pi zero using gpio pins (2 pin-5v, 6 pin-gnd,8 pin-RX of sim800l & 10pin-TX of sim800l) and able to send/receive sms and calls using minicom AT commands. Now, i have to run AT commands using python code. i have tried this code for 1 AT command as AT:

import serial

ser = serial.Serial('/dev/ttyS0', 115200, timeout=5)
ser.write("AT\r")
response = ser.read(2)
print response
ser.close()

Problem is code is running without error but there is no response for AT . there should be OK response i should get but unable to get it. i have tried \r\n in ser.write also ser.readline but no use whats the problem?? Thank you for help.

Return to “Python”