Python serial模块读取Arduino串口输出为空行的问题解决
解决Arduino随机数串口输出被Python读取为空的问题
Hey there, let's figure out why your Python script is only outputting b'' instead of those random numbers from Arduino. Let's break down the issues step by step and fix them!
首先看Arduino代码的核心问题
你的原Arduino代码:
void setup() { } void loop() { long rand = random(10); Serial.println(rand); delay(1000); }
这里最大的问题是你完全没初始化串口通信!Arduino的Serial模块需要在setup()里调用Serial.begin()来开启串口,并设置和Python脚本一致的波特率。没有这一步,Arduino根本不会往串口发送任何数据——那Python自然只能读到空字节了。
另外,默认情况下random()会生成固定序列的“伪随机数”,每次重启Arduino都会重复同样的数字,我们可以加个随机种子让它更随机。
修复后的Arduino代码
void setup() { // 初始化串口,波特率和Python保持一致:9600 Serial.begin(9600); // 用未连接的模拟引脚读取环境噪声作为随机种子,避免固定序列 randomSeed(analogRead(A0)); } void loop() { long rand = random(10); Serial.println(rand); delay(1000); }
再看Python代码的优化点
你的原Python代码:
#!/usr/bin/python import serial ser = serial.Serial("/dev/ttyACM0",9600, timeout = 1) if ser.is_open == 0: ser.open() print('serial was not open, so it is open now') else: print('serial was open this whole time') while ser.is_open: thing = ser.readline() print(thing) #ser.readline() ser.close()
这里有几个小问题:
- 你在循环第一次读取后就立刻关闭了串口——循环只执行一次,读完空数据就结束了,根本没机会读取后续的随机数。
- Arduino连接电脑时会自动重启,如果Python立刻开始读取,可能会读到重启过程中的空数据。
readline()返回的是字节对象,直接打印不够直观,最好解码成字符串。
修复后的Python代码
#!/usr/bin/python import serial import time # 初始化串口 ser = serial.Serial("/dev/ttyACM0", 9600, timeout=1) # 检查并处理串口状态 if not ser.is_open: ser.open() print('Serial port was closed, opened it now.') else: print('Serial port is already open.') # 等待Arduino重启完成(非常关键!) time.sleep(2) # 持续读取数据,直到按下Ctrl+C中断 try: while ser.is_open: # 读取一行数据,解码为字符串并去除多余的换行和空格 received_data = ser.readline().decode('utf-8').strip() # 只打印非空内容,避免输出空行 if received_data: print(f"Received random number: {received_data}") except KeyboardInterrupt: # 捕获Ctrl+C信号,优雅关闭串口 print("\nClosing serial port...") ser.close()
最终测试步骤
- 将修复后的Arduino代码上传到你的开发板。
- 关闭Arduino自带的串口监视器(同一个串口不能被两个程序同时占用)。
- 运行修复后的Python脚本,你应该能看到每隔一秒输出一个0-9之间的随机数啦!
内容的提问来源于stack exchange,提问作者Ramces Gonzalez
相关产品推荐
相关产品推荐

