ArduinoEthernetShield.ino 1.4 KB

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