esp32 arduino rgb
时间: 2023-11-24 20:08:41 浏览: 81
为了控制RGB LED,我们需要将其连接到ESP32开发板上。RGB LED有四个引脚,其中一个是共阳极,其余三个是红色,绿色和蓝色引脚。我们将共阳极连接到ESP32的3.3V引脚,而红色,绿色和蓝色引脚将连接到ESP32的GPIO 12,GPIO 13和GPIO 14引脚。
以下是ESP32 Arduino控制RGB LED的示例代码:
```arduino
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqtt_server = "your_MQTT_BROKER_IP";
WiFiClient espClient;
PubSubClient client(espClient);
int redPin = 12;
int greenPin = 13;
int bluePin = 14;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
void reconnect() {
while (!client.connected()) {
Serial.println("Connecting to MQTT Broker...");
if (client.connect("ESP32Client")) {
Serial.println("Connected to MQTT Broker");
client.subscribe("rgb");
} else {
Serial.print("Failed to connect to MQTT Broker, rc=");
Serial.print(client.state());
Serial.println(" retrying in 5 seconds");
delay(5000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
String message = String((char*)payload);
if (message == "red") {
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, LOW);
} else if (message == "green") {
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
digitalWrite(bluePin, LOW);
} else if (message == "blue") {
digitalWrite(redPin, LOW);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, HIGH);
} else if (message == "off") {
digitalWrite(redPin, LOW);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, LOW);
}
}
```
在此示例中,我们使用MQTT协议控制RGB LED。我们将RGB LED连接到ESP32的引脚12,13和14上,并将其连接到MQTT代理。我们可以通过向“rgb”主题发布消息来控制RGB LED的颜色。如果消息是“red”,则将点亮红色LED,如果消息是“green”,则将点亮绿色LED,如果消息是“blue”,则将点亮蓝色LED,如果消息是“off”,则将关闭所有LED。
阅读全文