前提・実現したいこと
ESP8266で人感センサーでMQTTサーバーを使い検知状態をネットへ通知
Arduino
発生している問題・エラーメッセージ
portに出力がない(・・・・・・)となっている MQTTサーバーでは無反応
該当のソースコード
Arduino
1#include <ESP8266WiFi.h> 2#include <PubSubClient.h> 3 4 // Update these with values suitable for your network. 5 6const char* ssid = "xxxxxxxxxxx"; 7const char* password = "XXXXXXX"; 8const char* mqtt_server = "xxxxxxxxx"; 9 10WiFiClient espClient; 11PubSubClient client(espClient); 12long lastMsg = 0; 13char msg[50]; 14int value = 0; 15 16void setup() { 17 pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output 18 Serial.begin(115200); 19 setup_wifi(); 20 client.setServer(mqtt_server, 1883); 21 client.setCallback(callback); 22} 23 24void setup_wifi() { 25 26 delay(10); 27 // We start by connecting to a WiFi network 28 Serial.println(); 29 Serial.print("Connecting to "); 30 Serial.println(ssid); 31 32 WiFi.begin(ssid, password); 33 34 while (WiFi.status() != WL_CONNECTED) { 35 delay(500); 36 Serial.print("."); 37 } 38 39 Serial.println(""); 40 Serial.println("WiFi connected"); 41 Serial.println("IP address: "); 42 Serial.println(WiFi.localIP()); 43} 44 45void callback(char* topic, byte* payload, unsigned int length) { 46 Serial.print("Message arrived ["); 47 Serial.print(topic); 48 Serial.print("] "); 49 for (int i = 0; i < length; i++) { 50 Serial.print((char)payload[i]); 51 } 52 Serial.println(); 53 54 // Switch on the LED if an 1 was received as first character 55 if ((char)payload[0] == '1') { 56 digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level 57 // but actually the LED is on; this is because 58 // it is acive low on the ESP-01) 59 } else { 60 digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH 61 } 62 63} 64 65void reconnect() { 66 // Loop until we're reconnected 67 while (!client.connected()) { 68 Serial.print("Attempting MQTT connection... "); 69 // Attempt to connect 70 if (client.connect("ESP8266Client")) { 71 Serial.println("connected"); 72 // Once connected, publish an announcement... 73 client.publish("ondo", "from Arduino ----reconnect"); 74 // ... and resubscribe 75 //client.subscribe("vol001"); 76 } else { 77 Serial.print("failed, rc="); 78 Serial.print(client.state()); 79 Serial.println(" try again in 5 seconds"); 80 // Wait 5 seconds before retrying 81 delay(5000); 82 } 83 } 84} 85void loop() { 86 87 if (!client.connected()) { 88 reconnect(); 89 } 90 client.loop(); 91 delay(2000); 92 long now = millis(); 93 if (now - lastMsg > 200) { 94 lastMsg = now; 95 ++value; 96 snprintf (msg, 75, "ESP8226- #%ld", value); 97 Serial.print("Publish message: "); 98 Serial.println(msg); 99 client.publish("ondo", msg); 100 } 101 Serial.print(" Received " + client.subscribe("ondo")); 102}
試したこと
LチカMQTT無しでSAT無しでLチカなど初歩的なところから見直しました
補足情報(FW/ツールのバージョンなど)
Windows10 ,MQTT・NodeMCU初学者、port番号がcom3です
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/02/07 13:20
2021/02/07 13:28