串口通讯常见问题
C语言编程常见问题
串口指令:
CAN总线控制命令
=>can --help
usage: can [-c ] [-i ] [-v ] [-e] [-r]
options:
-c/--cmd info|(de)init|reset|baudrate|reset_input|read|write|filter
-i/--idx index param
-v/--val value param
-e/--ext extended
-r/--rtr remote
data data args
=>
示例:
调整波特率(默认1M)
=>can -c baudrate -v 500000
=>
发送报文(11位标识符0xA0,数据共3字节0x01、0x02和0x03)
=>can -c write -i 0xA0 0x01 0x02 0x03
=>
取出总线上收到的报文,将接收缓冲逐行打印出来
=>can -c read
0B0 D 01020304
...
=>
Python封装:
安装:pip3 install mcush
升级:pip3 install -U mcush
class ShellLabCAN(mcush.ShellLab.ShellLab):
def can(self, cmd, index=None, value=None, ext=None, rtr=None, args=None):
# 封装的串口命令
def canBaudrate(self, new_baudrate):
# 设置波特率
def canFilterReset(self, add_default=True):
# 重置滤波器
def canFilterSet(self, index, enable, can_id, mask, ext=None, rtr=None):
# 设置滤波器
def canRead(self, lines=None, block_ms=None):
# 读缓冲报文
def canReset(self):
# 复位
def canResetInput(self):
# 读缓冲区复位
def canWrite(self, cob_id, dat=[], ext=None, rtr=None):
# 发送报文
class ShellLabCANopen(ShellLabCAN):
def preOperNode(self, id):
def readFLOAT32(self, id, index, subindex):
def readINT16(self, id, index, subindex):
def readINT32(self, id, index, subindex):
def readINT8(self, id, index, subindex):
def readObject(self, id, index, subindex):
def readUINT16(self, id, index, subindex):
def readUINT32(self, id, index, subindex):
def readUINT8(self, id, index, subindex):
def resetNode(self, id):
def startNode(self, id):
def stopNode(self, id):
def sync(self):
def writeFLOAT32(self, id, index, subindex, val):
def writeINT16(self, id, index, subindex, val):
def writeINT32(self, id, index, subindex, val):
def writeINT8(self, id, index, subindex, val):
def writeNMTCommand(self, cmd, id):
def writeNodeGuardRequest(self, id):
def writeObject(self, id, index, subindex, val):
def writeRPDO1(self, id, val):
def writeRPDO2(self, id, val):
def writeRPDO3(self, id, val):
def writeRPDO4(self, id, val):
def writeTPDO1Request(self, id):
def writeTPDO2Request(self, id):
def writeTPDO3Request(self, id):
def writeTPDO4Request(self, id):
def writeUINT16(self, id, index, subindex, val):
def writeUINT32(self, id, index, subindex, val):
def writeUINT8(self, id, index, subindex, val):
示例:
import mcush
from binascii import hexlify
s=mcush.ShellLab.ShellLabCAN('/dev/ttyACM0')
s.canBaudrate(500000)
s.canWrite(0xA0, [0x01, 0x02, 0x03]) # 发送三字节数据
for cid, ext, rtr, dat in s.canRead():
dat = hexlify(dat) # 转成HEX字符串
print( 'id=0x%X, ext=%d, rtr=%d, dat=%s'% (cid, ext, rtr, dat) )
下载
Shell Lab 测试台软件
虚拟串口驱动(Windows)
|