如何将读取Arduino串口的getValues函数返回值转为整数?
串口数据转整数及代码优化方案
要将串口读取的字符串转换为整数,核心是先清理串口返回的冗余字符(通常带换行\n或回车\r),再通过int()完成类型转换,同时要处理转换失败的异常场景(比如串口返回无效数据)。
修改后的getValues函数
def getValues(): ser.write(b'g') # 解码串口数据并去除首尾空白字符(换行、空格等) arduinoData = ser.readline().decode('ascii').strip() try: # 尝试转换为整数 return int(arduinoData) except ValueError: # 处理无法转换的无效数据 print(f"无效传感器数据: {arduinoData}") return -1 # 返回标记值代表读取失败
修正原代码的其他问题
除了类型转换,你的代码还有几处需要修复的逻辑/语法错误:
- 文件模式错误:原代码用只读模式
'r'打开文件却尝试写入,需改为写入模式'w'(覆盖原有内容)或追加模式'a'。 - 循环调用错误:直接用
getValues(函数对象)和40比较,而非调用函数getValues()获取返回值;多个while循环会导致逻辑阻塞,应结合if-elif-else实现判断逻辑。 - 语法与逻辑漏洞:最后一个
while循环括号使用错误,且读取文件内容后不会自动更新,需重新读取才能获取最新值。
优化后的完整代码示例
import serial import subprocess import time ser = serial.Serial('COM3', baudrate=9600, timeout=1) file_path = 'C://Users//adith//Documents//Code//Local-Sys-Files//Python//Sensor stuff uwu//comfirm.txt' def getValues(): ser.write(b'g') arduinoData = ser.readline().decode('ascii').strip() try: return int(arduinoData) except ValueError: print(f"无效数据: {arduinoData}") return -1 # 持续读取传感器数据并写入判断结果 while True: sensor_val = getValues() if sensor_val == -1: continue # 打开文件写入结果 with open(file_path, 'w') as f: if sensor_val < 40 or sensor_val == 40: f.write("False") else: f.write("True") time.sleep(0.5) # 控制读取频率 # 单独的Spotify启动逻辑(可根据需求调整执行时机) while True: with open(file_path, 'r') as f: content = f.read().strip() if content == "True": subprocess.call("C://Users//Toasted//AppData//Roaming//Spotify//Spotify.exe") time.sleep(1) # 避免频繁读取文件
关键说明
strip():去除字符串首尾的空白字符,避免因换行/回车导致int()转换失败。try-except:防止串口返回非数字内容导致程序崩溃,提升代码健壮性。with语句:自动管理文件的打开与关闭,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Adithya Nambiar
相关产品推荐
相关产品推荐

