import serial
import time
import multiprocessing
def send_command(ser, command):
ser.write(command.encode())
print(f"Sent command: {command}")
def receive_response(ser):
while True:
response = ser.readline().decode().strip()
if response:
print(f"Received response: {response}")
def main(port='/dev/ttyACM0', baudrate=9600, timeout=1):
try:
# Open the serial port
ser = serial.Serial(port, baudrate, timeout=timeout)
# Wait for the Arduino to initialize (optional)
time.sleep(2)
# Define commands to send
commands = ["command1", "command2", "command3"]
# Create a separate process to continuously listen for responses
response_process = multiprocessing.Process(target=receive_response, args=(ser,))
response_process.daemon = True
response_process.start()
# Send commands
for command in commands:
send_command(ser, command)
# Close the serial port
ser.close()
print("Communication finished.")
except Exception as e:
print("Error:", str(e))
if __name__ == "__main__":
main()