#include <WiFi.h>
#include <MQTT.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED width, in pixels
#define SCREEN_HEIGHT 64 // OLED height, in pixels
// Create an OLED display object connected to I2C
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
WiFiClient net;
MQTTClient Client;
const char ssid[]="Wokwi-GUEST";
const char pass[]="";
const int pinRed = 2;
const int pinGreen = 4;
const int pinBlue = 17;
void setup() {
pinMode(pinRed, OUTPUT);
pinMode(pinGreen, OUTPUT);
pinMode(pinBlue, OUTPUT);
Serial.begin(9600);
// Initialize OLED display with I2C address 0x3C
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("Failed to start SSD1306 OLED"));
while (1);
}
delay(2000); // Wait two seconds for initializing
oled.clearDisplay(); // Clear display
oled.setTextSize(1); // Set text size
oled.setTextColor(WHITE); // Set text color
oled.setCursor(12, 30); // Set position to display (x,y)
oled.println("Welcome to MQTT"); // Set text
oled.display(); // Display on OLED
WiFi.begin(ssid,pass);
Client.begin("broker.emqx.io", net);
Client.onMessage(subscribe);
reconnect();
}
void loop() {
Client.loop();
if(!Client.connected()){
reconnect();
}
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
}
void rgb(bool red, bool green, bool blue){
digitalWrite(pinRed, red);
digitalWrite(pinGreen, green);
digitalWrite(pinBlue, blue);
}
void reconnect(){
rgb(1,0,0); //merah
// Serial.println("merah");
while (WiFi.status() != WL_CONNECTED){
delay(500);
}
rgb(0,1,0);
while (!Client.connect("Client-connnect-01")){
delay(500);
}
rgb(0,0,1); //biru
Client.subscribe("kelasiot1/#", 1);
}
void subscribe(String &topic, String &data){
// if (topic == "kelasiot1/led")
Serial.print("Topic =");
Serial.println(topic);
Serial.print("Data =");
Serial.println(data);
oled.clearDisplay(); // Clear display
oled.setCursor(1, 2); // Set position to display (x,y)
oled.setTextSize(1);
oled.print("Temperatur"); // Set text
oled.setTextSize(2);
oled.setCursor(1, 15);
oled.println(data);
oled.setCursor(40, 15);
oled.print("C");
oled.display();
// delay(500); // Display on OLED
}