python(49)-串口接收与发送
1.发送16进制码
import serial
import string
import binascii
s=serial.Serial('com4',9600)
s.open()
#接收
n=s.inwaiting()
if n:
data= str(binascii.b2a_hex(s.read(n)))[2:-1]
print(data)
#发送
d=bytes.fromhex('10 11 12 34 3f')
s.write(d)
s.close()
2.发送ASCII码
import serial
byte = 42
out = serial.Serial("/dev/ttyS0") # "COM1" on Windows
out.write(bytes(byte))
3.
import serial
import binascii
ser = serial.Serial()
def port_open():
ser.port = 7 #设置端口号
ser.baudrate = 9600 #设置波特率
ser.bytesize = 8 #设置数据位
ser.stopbits = 1 #设置停止位
ser.parity = "N" #设置校验位
ser.open() #打开串口,要找到对的串口号才会成功
if(ser.isOpen()):
print("打开成功")
else:
print("打开失败")
def port_close():
ser.close()
if (ser.isOpen()):
print("关闭失败")
else:
print("关闭成功")
def send(send_data):
if (ser.isOpen()):
ser.write(send_data.encode('utf-8')) #utf-8 编码发送
#ser.write(binascii.a2b_hex(send_data)) #Hex发送
print("发送成功",send_data)
else:
print("发送失败")
if __name__ == "__main__":
port_open()
#port_close()
while True:
send("Hello World!")
Python实现串口通信(pyserial) - -零 - 博客园
【Python】字符串转换为ASCII码_crazyang的博客-CSDN博客_python字符串转ascii码
python基础--函数2(ascii,bin,ord,chr,oct,hex)_liranke的专栏-CSDN博客_bin(ord(i))[2:]
Python 串口数据打包与解析_boom的博客-CSDN博客_python串口数据解析