RFID 串口读取 Python
import rospy
from rfid_reader_demo.msg import rfid_tag_info
import serial
import time
pub = rospy.Publisher('/rfid_tag_info', rfid_tag_info, queue_size=20)
def rfidFuc():
g_ser_rfid.write([0xbb, 0x00, 0x27, 0x00, 0x03, 0x22, 0x27, 0x10 , 0x83, 0x7e])
read = g_ser_rfid.read(512)
read_hex = read.encode('hex')
if(len(read_hex)):
return read_hex
else:
return 'error1231231123';
def hex_to_dec(hex_str):
if hex_str[0] in '0123456789':
dec_data = int(hex_str, 16)
else:
width = 16
d = 'FF' + hex_str
dec_data = int(d, 16)
if dec_data > 2 ** (width - 1) - 1:
dec_data = 2 ** width - dec_data
dec_data = 0 - dec_data
return str(dec_data)
def idPub():
rospy.loginfo("---开始阅读RFID标签---")
rate = rospy.Rate(5)
rfid_tag_msg = rfid_tag_info()
while not rospy.is_shutdown():
rfid_msgs = rfidFuc()
length = len(rfid_msgs)
for i in range(length):
if i+50<=length:
if rfid_msgs[i]+rfid_msgs[i+1]=='bb' and rfid_msgs[i+4]+rfid_msgs[i+5]!="ff" and rfid_msgs[i+46]+rfid_msgs[i+47]=="7e":
rfid_tag_msg.tagEpc = rfid_msgs[i+16:i+40]
rfid_tag_msg.tagRssi = rfid_msgs[i+10]+rfid_msgs[i+11]
rfid_tag_msg.tagRssi = hex_to_dec(rfid_tag_msg.tagRssi)
rfid_tag_msg.keyId = rfid_msgs[i+36:i+40]
pub.publish(rfid_tag_msg)
else:
break
rate.sleep()
g_ser_rfid.close()
if __name__ == '__main__':
input_port = "/dev/ttyUSB0"
input_baudrate = "115200"
print('====== defalt setting ======')
print("port: " + input_port)
print("baudrate: " + input_baudrate)
print('=========================')
g_ser_rfid = serial.Serial(input_port, input_baudrate, bytesize=8,
parity=serial.PARITY_EVEN, stopbits=1, timeout=0.07)
time.sleep(0.2)
try:
rospy.init_node('rfid_tag_info_publisher', anonymous=True)
idPub()
except rospy.ROSInterruptException:
pass
简单的程序却很好用