mqtt_stream.ino 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Example of using a Stream object to store the message payload
  3. Uses SRAM library: https://github.com/ennui2342/arduino-sram
  4. but could use any Stream based class such as SD
  5. - connects to an MQTT server
  6. - publishes "hello world" to the topic "outTopic"
  7. - subscribes to the topic "inTopic"
  8. */
  9. #include <SPI.h>
  10. #include <Ethernet.h>
  11. #include <PubSubClient.h>
  12. #include <SRAM.h>
  13. // Update these with values suitable for your network.
  14. byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
  15. IPAddress ip(172, 16, 0, 100);
  16. IPAddress server(172, 16, 0, 2);
  17. SRAM sram(4, SRAM_1024);
  18. void callback(char* topic, byte* payload, unsigned int length) {
  19. sram.seek(1);
  20. // do something with the message
  21. for(uint8_t i=0; i<length; i++) {
  22. Serial.write(sram.read());
  23. }
  24. Serial.println();
  25. // Reset position for the next message to be stored
  26. sram.seek(1);
  27. }
  28. EthernetClient ethClient;
  29. PubSubClient client(server, 1883, callback, ethClient, sram);
  30. void setup()
  31. {
  32. Ethernet.begin(mac, ip);
  33. if (client.connect("arduinoClient")) {
  34. client.publish("outTopic","hello world");
  35. client.subscribe("inTopic");
  36. }
  37. sram.begin();
  38. sram.seek(1);
  39. Serial.begin(9600);
  40. }
  41. void loop()
  42. {
  43. client.loop();
  44. }