코드 검색

ESP32 튜토리얼 52/55 - WS2812 CheerLights MQTT 글로벌 동기화 및 LCD | SunFounder ESP32 IoT 키트

ESP32 튜토리얼 52/55 - WS2812 CheerLights MQTT 글로벌 동기화 및 LCD | SunFounder ESP32 IoT 키트

이 튜토리얼에서는 ESP32를 사용하여 CheerLights 프로젝트를 만들 것입니다. 이 프로젝트는 MQTT를 통해 전 세계적으로 색상을 동기화합니다. 이 프로젝트는 다른 사용자의 입력에 따라 색상을 변경할 뿐만 아니라 LCD 화면에 현재 색상과 업데이트된 횟수를 표시합니다. 결과적으로 IoT 기능을 재미있게 시연하며, 장치가 어떻게 상호 작용하고 거리에 관계없이 사용자들을 연결 상태로 유지하는지 보여줍니다. 추가 설명을 위해 (비디오 00:00)의 영상을 시청하세요.

esp32-52-cheer-light-lcd-main

하드웨어 설명

이 프로젝트를 구축하려면 ESP32 마이크로컨트롤러, WS2812 LED 스트립, LCD 디스플레이가 필요합니다. ESP32는 작업의 두뇌 역할을 하며, 내장된 Wi-Fi 기능을 사용하여 인터넷에 연결하고 MQTT 메시지를 수신합니다. 이를 통해 다른 사용자의 전 세계 입력에 따라 LED 색상이 실시간으로 업데이트됩니다.

WS2812 LED 스트립은 주소 지정이 가능한 RGB LED가 필요한 프로젝트에서 인기 있는 선택입니다. 각 LED는 독립적으로 제어할 수 있어 풍부한 색상 디스플레이가 가능합니다. LCD는 현재 색상과 변경된 횟수를 시각적으로 확인할 수 있게 하여 사용자 상호 작용을 향상시킵니다.

cheeLights_LCD

데이터시트 세부 정보

제조업체 SunFounder
부품 번호 ESP32
로직/IO 전압 3.3 V
공급 전압 5 V
출력 전류 (채널당) 20 mA
피크 전류 (채널당) 60 mA
PWM 주파수 안내 400 Hz
입력 로직 임계값 0.15 V (낮음), 0.8 V (높음)
전압 강하 / RDS(on) / 포화 0.2 V
열 한계 85 °C
패키지 ESP32 모듈
참고 사항 / 변형 내장 Wi-Fi 및 Bluetooth 포함

 

  • ESP32(5V) 및 WS2812 스트립(5V)에 적절한 전원 공급을 확인하세요.
  • ESP32와 LED 스트립 사이에 공통 접지를 사용하세요.
  • 색상 동기화를 위해 적절한 MQTT 브로커를 구현하세요.
  • WS2812의 데이터 핀 연결(코드에 따라 핀 14)에 주의하세요.
  • LED 수에 주의하세요. 전력 한계를 초과하면 추가 전원이 필요합니다.

배선 지침

ESP32-11_LCD-wiring
esp32-47-cheer-light-wiring

구성 요소를 배선하려면 WS2812 LED 스트립을 연결하는 것부터 시작하세요. LED 스트립의 접지 핀(보통 검은색)을 ESP32의 접지 핀에 연결하세요. 다음으로 LED 스트립의 VCC 핀(보통 빨간색)을 ESP32의 5V 출력에 연결하세요. 마지막으로 데이터 핀(종종 노란색)을 ESP32의 GPIO 핀 14에 연결하세요.

LCD의 경우 접지 핀(보통 검은색)을 ESP32의 접지에 연결하세요. VCC 핀(보통 빨간색)은 5V 출력에 연결해야 합니다. SDA 핀(일반적으로 회색)은 GPIO 핀 21에 연결하고, SCL 핀(보통 흰색)은 GPIO 핀 22에 연결합니다. 이 설정을 통해 ESP32가 LCD와 통신하고 필요에 따라 정보를 표시할 수 있습니다.

코드 예제 및 설명

설정 함수에서 LCD를 초기화하고 Wi-Fi에 연결합니다. 아래 코드는 필요한 라이브러리를 정의하고 LCD를 설정하는 방법을 보여줍니다:

#include  
#include 
LiquidCrystal_I2C lcd(0x27, 16,2);  // LCD 주소 설정
void setup() {
  Serial.begin(115200);
  lcd.init(); // LCD 초기화 
  lcd.backlight(); // LCD 백라이트 켜기
}

