Created
May 25, 2019 07:57
-
-
Save samuelbles07/11d70b8a17998d1d76cf264f9c5832d2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 = "YOUR-SSID"; | |
const char* password = "YOUR-PASSWORD"; | |
const char* mqtt_server = "broker.mqtt-dashboard.com"; | |
WiFiClient myClient; | |
PubSubClient client(myClient); | |
long lastMsg = 0; | |
char msg[50]; | |
int value = 0; | |
void setup_wifi() { | |
delay(10); | |
Serial.println(); | |
Serial.print("Connecting to "); | |
Serial.println(ssid); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.println("IP address: "); | |
Serial.println(WiFi.localIP()); | |
} | |
void callback(char* topic, byte* payload, unsigned int length) { | |
Serial.print("Message arrived ["); | |
Serial.print(topic); | |
Serial.print("] "); | |
for (int i = 0; i < length; i++) { | |
Serial.print((char)payload[i]); | |
} | |
Serial.println(); | |
if ((char)payload[0] == '1') { | |
Serial.println("Led Hidup"); | |
digitalWrite(LED_BUILTIN, LOW); | |
} else { | |
Serial.println("Led Mati"); | |
digitalWrite(LED_BUILTIN, HIGH); | |
} | |
} | |
void reconnect() { | |
while (!client.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
if (client.connect("")) { | |
Serial.println("connected"); | |
client.publish("espectro32/test/send", "hello world"); | |
client.subscribe("espectro32/test/receive"); | |
} else { | |
Serial.println(" try again in 5 seconds"); | |
delay(5000); | |
} | |
} | |
} | |
void setup() { | |
delay(10); | |
pinMode(LED_BUILTIN, OUTPUT); | |
Serial.begin(9600); | |
setup_wifi(); | |
client.setServer(mqtt_server, 1883); | |
client.setCallback(callback); | |
} | |
void loop() { | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
long now = millis(); | |
if (now - lastMsg > 7000) { | |
lastMsg = now; | |
++value; | |
snprintf (msg, 50, "hello world #%ld", value); | |
Serial.print("Publish message: "); | |
Serial.println(msg); | |
client.publish("espectro32/test/send", msg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment