使用python serial与M3650B-HA(RFID读写器)串口通信
环境:py3.6
模块:pyserial
1、serial模块安装
废话不多说,直接上代码,测试环境py3.6
# coding:utf-8
__author__='古墓派掌门'
import binascii
import serial.tools.list_ports
import serial
class Ser(object):
def __init__(self):
# 打开端口
# self.port = serial.Serial(port='COM3', baudrate=9600, bytesize=8, parity='E', stopbits=1, timeout=2)
plist = list(serial.tools.list_ports.comports())
if len(plist) <= 0:
print("没有发现端口!")
else:
plist_0 = list(plist[0])
serialName = plist_0[0]
self.port = serial.Serial(port=serialName, baudrate=9600)
print("可用端口名>>>", self.port.name)
# def show_port(self):
# plist = list(serial.tools.list_ports.comports())
# if len(plist) <= 0:
# print("没有发现端口!")
# else:
# plist_0 = list(plist[0])
# serialName = plist_0[0]
# serialFd = serial.Serial(serialName, 9600, timeout=60)
# print("可用端口名>>>", serialFd.name)
# 发送指令的完整流程
def send_cmd(self, cmd):
self.port.write(bytearray.fromhex(cmd))
# print(cmd)
response = self.port.read(12)
# response = self.convert_hex(response)
response=str(response).replace("\\x"," ")
return response
# 转成16进制的函数
def convert_hex(self, string):
res = []
result = []
for item in string:
res.append(item)
for i in res:
result.append(hex(i))
return result
if __name__=='__main__':
ser1=Ser()
while 1:
# order=input("请输入指令:\n")
# print(ser1.send_cmd(order))#02 08 F9 20 00 00 00 2c
# order='01 08 A1 20 00 00 00 77'.encode('ascii')
# # ser.write(order)
# print(order)
order=input("请输入命令,格式见收据手册\n")#01 08 A1 20 00 01 00 76
print(ser1.send_cmd(order))