#include <WiFi.h>
#include <MQTT.h>
#include <ESP32Servo.h>
WiFiClient net;
MQTTClient client;
Servo servo;
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
//nomor pin gpio
const int pinRed = 2;
const int pinGreen = 4;
const int pinBlue = 16;
const int pinLed = 13;
const int pinServo = 32;
void setup() {
// put your setup code here, to run once:
pinMode(pinRed, OUTPUT);
pinMode(pinGreen, OUTPUT);
pinMode(pinBlue, OUTPUT);
pinMode(pinLed, OUTPUT);
servo.attach(pinServo, 500, 2400);
WiFi.begin(ssid, pass);
client.begin("broker.emqx.io", net);
client.onMessage(subscribe);
connect();
}
void loop() {
// put your main code here, to run repeatedly:
client.loop();
if(!client.connected()){
connect();
}
delay(10); // this speeds up the simulation
}
void subscribe(String &topic, String &data){
if(topic == "cobakelasiot/led"){
if(data == "nyala"){
digitalWrite(pinLed, 1);
}else if(data == "mati"){
digitalWrite(pinLed, 0);
}
}
if(topic == "cobakelasiot/servo"){
int posServo = data.toInt();
servo.write(posServo);
}
}
void rgb(bool red, bool green, bool blue){
digitalWrite(pinRed, red);
digitalWrite(pinGreen, green);
digitalWrite(pinBlue, blue);
}
void connect(){
rgb(1, 0, 0);// rgb merah
while (WiFi.status() !=WL_CONNECTED){
delay(500);
}
rgb(0, 1, 0); // rgb hijau
while(!client.connect("Cmqttx_0971a3e2")){
delay(500);
}
rgb(0, 0, 1); // rgb biru
client.subscribe("cobakelasiot/#, 1"); //subscribe menggunakan qos 1
}