python 串口通讯
Posted Yang-hao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 串口通讯相关的知识,希望对你有一定的参考价值。
1. 查看可用串口命令
ls /dev/chesis/ -l
也可以使用 ls /dev/*USB* -l 查看,但是串口可能会发生改变,故使用chesis查看更为安全
2.需要安装及导入的包:
串口包:serial
结构体包:struct
c++数据类型包:ctypes
3.发送命令的代码:
1 import serial 2 import struct 3 import time 4 from ctypes import * 5 def func1(): 6 portx = "/dev/chesis" 7 bps=115200 8 timex=None 9 ser=serial.Serial(portx,bps,timeout=timex) 10 class MyStruct(Structure): 11 _fields_ = [ 12 ("head1", c_byte), 13 ("head2", c_byte), 14 ("v1", c_byte), 15 ("v2", c_byte), 16 ("v1_dire", c_byte), 17 ("v2_dire", c_byte), 18 ("res1", c_byte), 19 ("res2", c_byte), 20 ("res3", c_byte), 21 ("res4", c_byte) 22 ] 23 24 mys = MyStruct() 25 mys.head1 = c_byte(255) 26 mys.head2 = c_byte(254) 27 mys.v1 = c_byte(30) 28 mys.v2 = c_byte(20) 29 mys.v1_dire = c_byte(0) 30 mys.v2_dire = c_byte(0) 31 mys.res1 = c_byte(0) 32 mys.res2 = c_byte(0) 33 mys.res3 = c_byte(0) 34 mys.res4 = c_byte(0) 35 msg = struct.pack(‘bbBBBBBBBB‘, mys.head1, mys.head2, mys.v1, mys.v2, mys.v1_dire, mys.v2_dire, mys.res1, mys.res2, mys.res3, mys.res4) 36 ser.write(msg) 37 # read data from serial 38 #threading.Thread(target=ReadData,args=(ser,)).start() 39 #ReadData(ser) 40 ser.close() 41 42 43 for i in range(200): 44 time.sleep(0.1) 45 func1()
4.接收串口返回的数据:
1 import time 2 import struct 3 from ctypes import * 4 import serial 5 6 7 def func2(): 8 portx = ‘/dev/chesis‘ 9 bps = 115200 10 timex = None 11 ser = serial.Serial(portx, bps, timeout=timex) 12 # while True: 13 14 while True: 15 msg = ser.read(12) 16 if msg: 17 print(‘the msg is:‘, msg) 18 data = struct.unpack(‘BBBBBBBBBBBB‘, msg) 19 # print(data) 20 gyroz = data[6] * 256 + data[7] - 32756 21 v1 = data[2] 22 v1_dire = data[3] 23 v2 = data[4] 24 v2_dire = data[5] 25 print(‘the msg is:‘, data) 26 elif msg == ‘exit‘: 27 break 28 ser.close() 29 30 31 func2()
以上是关于python 串口通讯的主要内容,如果未能解决你的问题,请参考以下文章
python与arduino串口通讯对接opencv实现智能物品分拣
Arduino UNO + Proteus串口通讯仿真实验汇总