Last active
June 9, 2021 18:22
-
-
Save tassioauad/a18a4d26b0f8d7a1940da063fe796f1f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <WiFi.h> | |
#include <PubSubClient.h> | |
const char* ssid = "Oliveira"; | |
const char* password = "20099002"; | |
const char* mqtt_server = "104.248.117.230"; | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
const int LED = 2; | |
void callback(char* topic, byte* payload, unsigned int length) { | |
Serial.print("Topico "); | |
Serial.print(topic); | |
Serial.print(": "); | |
String payloadString = ""; | |
for (int i = 0; i < length; i++) { | |
payloadString += (char) payload[i]; | |
} | |
if(payloadString == "on") { | |
digitalWrite(LED, HIGH); | |
} else { | |
digitalWrite(LED, LOW); | |
} | |
Serial.println(payloadString); | |
} | |
void setup() { | |
Serial.begin(9600); | |
Serial.print("Conectando ao WiFi... "); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println("WiFi conectado!"); | |
Serial.println("Endereço IP: "); | |
Serial.println(WiFi.localIP()); | |
client.setServer(mqtt_server, 1883); | |
client.setCallback(callback); | |
client.connect("1"); | |
while (!client.connected()) { | |
Serial.print("Falha:"); | |
Serial.print(client.state()); | |
Serial.println(" nova tentativa em 5 segundos"); | |
delay(5000); | |
client.connect("1"); | |
} | |
pinMode(LED, OUTPUT); | |
client.subscribe("iot"); | |
} | |
void loop() { | |
client.loop(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment