Загрузка данных


import serial
import serial.tools.list_ports
import time

class RGBController:
    def __init__(self, port=None, baudrate=9600):
        # Автопоиск Arduino
        if port is None:
            ports = serial.tools.list_ports.comports()
            for p in ports:
                if "Arduino" in p.description or "CH340" in p.description or "USB" in p.description:
                    port = p.device
                    break

        if port is None:
            raise Exception("Arduino не найдена! Проверь подключение.")

        self.ser = serial.Serial(port, baudrate, timeout=2)
        time.sleep(2)  # Ждём инициализации Arduino
        print(f"Подключено к {port}")

    def set_color(self, r, g, b):
        """Отправить цвет на Arduino"""
        # Ограничиваем значения
        r = max(0, min(255, r))
        g = max(0, min(255, g))
        b = max(0, min(255, b))

        command = f"{r},{g},{b}\n"
        self.ser.write(command.encode())

        # Получаем ответ
        response = self.ser.readline().decode().strip()
        print(f"Цвет установлен: RGB({r},{g},{b}) -> {response}")

    def close(self):
        self.ser.close()

    # Предустановленные цвета
    def red(self): self.set_color(255, 0, 0)
    def orange(self): self.set_color(255, 165, 0)
    def yellow(self): self.set_color(255, 255, 0)
    def green(self): self.set_color(0, 255, 0)
    def cyan(self): self.set_color(0, 255, 255)    # Голубой
    def blue(self): self.set_color(0, 0, 255)
    def purple(self): self.set_color(128, 0, 128)  # Фиолетовый
    def white(self): self.set_color(255, 255, 255)

# ============ ИНТЕРАКТИВНАЯ ПРОГРАММА ============
def main():
    try:
        rgb = RGBController()
    except Exception as e:
        print(e)
        return

    colors = {
        '1': ('Красный', rgb.red),
        '2': ('Оранжевый', rgb.orange),
        '3': ('Жёлтый', rgb.yellow),
        '4': ('Зелёный', rgb.green),
        '5': ('Голубой', rgb.cyan),
        '6': ('Синий', rgb.blue),
        '7': ('Фиолетовый', rgb.purple),
        '8': ('Белый', rgb.white),
    }

    print("\n=== УПРАВЛЕНИЕ RGB СВЕТОДИОДОМ ===")
    print("1 - Красный\n2 - Оранжевый\n3 - Жёлтый\n4 - Зелёный")
    print("5 - Голубой\n6 - Синий\n7 - Фиолетовый\n8 - Белый")
    print("0 - Выход")
    print("Или введи свой цвет в формате: R,G,B (например 100,50,200)")

    while True:
        choice = input("\nТвой выбор: ").strip()

        if choice == '0':
            break
        elif choice in colors:
            colors[choice][1]()
        elif ',' in choice:
            parts = choice.split(',')
            if len(parts) == 3:
                try:
                    r, g, b = map(int, parts)
                    rgb.set_color(r, g, b)
                except:
                    print("Ошибка! Введи 3 числа через запятую (0-255)")
            else:
                print("Формат: R,G,B (например 255,100,50)")
        else:
            print("Не понял команду. Жми 1-8 или введи R,G,B")

    rgb.close()
    print("Пока, братан!")

if __name__ == "__main__":
    main()
питон

ардуино
// Пины для RGB (можно менять)
const int RED_PIN   = 9;   // PWM
const int GREEN_PIN = 10; // PWM
const int BLUE_PIN  = 11; // PWM

// Тип светодиода: true - ОБЩИЙ КАТОД (-), false - ОБЩИЙ АНОД (+)
const bool COMMON_CATHODE = true;

void setup() {
  Serial.begin(9600);
  pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
  
  // Начальный цвет - белый
  setColor(255, 255, 255);
}

void loop() {
  if (Serial.available()) {
    String command = Serial.readStringUntil('\n');
    command.trim();
    
    // Формат команды: "R,G,B" например "255,0,0"
    int firstComma = command.indexOf(',');
    int secondComma = command.indexOf(',', firstComma + 1);
    
    if (firstComma != -1 && secondComma != -1) {
      int r = command.substring(0, firstComma).toInt();
      int g = command.substring(firstComma + 1, secondComma).toInt();
      int b = command.substring(secondComma + 1).toInt();
      
      // Ограничиваем значения 0-255
      r = constrain(r, 0, 255);
      g = constrain(g, 0, 255);
      b = constrain(b, 0, 255);
      
      setColor(r, g, b);
      
      // Отправляем подтверждение
      Serial.print("OK: ");
      Serial.print(r);
      Serial.print(",");
      Serial.print(g);
      Serial.print(",");
      Serial.println(b);
    }
  }
}

void setColor(int r, int g, int b) {
  if (!COMMON_CATHODE) {
    // Для общего анода инвертируем сигнал
    r = 255 - r;
    g = 255 - g;
    b = 255 - b;
  }
  analogWrite(RED_PIN, r);
  analogWrite(GREEN_PIN, g);
  analogWrite(BLUE_PIN, b);
}