ArduinoMKRGSM1400.ino 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // This example uses an Arduino MKR GSM 1400 board
  2. // to connect to shiftr.io.
  3. //
  4. // IMPORTANT: This example uses the new MKRGSM library.
  5. //
  6. // You can check on your device after a successful
  7. // connection here: https://shiftr.io/try.
  8. //
  9. // by Sandeep Mistry
  10. // https://github.com/256dpi/arduino-mqtt
  11. #include <MKRGSM.h>
  12. #include <MQTT.h>
  13. const char pin[] = "";
  14. const char apn[] = "apn";
  15. const char login[] = "login";
  16. const char password[] = "password";
  17. GSMClient net;
  18. GPRS gprs;
  19. GSM gsmAccess;
  20. MQTTClient client;
  21. unsigned long lastMillis = 0;
  22. void connect() {
  23. // connection state
  24. bool connected = false;
  25. Serial.print("connecting to cellular network ...");
  26. // After starting the modem with gsmAccess.begin()
  27. // attach to the GPRS network with the APN, login and password
  28. while (!connected) {
  29. if ((gsmAccess.begin(pin) == GSM_READY) &&
  30. (gprs.attachGPRS(apn, login, password) == GPRS_READY)) {
  31. connected = true;
  32. } else {
  33. Serial.print(".");
  34. delay(1000);
  35. }
  36. }
  37. Serial.print("\nconnecting...");
  38. while (!client.connect("arduino", "try", "try")) {
  39. Serial.print(".");
  40. delay(1000);
  41. }
  42. Serial.println("\nconnected!");
  43. client.subscribe("/hello");
  44. // client.unsubscribe("/hello");
  45. }
  46. void messageReceived(String &topic, String &payload) {
  47. Serial.println("incoming: " + topic + " - " + payload);
  48. }
  49. void setup() {
  50. Serial.begin(115200);
  51. // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino.
  52. // You need to set the IP address directly.
  53. client.begin("broker.shiftr.io", net);
  54. client.onMessage(messageReceived);
  55. connect();
  56. }
  57. void loop() {
  58. client.loop();
  59. if (!client.connected()) {
  60. connect();
  61. }
  62. // publish a message roughly every second.
  63. if (millis() - lastMillis > 1000) {
  64. lastMillis = millis();
  65. client.publish("/hello", "world");
  66. }
  67. }