码迷,mamicode.com
首页 > 编程语言 > 详细

python 串口通讯

时间:2020-03-06 10:43:59      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:time   数据   imp   from   targe   span   data   type   close   

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 串口通讯

标签:time   数据   imp   from   targe   span   data   type   close   

原文地址:https://www.cnblogs.com/yang220/p/12425064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!