python 读取串口数据的示例
作者:二队 时间:2021-08-30 11:10:26
python3 读取串口数据 demo
最近在写一个demo,zigbee串口连接树莓派,树莓派使用串口通信接受zigbee穿过来得值。其中我是用的树莓派是3代B+,zigbee每隔三秒钟从串口输出数据。
下面是python串口通信,但是不是linux的,是我在windows上写的测试demo,python版本是3。
python串口读取数据
# TODO 串口读取数据
# Auther wjw
import serial # 导入串口包
import time # 导入时间包
ser = serial.Serial("COM3",115200,timeout = 5) # 开启com3口,波特率115200,超时5
ser.flushInput() # 清空缓冲区
def main():
while True:
count = ser.inWaiting() # 获取串口缓冲区数据
if count !=0 :
recv = ser.read(ser.in_waiting).decode("gbk") # 读出串口数据,数据采用gbk编码
print(time.time()," --- recv --> ", recv) # 打印一下子
time.sleep(0.1) # 延时0.1秒,免得CPU出问题
if __name__ == '__main__':
main()
上边的代码就已经实现python串口读数了,但大部分还需要写入。
串口写入数据
其实就是一个write方法,我开了一个线程,在线程里获取串口出来的数据,然后一个死循环每隔一秒发1,每隔一秒发0.
import serial
import time
import _thread # 导入线程包
data_ser = serial.Serial("COM3",115200,timeout = 5)
data_ser.flushInput()
def get_data():
while True:
data_count = data_ser.inWaiting()
if data_count !=0 :
recv = data_ser.read(data_ser.in_waiting).decode("gbk")
print(time.time()," --- data_recv --> ", recv)
time.sleep(0.1)
if __name__ == '__main__':
_thread.start_new_thread(get_data,()) # 开启线程,执行get_data方法
while 1:
time.sleep(20)
data_ser.write(b'1') # 发送二进制1
time.sleep(20)
data_ser.write(b'0') # 发送二进制0
完成了,应该差不多就这样!
树莓派自带python,但是默认是python2,可以两行命令修改默认python3
sudo rm /usr/bin/python
sudo ln -s /usr/bin/python3.4 /usr/bin/python
来源:https://www.cnblogs.com/wjw1014/p/12101825.html
标签:python,串口,数据
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
优化MySQL数据库查询的三种方法
2009-03-09 15:19:00
Python 完美解决 Import “模块“ could not be resolved ...的问题
2022-04-05 18:59:29
![](https://img.aspxhome.com/file/2023/7/128537_0s.png)
基于Python制作一个桌面宠物
2022-06-12 11:41:22
![](https://img.aspxhome.com/file/2023/2/100942_0s.jpg)
对Python 除法负数取商的取整方式详解
2023-10-02 20:21:41
python 列表推导和生成器表达式的使用
2021-03-16 11:21:39
![](https://img.aspxhome.com/file/2023/2/118052_0s.png)
Tesserocr库的正确安装方式
2023-12-26 17:19:34
![](https://img.aspxhome.com/file/2023/3/124363_0s.png)
Python object类中的特殊方法代码讲解
2021-01-27 13:40:33
比较规范的验证Email地址是否正确的正则表达式
2009-07-28 17:55:00
Python实现CNN的多通道输入实例
2021-10-10 11:33:07
Django shell调试models输出的SQL语句方法
2022-07-13 00:59:50
PyTorch中的C++扩展实现
2021-06-24 15:52:30
选项卡动态增删的效果(内嵌框架)
2008-05-22 12:59:00
![](https://img.aspxhome.com/file/UploadPic/20085/22/asgard_cardprogram_62s.jpg)
Python 使用 pip 安装 matplotlib 模块的方法
2021-08-22 02:42:52
![](https://img.aspxhome.com/file/2023/0/79430_0s.png)
Python实现字典的key和values的交换
2021-08-18 03:45:49
Python Pandas学习之series的二元运算详解
2023-12-16 01:58:30
![](https://img.aspxhome.com/file/2023/9/105859_0s.png)
Python和perl实现批量对目录下电子书文件重命名的代码分享
2022-01-28 02:51:48
运行asp.net时出现 http错误404-文件或目录未找到
2023-07-24 01:53:36
Go语言实现的可读性更高的并发神库详解
2023-07-20 08:03:49
![](https://img.aspxhome.com/file/2023/2/92032_0s.jpg)
Go语言快速入门图文教程
2023-07-23 10:30:16
![](https://img.aspxhome.com/file/2023/7/95367_0s.jpg)
并行查询让SQL Server加速运行
2009-03-16 16:31:00