import serial
import time
def send_command_to_com_port(ser, command):
try:
# Send the command
command_encoded = command.encode('ascii')
ser.write(command_encoded)
print(command_encoded)
except serial.SerialException as e:
print(f"Error communicating with the COM port: {e}")
def read_from_com_port(ser):
try:
# Read response from the COM port
response = ser.read_until("\n") # Read until a newline character is encountered
if response:
print(f"Response received: {response.decode('ascii').strip()}")
else:
print("No response received from the COM port.")
except serial.SerialException as e:
print(f"Error communicating with the COM port: {e}")
# Specify the COM port and send the command
com_port = "COM4"
# Configure the serial connection
ser = serial.Serial(
port=com_port, # Replace with your COM port (e.g., 'COM3' on Windows or '/dev/ttyUSB0' on Linux)
baudrate=115200, # Baud rate
bytesize=serial.EIGHTBITS, # 8 data bits
parity=serial.PARITY_NONE, # No parity bit
stopbits=serial.STOPBITS_ONE, # One stop bit
timeout=1 # Timeout in seconds
)
# Ensure the COM port is open
print(f"Serial port opened: {ser.is_open}")
# Send commands to the COM port
send_command_to_com_port(ser, 'm0\n')
time.sleep(2)
read_from_com_port(ser)
# Close the serial port
ser.close()
print("Serial connection closed.")
我使用以上代码获得的输出始终是:
Serial port opened: True
b'm0\\n'
No response received from the COM port.
Serial connection closed.
Process finished with exit code 0
additional注意:设备的所有说明都必须是ASCII编码的,并且必须以newline字符结尾' '
发送命令“ M0”后,我应该收到一个字符串的确认。但是我什么都没有。
在python中,您需要将newline字符指定为字节:
response = ser.read_until(b"\n")
"\n"
https://docs.python.org/3/library/stdtypes.html