Smart electronics
Jump to navigation
Jump to search
ESP Board manager
https://espressif.github.io/arduino-esp32/package_esp32_index.json
Tester
https://editor.p5js.org/bsmeenk/full/UuEWPceBe
Helper functions
Connecting to WiFI
void connectWifi() {
Serial.print("Connecting to wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println("\nWifi connected!");
delay(1000);
}
Connecting to MQQT broker
void connectMqtt() {
Serial.print("\nConnecting to MQTT broker...");
while (!client.connect(client_id.c_str())) {
Serial.print(".");
delay(1000);
}
Serial.println("\nMQTT connected!");
delay(1000);
client.subscribe(topic);
}
Sketches
LED
int ledPin = 26;
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ACTION_PIN, HIGH);
}
void loop() {
}
LED + WiFi
#include <WiFi.h>
int ledPin = 26;
char ssid[] = "bridgenet";
char pass[] = "interaction";
WiFiClient wifiClient;
MQTTClient client;
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
WiFi.begin(ssid, pass);
connectWifi();
}
void loop() {
}
void connectWifi() {
Serial.print("Connecting to wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println("\nWifi connected!");
delay(1000);
}
LED + WiFi + MQTT
#include <WiFi.h>
#include <MQTT.h>
int ledPin = 26;
char ssid[] = "bridgenet";
char pass[] = "interaction";
char host[] = "test.mosquitto.org";
char topic[] = "wdka"; // change this
String client_id = "boris-esp"; // change this
WiFiClient wifiClient;
MQTTClient client;
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
WiFi.begin(ssid, pass);
connectWifi();
client.begin(host, wifiClient);
client.onMessage(messageReceived);
connectMqtt();
}
void loop() {
client.loop();
if (!client.connected()) {
Serial.println("lost connection");
connectMqtt();
}
}
void messageReceived(String &topic, String &payload) {
Serial.println(payload);
if (payload == "off") {
digitalWrite(ledPin, LOW);
} else if (payload == "on") {
digitalWrite(ledPin, HIGH);
}
}
void connectWifi() {
Serial.print("Connecting to wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println("\nWifi connected!");
delay(1000);
}
void connectMqtt() {
Serial.print("\nConnecting to MQTT server...");
while (!client.connect(client_id.c_str())) {
Serial.print(".");
delay(1000);
}
Serial.println("\nMQTT connected!");
delay(1000);
client.subscribe(topic);
}