이 코드는 LCD를 사용할 수 있도록 초기화하여 메시지를 표시할 수 있게 합니다. 다음 발췌문은 Wi-Fi 연결이 설정되는 방법을 보여줍니다:

void setup_wifi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    lcdConnect(); // LCD용
    delay(500);
  }
  Serial.println("WiFi connected");
}

이 함수는 지정된 Wi-Fi 네트워크에 연결을 설정하고 연결하는 동안 LCD에 메시지를 표시합니다. 마지막으로 색상 변경 로직은 콜백 함수에서 처리됩니다:

void callback(char* topic, byte* message, unsigned int length) {
  String messageTemp;
  for (int i = 0; i < length; i++) {
    messageTemp += (char)message[i];
  }
  if (String(topic) == "cheerlights") {
    setColor(messageTemp);
  }
}

이 함수는 "cheerlights" 주제의 수신 메시지를 수신하고 그에 따라 색상을 업데이트합니다. 전체 코드는 기사 아래에 로드되므로 전체 구현을 검토하세요.

시연 / 기대 효과

프로젝트가 완료되면 전 세계 MQTT 피드의 입력에 따라 LED 스트립의 색상이 변경되는 것을 확인할 수 있습니다. LCD에는 현재 색상 이름과 변경된 횟수가 표시됩니다. 인터넷 연결이 끊기면 LCD에 연결이 다시 설정될 때까지 "Connecting..."이 표시됩니다(비디오 12:30).

일반적인 문제로는 데이터 연결에 올바른 핀을 사용하는지 확인하고 Wi-Fi 자격 증명이 정확한지 확인하는 것이 있습니다. SSID 또는 비밀번호에 불일치가 있으면 ESP32가 연결에 실패하고 LCD에 연결 중 메시지가 계속 표시됩니다.

비디오 타임스탬프

  • 00:00 시작
  • 1:59 프로젝트 소개
  • 6:16 배선 설명
  • 8:13 아두이노 코드 설명
  • 14:26 Arduino IDE에서 ESP32 보드 및 COM 포트 선택
  • 16:07 LCD를 사용한 CheerLight 데모

이미지

ESP32-11_LCD-wiring
ESP32-11_LCD-wiring
esp32-47-cheer-light-wiring
esp32-47-cheer-light-wiring
esp32-52-cheer-light-lcd-main
esp32-52-cheer-light-lcd-main
cheeLights_LCD
cheeLights_LCD
853-ESP32 Tutorial 52/55- CheerLight MQTT and LCD
언어: C++
/*********
This is the origianl code from Examples->iot_5_cheerlight of SunFounder
full video instrucions https://youtu.be/xEqmxMiF-E8
📚⬇️ Download and resource page https://robojax.com/RJT685

I have added LCD to display:
1-Color name
2-Count the number of times the color is updated
3-Showon LCD if wifi is connected
4-Show connecting if not connected or disconnected

Written by Ahmad Shamshiri
www.Robojax.com
Dec 29, 2023

  :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 <Wire.h> 
#include <LiquidCrystal_I2C.h>

//SDA->21,SCL->22 
LiquidCrystal_I2C lcd(0x27, 16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

int colorCount = 0;
int lastColor=0;

byte connected[] = {
          B00001,
          B00001,
          B00011,
          B00111,
          B00111,
          B01111,
          B01111,
          B11111
};


#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 = "dars";
const char* password = "5152535455";

// 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);

  lcd.init();// initialize the lcd 
  lcd.backlight(); // Turns on the LCD backlight.

  // 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) {
    lcdConnect();//for LCD
    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()) {
  lcdConnect();
    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]) {
        lastColor = colorIndex;//remeber the last color
        colorCount++;//increment the count
      // 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]));
        delay(100);
      }
      pixels.show();
    }
  }
}

void lcdConnect()
{
    lcd.clear(); 
    lcd.setCursor(0, 0); //line 0
    lcd.print("Connecting...");   
    lcd.setCursor(0, 1); 
    lcd.print("SSID:"); //line 1
    lcd.print(ssid);
}

void loop() {
  lcd.clear(); 

  if (!client.connected()) {
    reconnect(); 
  }else{
    lcd.createChar(0, connected);
    lcd.setCursor(15, 0);
    lcd.write(byte(0)); 
  }
  client.loop();


  //first row
  lcd.setCursor(0, 0);
  lcd.print("Color: ");  
  lcd.print(colorName[lastColor]);

  //second row
  lcd.setCursor(0, 1);
  lcd.print("Changed ");  
  lcd.print(colorCount);
  lcd.print(" times");

  delay(1000);//we must have delay to able to read the display
  






}

자원 및 참고자료

파일📁

파일이 없습니다.