ArduinoWiFiShield.ino 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // This example uses an Arduino Uno together with
  2. // a WiFi 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 <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. if (!client.connected()) {
  46. connect();
  47. }
  48. // publish a message roughly every second.
  49. if (millis() - lastMillis > 1000) {
  50. lastMillis = millis();
  51. client.publish("/hello", "world");
  52. }
  53. }