Problems displaying data sent from Arduino to Pi - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Problems displaying data sent from Arduino to Pi (/thread-18453.html) |
Problems displaying data sent from Arduino to Pi - VostokRising - May-18-2019 Hi, I'm following the book Beginning Robotics with Raspberry Pi & Arduino. I'm familiar with the Arduino and C++, but learning Python along with the book. I'm at the part where I'm sending Distance Measurements from an Arduino hooked up to an HC-SR04 sensor over the USB serial connection to be displayed by the Python program. This is the code that I have # Import serial and time libraries import serial import time ser = serial.Serial('/dev/ttyACM0',9600,timeout=1) while 1: recSer = ser.readline().decode('utf-8') recSer.rstrip() distance = int(recSer + '0')/10 print("Distance: " + str(distance) + "cm", end = '\r') time.sleep(0.5)Here is the error: I have googled around the net and I understand it is to with trying to display a float as an int in a string, but I'm at a loss on how to fix it.I've tried int(float(recSer + '0') but still no joy. I am using Python 3.5.3 on the Raspberry Pi, Any help appreciated, RE: Problems displaying data sent from Arduino to Pi - buran - May-18-2019 (May-18-2019, 06:30 PM)VostokRising Wrote: recSer.rstrip()rstrip() does not work in-place so it should be recSer = recSer.rstrip()then what is the point to conacatenate 0 and then devide by 10? convert to float? then simply use float() if it is just for string formatting Python 3.7.3 (default, Mar 26 2019, 01:59:45) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> recSer = '342\r\n' # to replicate what you get >>> distance = recSer.rstrip() >>> float(distance) 342.0 >>> distance = int(distance) # convert from str to int >>> print(f'Distance is {distance:.1f}cm') Distance is 342.0cm RE: Problems displaying data sent from Arduino to Pi - VostokRising - May-18-2019 Hi buran, Thanks for that. It works perfectly. Like I said I'm working through the book and wrote down his code as he has it in the chapter. |