Last active
November 23, 2016 06:11
-
-
Save haru01/c8d60f36f92206de86c17591e162d1bb 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 <ESP8266WiFi.h> | |
#include <WiFiClient.h> | |
#include <PubSubClient.h> | |
const char* ssid = "****"; | |
const char* wifi_password = "****"; | |
const char* mqtt_server = "****"; | |
const int port = ****; | |
const char* username = "****"; | |
const char* password = "****"; | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
void setup() { | |
Serial.begin(115200); | |
setupWifi(); | |
client.setServer(mqtt_server, port); | |
} | |
void loop() { | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
client.publish("key", "hello"); | |
Serial.print("publish ed"); | |
delay(1000); | |
} | |
void setupWifi() { | |
delay(10); | |
Serial.println(); | |
Serial.print("Connecting to "); | |
Serial.println(ssid); | |
WiFi.begin(ssid, wifi_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 reconnect() { | |
while (!client.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
if (client.connect("1-go-ki", username, password)) { | |
Serial.println("connected"); | |
} else { | |
Serial.print("failed, rc="); | |
Serial.print(client.state()); | |
Serial.println(" try again in 5 seconds"); | |
delay(5000); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MQTTでメッセージ送信