1

I use this small program on my Raspberry Pi to recieve a string sent by my arduino.

import time
import serial

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

def check_for_command():
    bytestoread = ser.inWaiting()
    if bytestoread != 0:
        temp = ser.read(bytestoread)
        print(temp)

while 1:
    check_for_command()
    time.sleep(0.1)

the code on the arduino is rather simple:

void setup(){
Serial.begin(9600);
}

void loop(){
Serial.println(“Hello Pi”);
delay(2000);

the annoying part is. I recieve this:

b'Hello Pi\r\n'

instead of the clean

Hello Pi

How do I get rid of those extra bits without using a list for each character.

Thank in advance!

  • The python code does not need to be anywhere near this complicated. Once you open the device to the handle ser, then all you need is -- linenin=ser.readline() --- and it is good that you are using -- Serial.println -- on the Arduino that sends the \n character at the end of the string so it will work just fine. Then all you need in Python is -- print linein -- to see what you have received. Nothing complicated is required. Just treat it like a file, and remember that ser.readline() is a blocking function. It will stop everything and wait for input. – SDsolar Jul 17 '17 at 4:11
1

The b prefix in Python 3 just means that it is a bytes literal. It's not part of the output, that's just telling you the type.

The \r\n is a common Carriage-Return and Newline line-ending characters. You can remove that from your string by calling strip().

Since these are floating-point numbers being returned, I'm guessing you're going to want to use them in some way after they are read, too:

import serial

ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
   value = float(ser.readline().strip())
   print('New value is {0:0.2f}'.format(value))

See also:

  • trying to use your lines it gives me a format error on the last line. just before the .format – Anton van der Wel Jul 16 '17 at 18:23
  • Can you copy and paste the exact error? – Ameer Jul 16 '17 at 18:36
  • fixed that error found a new one that sometimes occurs, the first problem was: I am using python 3 so print needs brackets. :) the other error is when by accident serial chains two numbers: ValueError: could not convert string to float: b'21.020.5' – Anton van der Wel Jul 16 '17 at 18:52
  • I have updated my code to include python 3 style prints. – Ameer Jul 16 '17 at 18:57
  • and now you suggest a try and catch to avoid the ValueError? – Anton van der Wel Jul 16 '17 at 19:01
0

Use this line

temp = ser.readline(bytestoread).decode('ascii')

instead of

temp = ser.read(bytestoread)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.