Mit pyserialem Versäumnis eine Verbindung zum seriellen Anschluss herstellenPython

Python-Programme
Anonymous
 Mit pyserialem Versäumnis eine Verbindung zum seriellen Anschluss herstellen

Post by Anonymous »

Ich versuche mit einem seriellen Anschluss eine Verbindung zu einem Gerät herzustellen. Ich habe zwei Wege ausprobiert - 1) pyserial in Python und 2) Putty. Ich habe es geschafft, eine Verbindung zum Gerät herzustellen und es mit Putty zu verwenden. In Python kann ich jedoch nur eine Verbindung zum Gerät herstellen (öffnen Sie den Port), aber ich sende keine Befehle oder lese den Port. Mein Python -Skript (unten) und Kitteinstellungen. Aber vielleicht fehlt mir etwas. Wie repariere ich mein Skript?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.")
< /code>
Die Ausgabe, die ich mit dem obigen Code erhalte, ist immer: < /p>
Serial port opened: True
b'm0\n'
No response received from the COM port.
Serial connection closed.

Process finished with exit code 0
< /code>
Zusätzlicher Hinweis: Alle Anweisungen zum Gerät müssen ASCII codiert werden und müssen mit einem neuen Zeilenzeichen '\ n'. < /p>
nach dem Senden des Befehls enden 'M0' Ich sollte eine Bestätigung als Zeichenfolge erhalten. Aber ich bekomme nichts.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post