ESP32DevelopmentBoard.ino 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // This example uses an ESP32 Development Board
  2. // to connect to shiftr.io.
  3. //
  4. // You can check on your device after a successful
  5. // connection here: https://shiftr.io/try.
  6. //
  7. // by Joël Gähwiler
  8. // https://github.com/256dpi/arduino-mqtt
  9. #include <WiFi.h>
  10. #include <MQTT.h>
  11. const char ssid[] = "ssid";
  12. const char pass[] = "pass";
  13. WiFiClient net;
  14. MQTTClient client;
  15. unsigned long lastMillis = 0;
  16. void connect() {
  17. Serial.print("checking wifi...");
  18. while (WiFi.status() != WL_CONNECTED) {
  19. Serial.print(".");
  20. delay(1000);
  21. }
  22. Serial.print("\nconnecting...");
  23. while (!client.connect("arduino", "try", "try")) {
  24. Serial.print(".");
  25. delay(1000);
  26. }
  27. Serial.println("\nconnected!");
  28. client.subscribe("/hello");
  29. // client.unsubscribe("/hello");
  30. }
  31. void messageReceived(String &topic, String &payload) {
  32. Serial.println("incoming: " + topic + " - " + payload);
  33. }
  34. void setup() {
  35. Serial.begin(115200);
  36. WiFi.begin(ssid, pass);
  37. // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino.
  38. // You need to set the IP address directly.
  39. client.begin("broker.shiftr.io", net);
  40. client.onMessage(messageReceived);
  41. connect();
  42. }
  43. void loop() {
  44. client.loop();
  45. delay(10); // <- fixes some issues with WiFi stability
  46. if (!client.connected()) {
  47. connect();
  48. }
  49. // publish a message roughly every second.
  50. if (millis() - lastMillis > 1000) {
  51. lastMillis = millis();
  52. client.publish("/hello", "world");
  53. }
  54. }