ArduinoWiFi101.ino 1.5 KB

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