Search Code

ESP32 튜토리얼 47/55 - 인터넷을 통한 MQTT를 사용한 WS2812 CheerLights | SunFounder의 ESP32 IoT 키트

ESP32 튜토리얼 47/55 - 인터넷을 통한 MQTT를 사용한 WS2812 CheerLights | SunFounder의 ESP32 IoT 키트

이 튜토리얼에서는 MQTT를 통해 원격으로 제어할 수 있는 ESP32와 WS2812 LED를 사용하여 동기화된 조명 시스템을 만들어 보겠습니다. 이 시스템을 통해 여러 사용자가 동시에 조명 색상을 변경할 수 있어, 위치에 관계없이 연결된 경험을 만들 수 있습니다. 이 프로젝트는 Wi-Fi 기능을 갖춘 강력한 마이크로컨트롤러를 포함하는 SunFounder ESP32 IoT 키트를 활용하며, IoT 애플리케이션에 이상적입니다.

WS2812_스트립.ON

비디오 전체에서 이 효과를 구현하는 데 필요한 설정, 배선 및 코드 구현을 살펴보겠습니다. 더 자세한 설명이 필요하면 비디오의 특정 타임스탬프(비디오의 mm:ss)를 확인하세요.

하드웨어 설명

이 프로젝트의 주요 구성 요소는 ESP32 마이크로컨트롤러, WS2812 LED 스트립 및 MQTT 브로커입니다. ESP32는 내장 Wi-Fi 및 Bluetooth 기능을 갖춘 다재다능한 마이크로컨트롤러로, 인터넷에 쉽게 연결할 수 있습니다. 이는 프로젝트의 두뇌 역할을 하며 통신을 처리하고 LED 스트립을 제어합니다.

WS2812 LED 스트립은 개별적으로 주소 지정이 가능한 RGB LED로 구성되어 있으며, 다양한 색상을 표시하도록 제어할 수 있습니다. 각 LED는 단일 데이터 라인을 사용하여 켜거나 끄고 원하는 색상으로 설정할 수 있어 동적 조명 효과에 완벽합니다. MQTT 브로커는 서로 다른 클라이언트 간의 통신을 용이하게 하여 사용자가 LED 색상을 제어하는 주제를 게시하고 구독할 수 있게 합니다.

데이터시트 세부 정보

제조업체 Adafruit
부품 번호 WS2812B
로직/IO 전압 3.5 - 5.5 V
공급 전압 5 V
출력 전류(채널당) 20 mA
피크 전류(채널당) 60 mA
PWM 주파수 가이드 400 Hz
입력 로직 임계값 0.2Vcc(낮음), 0.7Vcc(높음)
전압 강하 / RDS(on) / 포화 0.5 V
열 제한 작동 온도: -25 ~ 85 °C
패키지 개별 5050 SMD
참고 사항 / 변형 다양한 길이와 구성으로 제공됨

 

  • 전압 강하를 방지하려면 WS2812 스트립에 충분한 전원을 공급하세요.
  • ESP32와 LED 스트립 사이에 공통 접지를 사용하세요.
  • 신호 저하를 방지하려면 데이터 라인을 짧게 유지하세요.
  • 전원 공급 장치 양단에 커패시터(1000μF)를 사용하여 전압 스파이크를 완화하는 것을 고려하세요.
  • 신호 반사를 방지하려면 데이터 라인에 적절한 저항을 사용하세요.
  • LED 스트립의 총 전류 소모에 주의하고, 필요할 때 외부 전원을 사용하세요.

배선 지침

ESP32를 WS2812 LED 스트립에 배선하려면 먼저 전원 공급 장치를 연결하세요. LED 스트립의 빨간색 선을 5V 전원에 연결하고 검은색 선을 접지에 연결합니다. 다음으로 WS2812 스트립의 데이터 라인(노란색 선)을 ESP32의 핀 14에 연결합니다. ESP32도 LED 스트립과 동일한 접지에 연결되어 공통 기준을 유지하는지 확인하세요.

전원 및 데이터 연결을 설정한 후 프로그래밍을 위해 마이크로 USB 케이블을 사용하여 ESP32를 컴퓨터에 연결합니다. 프로그래밍하는 동안 연결을 설정하려면 ESP32의 전원이 켜져 있는지 확인해야 합니다. 배선이 완료되면 코드를 업로드하고 설정을 테스트할 수 있습니다.

esp32-47-cheer-light-wiring

코드 예제 및 설명

코드는 Wi-Fi 및 MQTT 기능에 필요한 라이브러리를 포함하는 것으로 시작합니다. 식별자 ssidpassword는 Wi-Fi 자격 증명을 저장하는 데 사용되며, mqtt_server는 MQTT 브로커의 주소를 보유합니다.

