Ruslan_nig

Serial_Python_LED_on_off

Oct 9th, 2025
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. # Подключение к Arduino
  2. arduino = serial.Serial(port='COM12', baudrate=9600, timeout=1)
  3. # Для Linux/Mac: port='/dev/ttyUSB0' или '/dev/ttyACM0'
  4.  
  5. def write_read(x):
  6.     arduino.write(bytes(x, 'utf-8'))
  7.     time.sleep(0.05)
  8.     data = arduino.readline()
  9.     return data #что-то возвращаем...
  10.  
  11. try:
  12.     while True:
  13.         # Чтение данных с Arduino
  14.         if arduino.in_waiting > 0:
  15.             data = arduino.readline().decode('utf-8').rstrip()
  16.             print(f"Arduino: {data}")
  17.        
  18.         # Отправка данных на Arduino
  19.         user_input = input("Enter command (or 'quit' to exit): ")
  20.         if user_input.lower() == 'quit':
  21.             break
  22.        
  23.         #arduino.write(f"{user_input}\n".encode('utf-8'))
  24.         if user_input.lower() == 'on':
  25.             arduino.write("on".encode('utf-8'))
  26.         if user_input.lower() == 'off':
  27.             arduino.write("off".encode('utf-8'))
  28.        
  29.         time.sleep(0.1)
  30.  
  31. except KeyboardInterrupt:
  32.     print("Программа завершена пользователем")
  33.  
  34. finally:
  35.     arduino.close()
  36.     print("Соединение закрыто")
  37.  
Advertisement
Add Comment
Please, Sign In to add comment