#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <PubSubClient.h>
Adafruit_SSD1306 display(128, 64, &Wire, -1);
WiFiClient espClient;
PubSubClient client(espClient);
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "mqtt-dashboard.com";
char dt1;
char dt2[6];
int c = 0;
int j = 0;
int setpoin = 0;
String pesan;
void setup_wifi() {
delay(10);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void reconnect() {
while (!client.connected()) {
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
client.subscribe("kontrol/pid_kec");
} else {
delay(5000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length) {
for (int i = 0; i < length; i++) {
dt1 = ((char)payload[i]);
if (dt1 >= '-' && dt1 <= '9') {
dt2[j] = dt1;
j++;
}
}
setpoin = atoi(dt2);
Serial.println(setpoin);
j = 0;
memset(dt2, 0, sizeof(dt2));
}
void setup() {
Serial.begin(9600);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
for (;;);
}
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
int a = analogRead(36);
int b = map(a, 0, 4095, -1000, 1000);
if (a != c) Serial.println(b);
c = a;
if (!client.connected()) {
reconnect();
}
client.loop();
}
void serialEvent() {
while (Serial.available()) {
int data1 = Serial.parseInt();
int data2 = Serial.parseInt();
int data3 = Serial.parseInt();
if (Serial.read() == char(13)) {
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("SP : ");
display.println(data1);
display.print("PV : ");
display.println(data2);
display.print("OP : ");
display.println(data3);
display.display();
pesan = "{\"sp\":" + String(data1);
pesan = pesan + ",\"pv\":" + String(data2);
pesan = pesan + ",\"op\":" + String(data3) + "}";
client.publish("monitor/pid_kec", pesan.c_str());
}
}
}