串口操作在日常嵌入式设备调试的过程可以使用,而且非常方便,比较麻烦的应该是十六进制的接收处理。
python里面使用serial库来操作串口,serial的使用流程跟平常的类似,也是打开、关闭、读、写
1.打开串口
一般就是设置端口,波特率。
使用serial.Serial创建实体的时候会去打开串口,之后可以使用is_open开判断下是否串口是否打开正常。
def DOpenPort(portx, bps, timeout):
try:
# 打开串口,并得到串口对象
ser = serial.Serial(portx, bps, timeout=timeout)
# 判断是否打开成功
if(False == ser.is_open):
ser = -1
except Exception as e:
print("---异常---:", e)
return ser
2.关闭串口
使用ser.close即可关闭串口
def DColsePort(ser):
uart.fdstate = -1
ser.close()
3.写数据
数据的写使用ser.write接口,如果写的是十六进制的数据使用bytearray来定义,如writebuf = bytearray([0x55, 0xaa, 0x00, 0x01, 0x00, 0x00])
def DWritePort(ser, data):
result = ser.write(data) # 写数据
logging.info(ser)
logging.info("Write %s(%d)" % (data.hex(), result))
return result
4.读数据
读数据使用ser.read接口,一般会先使用in_waiting来判断下是否有数据,然后开始读
# 十六进制显示
def hexShow(argv):
try:
result = ''
hLen = len(argv)
for i in range(hLen):
hvol = argv[i]
hhex = '%02x' % hvol
result += hhex+' '
logging.info('Led Read:%s', result)
return result
except Exception as e:
print("---异常---