ArduinoYun.ino 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // This example uses an Arduino Yun or a Yun-Shield
  2. // and the MQTTClient 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 <Bridge.h>
  10. #include <BridgeClient.h>
  11. #include <MQTT.h>
  12. BridgeClient net;
  13. MQTTClient client;
  14. unsigned long lastMillis = 0;
  15. void connect() {
  16. Serial.print("connecting...");
  17. while (!client.connect("arduino", "try", "try")) {
  18. Serial.print(".");
  19. delay(1000);
  20. }
  21. Serial.println("\nconnected!");
  22. client.subscribe("/hello");
  23. // client.unsubscribe("/hello");
  24. }
  25. void messageReceived(String &topic, String &payload) {
  26. Serial.println("incoming: " + topic + " - " + payload);
  27. }
  28. void setup() {
  29. Bridge.begin();
  30. Serial.begin(115200);
  31. // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino.
  32. // You need to set the IP address directly.
  33. client.begin("broker.shiftr.io", net);
  34. client.onMessage(messageReceived);
  35. connect();
  36. }
  37. void loop() {
  38. client.loop();
  39. if (!client.connected()) {
  40. connect();
  41. }
  42. // publish a message roughly every second.
  43. if (millis() - lastMillis > 1000) {
  44. lastMillis = millis();
  45. client.publish("/hello", "world");
  46. }
  47. }