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

时间:2017-03-13 17:19:14

标签: python serialization arduino int readline

所以我将一堆串行数据从我的Arduino 2560 Mega发送到我的Python程序,我将只对整数数据进行操作。最初,我的Arduino校准了很多东西,连续打印确认信息......然后它开始从LM35获取温度值。然后连续打印那些温度值。

我要么: a)想要知道在温度读数开始连续打印时从收到整数时如何使用Python的readline()函数。

OR

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'

这是有道理的,因为字符串文字'获取颜色值:盐水/空气\ r \ n',即使在剥离后,也不会通过int()函数进行转换。

另请告诉我.isDigit()是否有必要(或者就此而言,正确使用)。几周前我刚刚开始使用Python,所以从我的角度来看,这一切都已经开始了。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

你应该抓住例外。

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块。