简体   繁体   English

python 3.x中的串行readline方法

[英]Serial readline method in python 3.x

pySerial write() won't take my string pySerial write()不会接受我的字符串

In that post, coders explained how to use the 在该帖子中,编码人员解释了如何使用

ser.write() ser.write()

method. 方法。

I am still wondering how to use the 我仍然想知道如何使用

readline() readline()

method in python3.x as I want to recieve a float, and compare it in my python 3.x code. 我想在python3.x中获得一个float值,并在python 3.x代码中对其进行比较。 I know how to use the readline() in python 2.7. 我知道如何在python 2.7中使用readline()。 But I am not able to get it working in 3.x. 但是我无法在3.x中运行它。

import serial
import time

ser=serial.Serial('/dev/ttyACM0', 9600)
while 1:
    ans = ser.readline()
    print(ans)
    if ans > 25.50:
        print('its getting hot in  here')
    else:
        print('Everything is fine')

Thanks in advance 提前致谢

The first thing that occurs to me is that ans will be a string variable after readline() . 对我而言,第一件事是ans将是readline()之后的字符串变量。 You can't compare a string to a floating-point variable without some conversion. 如果不进行某些转换,就无法将字符串与浮点变量进行比较。 So: 所以:

if ans > 25.50:

will not work because ans is a string. 将不起作用,因为ans是一个字符串。 Instead, you need something like: 相反,您需要以下内容:

float_ans = float(ans)
if float_ans > 25.50:
# etc...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM