python 串口通讯

1. 查看可用串口命令

ls /dev/chesis/ -l

也可以使用 ls /dev/*USB* -l 查看,但是串口可能会发生改变,故使用chesis查看更为安全

2.需要安装及导入的包:

串口包:serial

结构体包:struct

c++数据类型包:ctypes

3.发送命令的代码:

import serial
import struct
import time
from ctypes import *
def func1():
    portx = "/dev/chesis"
    bps=115200
    timex=None
    ser=serial.Serial(portx,bps,timeout=timex)
    class MyStruct(Structure):
        _fields_ = [
            ("head1", c_byte),
            ("head2", c_byte),
            ("v1", c_byte),
            ("v2", c_byte),
            ("v1_dire", c_byte),
            ("v2_dire", c_byte),
            ("res1", c_byte),
            ("res2", c_byte),
            ("res3", c_byte),
            ("res4", c_byte)
        ]

    mys = MyStruct()
    mys.head1 = c_byte(255)
    mys.head2 = c_byte(254)
    mys.v1 = c_byte(30)
    mys.v2 = c_byte(20)
    mys.v1_dire = c_byte(0)
    mys.v2_dire = c_byte(0)
    mys.res1 = c_byte(0)
    mys.res2 = c_byte(0)
    mys.res3 = c_byte(0)
    mys.res4 = c_byte(0)
    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)
    ser.write(msg)
    # read data from serial
    #threading.Thread(target=ReadData,args=(ser,)).start()
    #ReadData(ser)
    ser.close()


for i in range(200):
    time.sleep(0.1)
    func1()

4.接收串口返回的数据:

import time
import struct
from ctypes import *
import serial


def func2():
    portx = ‘/dev/chesis‘
    bps = 115200
    timex = None
    ser = serial.Serial(portx, bps, timeout=timex)
    # while True:

    while True:
        msg = ser.read(12)
        if msg:
            print(‘the msg is:‘, msg)
            data = struct.unpack(‘BBBBBBBBBBBB‘, msg)
            # print(data)
            gyroz = data[6] * 256 + data[7] - 32756
            v1 = data[2]
            v1_dire = data[3]
            v2 = data[4]
            v2_dire = data[5]
            print(‘the msg is:‘, data)
        elif msg == ‘exit‘:
            break
    ser.close()


func2()

相关推荐