Last active
November 23, 2016 06:10
-
-
Save haru01/37eefec838f26c522ba46b8de3d50e61 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 = "****"; | |
const char* clientId = "****"; | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
int b_pin = 5; | |
int state = 0; | |
void setup() { | |
Serial.begin(115200); | |
pinMode(b_pin, INPUT); | |
setupWifi(); | |
client.setServer(mqtt_server, port); | |
} | |
void loop() { | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
state = digitalRead(b_pin); | |
if (state == 1) { | |
Serial.println("clicked"); | |
client.publish("key", "click"); | |
Serial.println("publish"); | |
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(clientId, 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
ボタックリック時にメッセージ送信