macarena.py (1089B)
1 import serial 2 import time 3 4 def send_command(ser, command): 5 ser.write(command.encode()) 6 ser.write(b'\n') # Assuming commands are terminated with a newline character 7 8 def main(): 9 # Open serial port 10 ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1) 11 12 if not ser.is_open: 13 print("Failed to open serial port.") 14 return 15 16 print("Serial port opened successfully.") 17 18 try: 19 while True: 20 # Initiate animation sequence 21 send_command(ser, "@4m2d") 22 send_command(ser, "1s9") 23 time.sleep(1) # Wait for 1 second 24 send_command(ser, "@2m4") 25 send_command(ser, "1sl") 26 time.sleep(1) 27 send_command(ser, "@4m2c") 28 time.sleep(1) 29 send_command(ser, "@2m3") 30 send_command(ser, "1se") 31 send_command(ser, "1sd") 32 time.sleep(1) 33 34 except KeyboardInterrupt: 35 print("Program terminated by user.") 36 37 # Close serial port 38 ser.close() 39 print("Serial port closed.") 40 41 if __name__ == "__main__": 42 main() 43