RadioLib/examples/ESP8266_MQTT_Publish/ESP8266_MQTT_Publish.ino

84 wiersze
2.2 KiB
Arduino
Czysty Zwykły widok Historia

2018-07-03 10:01:37 +00:00
/*
* KiteLib ESP8266 MQTT Publish Example
*
* This example publishes MQTT messages using ESP8266 WiFi module.
*
* The messages are published to https://shiftr.io/try. You can use this namespace
* for testing purposes, but remember that it is publicly accessible!
*
2018-07-11 11:44:43 +00:00
* IMPORTANT: Before uploading this example, make sure that the ESP8266 module is running
2018-07-03 10:01:37 +00:00
* AT firmware (can be found in the /extras folder of the library)!
*/
// include the library
#include <KiteLib.h>
// ESP8266 module is in slot A on the shield
ESP8266 wifi = Kite.ModuleA;
2018-07-11 11:44:43 +00:00
// create MQTT client instance using the wifi module
2018-07-11 15:40:25 +00:00
// the default port used for MQTT is 1883
MQTTClient mqtt(&wifi, 1883);
2018-07-11 11:44:43 +00:00
2018-07-03 10:01:37 +00:00
void setup() {
Serial.begin(9600);
2018-07-11 15:40:25 +00:00
// initialize ESP8266
2018-07-03 10:01:37 +00:00
Serial.print(F("[ESP8266] Initializing ... "));
2018-07-11 15:40:25 +00:00
// baudrate: 9600 baud
2018-07-03 10:01:37 +00:00
byte state = wifi.begin(9600);
if(state == ERR_NONE) {
Serial.println(F("success!"));
} else {
Serial.print(F("failed, code 0x"));
Serial.println(state, HEX);
while(true);
}
2018-07-11 15:40:25 +00:00
// join access point
2018-07-03 10:01:37 +00:00
Serial.print(F("[ESP8266] Joining AP ... "));
2018-07-11 15:40:25 +00:00
// name: SSID
// password: password
2018-07-03 10:01:37 +00:00
state = wifi.join("SSID", "password");
if(state == ERR_NONE) {
Serial.println(F("success!"));
} else {
Serial.print(F("failed, code 0x"));
Serial.println(state, HEX);
while(true);
}
2018-07-11 15:40:25 +00:00
// connect to MQTT server
2018-07-11 11:44:43 +00:00
Serial.print(F("[ESP8266] Connecting to MQTT server ... "));
2018-07-11 15:40:25 +00:00
// server URL: broker.shiftr.io
// client ID: arduino
// username: try
// password: try
2018-07-11 11:44:43 +00:00
state = mqtt.connect("broker.shiftr.io", "arduino", "try", "try");
2018-07-03 10:01:37 +00:00
if(state == ERR_NONE) {
Serial.println(F("success!"));
} else {
Serial.print(F("failed, code 0x"));
Serial.println(state, HEX);
while(true);
}
}
void loop() {
2018-07-11 15:40:25 +00:00
// publish MQTT message
2018-07-03 10:01:37 +00:00
Serial.print(F("[ESP8266] Publishing MQTT message ... "));
2018-07-11 15:40:25 +00:00
// topic name: hello
// application message: world
2018-07-11 11:44:43 +00:00
byte state = mqtt.publish("hello", "world");
2018-07-03 10:01:37 +00:00
if(state == ERR_NONE) {
Serial.println(F("success!"));
} else {
Serial.print(F("failed, code 0x"));
Serial.println(state, HEX);
}
// wait for a second before publishing again
delay(1000);
}