'Reading numbers through serial communication on Raspberry Pi
I have been trying to write a program that allows my Raspberry Pi to receive numbers through serial communication. I am communicating these numbers to the Raspberry Pi using an Arduino. The Arduino serial prints a prefix character followed by the number: Serial.println("T"); Serial.println(483); In the program, I am able to identify the prefix, but when I try to read the following number I am only able to get the first digit:
ser = serial.Serial('/dev/ttyACM0', 9600, timeout = 0)
while True:
if ser.in_waiting > 0:
# If there's more than 20 bytes in the buffer, clear it.
if ser.in_waiting >= 20:
ser.reset_input_buffer()
temp = ser.readline().decode('utf-8')
# Check to see what the prefix of the data is
if (temp.strip().isalpha()):
# If we got a 'T', it's a temperature update. Save temperature as number and print
if (temp.strip() == 'T'):
temp = ser.readline().decode('utf-8')
if temp.strip().isdigit():
number = (temp.strip())
print(number)
In this case, when I print(number) it outputs the number 4 and not 483. Does anyone know what is wrong?
Software with substitutions:
if ser.in_waiting > 0:
# If there's more than 20 bytes in the buffer, clear it.
if ser.in_waiting >= 20:
ser.reset_input_buffer()
temp = ser.readline().decode('utf-8')
# Check to see what the prefix of the data is
if (temp.strip().isalpha()):
# If we got a 'T', it's a temperature update. Update the temperature
if (temp.strip() == 'B'):
b = ser.readline()
print([int(c) for c in b])
temp = b.decode('utf-8')
if temp.strip().isdigit():
number = (temp.strip())
print ("temp = " + temp)
Output after Serial.println("T"); Serial.println(483); ran three times:
[52]
temp = 4
[]
[]
[]
[]
[52]
temp = 4
[52]
temp = 4
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
