import RPi.GPIO as GPIO
import serial
import string
import binascii
import time
ser = serial.Serial("/dev/ttySC0",9600,timeout=1)# Send modbus device inquiry frame (hex code)
ser.write(bytes.fromhex('01 03 00 00 00 02 C4 0B '))# Modbus device returns response frame rate (hex code)
ser.flushInput()
data =""print("You can always receive data, press Ctrl + C to exit")while1:while ser.inWaiting()>0:
data = ser.readline()if data !="":print(str(binascii.b2a_hex(data))[2:-1])
data =""
树莓派判断并接收ascill 和 hex的 程序
import serial
ser = serial.Serial(# Your serial port name
port='/dev/ttyUSB0',# Baud rate
baudrate=9600,# Data bits
bytesize=serial.EIGHTBITS,# Parity
parity=serial.PARITY_NONE,# Stop bits
stopbits=serial.STOPBITS_ONE
)whileTrue:# Read one byte of data
data = ser.read()# Check if it's an ASCII characterif data.isalpha():# Print the characterprint(data)# Otherwise, it's a hex valueelse:# Convert the hex value to an integer
data =int(data,16)# Print the integerprint(data)
import serial
ser = serial.Serial('/dev/ttyUSB0',115200) # 串口名称和波特率
while True:
# 发送ASCII数据
ser.write('Hello, world!\r\n'.encode())
# 发送Hex数据
ser.write(bytes.fromhex('01 02 03 04 05 06'))
# 读取并解码ASCII数据
data = ser.readline().decode().strip()if data:print('Received ASCII: {}'.format(data))
# 读取Hex数据
data = ser.read(6)if data:print('Received Hex: {}'.format(data.hex()))
ser.close() # 关闭串口
import serial
# 配置串口
ser = serial.Serial('/dev/ttyS0',9600) # 根据实际串口配置更改端口和波特率
# 发送ASCII数据
def send_ascii(data):
ser.write(data.encode())
# 发送16进制数据
def send_hex(data):
ser.write(bytes.fromhex(data))
# 接收数据
def receive():
data = ser.readline().decode().strip()if data.startswith(":"):
# 如果收到16进制数据,则返回16进制字符串
return data.strip(":")else:
# 否则返回ASCII字符串
return data
# 示例
send_ascii("Hello, World!")send_hex("1a2b3c")
data =receive()print(data)