Advertisement
j0h

seprateListener

j0h
Jul 24th, 2023
1,099
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. import serial
  2. import time
  3. import multiprocessing
  4.  
  5. def send_command(ser, command):
  6.     ser.write(command.encode())
  7.     print(f"Sent command: {command}")
  8.  
  9. def receive_response(ser):
  10.     while True:
  11.         response = ser.readline().decode().strip()
  12.         if response:
  13.             print(f"Received response: {response}")
  14.  
  15. def main(port='/dev/ttyACM0', baudrate=9600, timeout=1):
  16.     try:
  17.         # Open the serial port
  18.         ser = serial.Serial(port, baudrate, timeout=timeout)
  19.        
  20.         # Wait for the Arduino to initialize (optional)
  21.         time.sleep(2)
  22.  
  23.         # Define commands to send
  24.         commands = ["command1", "command2", "command3"]
  25.  
  26.         # Create a separate process to continuously listen for responses
  27.         response_process = multiprocessing.Process(target=receive_response, args=(ser,))
  28.         response_process.daemon = True
  29.         response_process.start()
  30.  
  31.         # Send commands
  32.         for command in commands:
  33.             send_command(ser, command)
  34.  
  35.         # Close the serial port
  36.         ser.close()
  37.         print("Communication finished.")
  38.     except Exception as e:
  39.         print("Error:", str(e))
  40.  
  41. if __name__ == "__main__":
  42.     main()
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement