Skip to content

Instantly share code, notes, and snippets.

@jhaury
Created May 18, 2022 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhaury/3d995fa93fb2e74d7c159c0793631aa3 to your computer and use it in GitHub Desktop.
Save jhaury/3d995fa93fb2e74d7c159c0793631aa3 to your computer and use it in GitHub Desktop.
# oled screen off a esp8266 will display via mqtt temp and humidity
#
#
#include Wire.h
#include Arduino.h
#include U8g2lib.h
#include ESP8266WiFi.h
#include PubSubClient.h
U8G2_SSD1306_128X32_UNIVISION_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 2, /* data=*/ 0); // pin remapping with ESP8266 HW I2C
const char* ssid = "SSID"; // ssid
const char* password = "PW"; // password
const char* mqtt_server = "192.168.X.X"; // mqtt server
const char* inTopic = "/"; // topic esp will subscribe to
const char* clientId = "esp"; // id of the esp
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup()
{
u8g2.begin();
u8g2.enableUTF8Print();
Serial.begin(9600);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
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* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
payload[length] = '\0';
Serial.print((char)payload[i]);
}
Serial.println();
String message = String((char*)payload);
if ((char)payload[0]) {
// if ((char)payload[0] == '1') {
u8g2.clearBuffer();
u8g2.setFont(u8g2_font_ncenB10_tr);
u8g2.setCursor(0, 24);
u8g2.print(message);
// u8g2.drawStr(0,24,"Turning ON");
u8g2.sendBuffer();
delay(5000);
} else if ((char)payload[0] == '0') {
u8g2.clearBuffer();
u8g2.print(message);
// u8g2.drawStr(0,24,"Turning OFF");
u8g2.sendBuffer();
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect(clientId)) {
Serial.println("connected");
client.subscribe(inTopic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment