![](/img/trans.png)
[英]python 3 readline() twice from arduino Serial Monitor
[英]Arduino to Python - is serial input from readline() an integer or an actual string?
所以我要從Arduino 2560 Mega發送一堆串行數據到我的Python程序,在那里我將只處理整數數據。 最初,我的Arduino校准了很多東西,依次打印確認信息...然后開始從LM35獲取溫度值。 然后將這些溫度值串行打印出來。
我要么:a)想知道當溫度讀數開始被串行打印時開始接收整數時如何使用Python的readline()
函數。
要么
b)從頭開始測試readline()
的傳入字符串,確定何時開始接收我關心的數字。
是的,將這些溫度值視為整數而不是浮點數。
現在,這是我在做什么:
while(1==1):
if (s.inWaiting() > 0):
myData = s.readline()
time = myData
value = int(time.strip('\0'))
if (time.isDigit()):
# do stuff
我收到錯誤:
value = int(time.strip('\0'))
ValueError: invalid literal for int() with base 10: 'Obtaining color values for: Saline/Air\r\n'
這是有道理的,因為即使在剝離后,字符串文字“獲取:Saline / Air \\ r \\ n的顏色值”也永遠不會通過int()
函數進行轉換。
也讓我知道.isDigit()
是否甚至是必需的(或為此正確使用)。 我幾周前才剛開始使用Python,所以從我的角度來看,這一切都是懸而未決的。
您可以執行以下操作將字符串轉換為整數:
while(1==1):
if (s.inWaiting() > 0):
myData = s.readline()
try:
# This will make it an integer, if the string is not an integer it will throw an error
myData = int(myData)
except ValueError: # this deals will the error
pass # if we don't change the value of myData it stays a string
這是您可以嘗試的示例。
在Python中:
import serial
# Converts to an integer if it is an integer, or it returns it as a string
def try_parse_int(s):
try:
return int(s)
except ValueError:
return s
ser = serial.Serial('/dev/ttyACM0', 115200)
while True:
data = ser.readline().decode("utf-8").strip('\n').strip('\r') # remove newline and carriage return characters
print("We got: '{}'".format(data))
data = try_parse_int(data)
print(type(data))
在我的Arduino上:
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(1);
delay(1000);
Serial.println("test");
delay(1000);
}
這將產生:
We got: 'test'
<class 'str'>
We got: '1'
<class 'int'>
您應該捕獲異常。
while True:
if s.inWaiting() > 0:
myData = s.readline()
try:
value = int(mydata.strip('\0'))
except ValueError:
# handle string data (in mydata)
else:
# handle temperature reading (in value)
因此,如果可以將值轉換為int,則else
塊將運行。 如果該值為字符串,則運行except
塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.