const char* ssid = "SSID";
const char* password = "PASSWORD";
const char* mqtt_server = "mqtt.cheerlights.com";

다음으로 지원되는 CheerLights 색상과 해당 RGB 값을 배열을 사용하여 정의합니다. 이를 통해 프로그램은 사용자 입력에 따라 색상 설정에 쉽게 액세스할 수 있습니다.

String colorName[] = {"red", "pink", "green", "blue", "cyan", "white", "warmwhite", "oldlace", "purple", "magenta", "yellow", "orange"};
int colorRGB[][3] = { 255, 0, 0,  // "red"
                      255, 192, 203,  // "pink" ...};

setup() 함수는 직렬 통신을 초기화하고, Wi-Fi 연결을 설정하며, MQTT 클라이언트를 준비합니다. 또한 LED 스트립을 시작합니다.

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  pixels.begin();
  pixels.show(); 
}

메인 루프는 MQTT 연결을 지속적으로 확인하고 LED 색상을 제어하는 수신 메시지를 처리합니다. callback() 함수는 구독한 주제에서 메시지가 수신될 때 트리거됩니다.

시연 / 기대 효과

모든 것이 설정되고 코드가 업로드되면 MQTT 주제에 메시지를 보내 WS2812 LED의 색상을 변경할 수 있어야 합니다. 다른 사용자가 색상을 변경하면 연결된 모든 장치가 동시에 변경 사항을 반영합니다. 극성 반전이나 잘못된 연결과 같은 잠재적인 문제에 주의하세요. 이러한 문제는 LED가 제대로 작동하지 못하게 할 수 있습니다(비디오의 mm:ss).

비디오 타임스탬프

  • 00:00 시작
  • 2:00 소개
  • 3:48 문서 페이지
  • 6:33 배선 설명
  • 7:35 아두이노 코드 설명
  • 15:03 Arduino IDE에서 ESP32 보드 및 COMP 포트 선택
  • 16:46 CheerLights 시연

이미지

WS2812_strip.ON
WS2812_strip.ON
esp32-47-cheer-light-wiring
esp32-47-cheer-light-wiring
848-ESP32 Tutorial 47/55- Arduino code for cheer light
언어: C++
/*********
  :ref: https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/
  https://docs.sunfounder.com/projects/kepler-kit/en/latest/iotproject/5.mqtt_pub.html
*********/

#include <WiFi.h>
#include <PubSubClient.h>
//#include <Wire.h>
#include <Adafruit_NeoPixel.h>

// Replace the next variables with your SSID/Password combination
const char* ssid = "SSID";
const char* password = "PASSWORD";

// Add your MQTT Broker address:
const char* mqtt_server = "mqtt.cheerlights.com";
const char* unique_identifier = "sunfounder-client-sdgvsasdda";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
int value = 0;


// Define the supported CheerLights colors and their RGB values
String colorName[] = {"red", "pink", "green", "blue", "cyan", "white", "warmwhite", "oldlace", "purple", "magenta", "yellow", "orange"};

int colorRGB[][3] = { 255,   0,   0,  // "red"
                      255, 192, 203,  // "pink"
                        0, 255,   0,  // "green"
                        0,   0, 255,  // "blue"
                        0, 255, 255,  // "cyan"
                      255, 255, 255,  // "white"
                      255, 223, 223,  // "warmwhite"
                      255, 223, 223,  // "oldlace"
                      128,   0, 128,  // "purple"
                      255,   0, 255,  // "magenta"
                      255, 255,   0,  // "yellow"
                      255, 165,   0}; // "orange"

// init rgb strip 
#define LED_PIN 13
#define NUM_LEDS 8

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUM_LEDS, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  Serial.begin(115200);

  // wifi default settings
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  // rgb strip begin
  pixels.begin();
  pixels.show(); 

}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;

  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // If a message is received on the topic, you will check this message.
  // Changes the output state according to the message
  if (String(topic) == "cheerlights") {
    Serial.print("Changing color to ");
    Serial.println(messageTemp);
    setColor(messageTemp);
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(unique_identifier)) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("cheerlights");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setColor(String color) {
  // Loop through the list of colors to find the matching color
  for (int colorIndex = 0; colorIndex < 12; colorIndex++) {
    if (color == colorName[colorIndex]) {
      // Set the color of each NeoPixel on the strip
      for (int pixel = 0; pixel < NUM_LEDS; pixel++) {
        pixels.setPixelColor(pixel, pixels.Color (colorRGB [colorIndex][0], colorRGB [colorIndex][1], colorRGB [colorIndex][2]));
      }
      pixels.show();
    }
  }
}


void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

자원 및 참고자료

파일📁

파일이 없습니다.