Arduino 到 Python - 来自 readline() 的串行输入是整数还是实际字符串?

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('[=11=]'))
                if (time.isDigit()):
                    # do stuff

我收到错误:

value = int(time.strip('[=12=]'))
ValueError: invalid literal for int() with base 10: 'Obtaining color values for: Saline/Air\r\n'

这是有道理的,因为字符串文字 'Obtaining color values for:Saline/Air\r\n',即使在剥离之后,也永远不会通过 int() 函数进行转换。

另外让我知道 .isDigit() 是否有必要(或者就此而言,正确使用)。我几周前才开始与 Python 合作,所以从我的角度来看,这一切都悬而未决。

你应该捕获异常。

while True:
    if s.inWaiting() > 0:
        myData = s.readline()
        try:
            value = int(mydata.strip('[=10=]'))
        except ValueError:
            # handle string data (in mydata)
        else:
            # handle temperature reading (in value)

因此,如果该值可以转换为 int,则 else 块运行。如果该值为字符串,则运行 except 块。

您可以执行以下操作将字符串转换为整数:

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'>