Advertisement
j0h

serialHoren

j0h
Jul 24th, 2023
1,111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. import serial
  2. import time
  3.  
  4. def send_and_receive(port='/dev/ttyACM0', baudrate=9600, timeout=1):
  5.     try:
  6.         # Open the serial port
  7.         ser = serial.Serial(port, baudrate, timeout=timeout)
  8.        
  9.         # Wait for the Arduino to initialize (optional)
  10.         time.sleep(2)
  11.  
  12.         # Define commands to send
  13.         commands = ["command1", "command2", "command3"]
  14.  
  15.         for command in commands:
  16.             # Send the command
  17.             ser.write(command.encode())
  18.             print(f"Sent command: {command}")
  19.  
  20.             # Wait for a response
  21.             response = ser.readline().decode().strip()
  22.             print(f"Received response: {response}")
  23.  
  24.         # Close the serial port
  25.         ser.close()
  26.         print("Communication finished.")
  27.     except Exception as e:
  28.         print("Error:", str(e))
  29.  
  30. if __name__ == "__main__":
  31.     send_and_receive()
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement