Skip to content

Instantly share code, notes, and snippets.

@Mayoogh
Last active March 19, 2021 11:00
Show Gist options
  • Save Mayoogh/1edeead29c502143248f1c6eb097cdcd to your computer and use it in GitHub Desktop.
Save Mayoogh/1edeead29c502143248f1c6eb097cdcd to your computer and use it in GitHub Desktop.
#include <WiFi.h>
#include <PubSubClient.h>
/* reference https://youtu.be/5tG3JXFYrUo von Ali Panjaitan
*/
const char* ssid="SSID";
const char* pass="password";
const char* brokerUser = "user";
const char* brokerPass = "password";
const char* broker = "mqtt.dioty.co";
const char* outTopic ="/out";
const char* inTopic ="/in";
char Recdata[100];
String response;
WiFiClient espClient;
PubSubClient client(espClient);
long currentTime, lastTime;
int count = 0;
char messages[50];
int LED = 18;
void setupWifi(){
delay(100);
Serial.print("\nConnecting to");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while(WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print("-");
}
Serial.print("\nConnected to ");
Serial.println(ssid);
}
void reconnect(){
while(!client.connected()){
Serial.print("\nConncting to ");
Serial.println(broker);
if(client.connect("esp32", brokerUser, brokerPass)){
Serial.print("\nConnected to ");
Serial.println(broker);
client.subscribe(inTopic);
} else {
Serial.println("\n Trying to reconnect");
delay(5000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length){
Serial.print("Message received : ");
// Serial.println(topic);
for(int i=0; i<length; i++){
response += (char)payload[i];
}
Serial.println(response);
if(response == "on") // Turn the light on
{
digitalWrite(LED, HIGH);
response = "";
}
else if(response == "off") // Turn the light off
{
digitalWrite(LED, LOW);
response = "";
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
setupWifi();
client.setServer(broker, 1883);
client.setCallback(callback);
pinMode(18, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()){
reconnect();
}
client.loop();
// currentTime = millis();
// if(currentTime - lastTime > 2000){
// count++;
// snprintf(messages, 75, "Count: %ld", count);
// Serial.print("Sending Messages: ");
// Serial.println(messages);
// client.publish(outTopic, messages);
// lastTime = millis();
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment