I2C 1602 LCD & MQTT
#include <WiFi.h>
#include <PubSubClient.h>
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
// Update these with values suitable for your network.
const char* ssid = "Wokwi-GUEST"; // your network SSID (name)
const char* password = ""; // your network password
//const char* mqtt_server = "broker.mqttdashboard.com";// choose your mqtt server
const char* mqtt_server = "broker.mqttgo.io";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
//=========================================================
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Command from MQTT broker is : [");
Serial.print(topic);
Serial.println();
Serial.print(" publish data is:");
lcd.clear();
{
for(int i=0;i<length;i++)
{
Serial.print((char)payload[i]);
lcd.setCursor(0, 0);
lcd.print("alex9ufo LCD"); // Start Print text to Line 1
lcd.setCursor(i, 1);
lcd.write((char)payload[i]);
}
}
Serial.println();
} //end callback
//=========================================================
void reconnect() {
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
//if you MQTT broker has clientID,username and password
//please change following line to if (client.connect(clientId,userName,passWord))
if (client.connect(clientId.c_str()))
{
Serial.println("connected");
//once connected to MQTT broker, subscribe command if any
client.subscribe("alex9ufo/Command");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 6 seconds before retrying
delay(6000);
}
}
} //end reconnect()
//=========================================================
void setup_wifi() {
delay(100);
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
//=========================================================
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
// Init
lcd.init();
lcd.backlight();
// Print something
lcd.setCursor(3, 0);
lcd.print("Welcome to");
lcd.setCursor(2, 1);
lcd.print("lcd display");
lcd.setCursor(5, 2);
lcd.print("Simulator");
lcd.setCursor(7, 3);
lcd.print("Enjoy!");
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.setCallback(callback);
client.loop();
}
沒有留言:
張貼留言