zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    openwrt 汉化
    错误: libstdc++.so.6: cannot open shared object file: No such file or directory
    openwrt uci
    openwrt makefile选项
    Ubuntu服务器断网问题解决
    lldpcli 常用命令
    openwrt ramips随记
    shell脚本学习(二)
    完成响应式的方式
    盒子模型 W3C中和IE中盒子的总宽度分别是什么
  • 原文地址:https://www.cnblogs.com/yang220/p/12425064.html
Copyright © 2011-2022 走看看