Advertisement
Kyngston

Arduino MQTT IoT demo

Jun 4th, 2015
958
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. /*
  2.  Basic MQTT example
  3.  
  4.   - connects to an MQTT server
  5.   - publishes "hello world" to the topic "led"
  6.   - subscribes to the topic "led"
  7.   - controls an led on pin 3
  8.   - reads a button on pin 2
  9.   - turns on/off the led when it receives "on"/"off" from the "led" topic
  10.   - sends "on"/"off" to the "led" topic when the button is pressed
  11. */
  12.  
  13. #include <SPI.h>
  14. #include <Ethernet.h>
  15. #include <PubSubClient.h>
  16. #include <Bounce2.h>
  17.  
  18. int led = 3;
  19. int button = 2;
  20. int ledValue = LOW;
  21.  
  22. // Arduino MAC address is on a sticker on your Ethernet shield
  23. byte mac[]    = {  0x90, 0xA2, 0xDA, 0x0D, 0x7D, 0x3A };
  24. // IP Address of your MQTT broker
  25. byte server[] = { 192, 168, 1, 101 };
  26.  
  27.  
  28. void callback(char* topic, byte* payload, unsigned int length) {
  29.   // handle message arrived
  30.   String content="";
  31.   char character;
  32.   for (int num=0;num<length;num++) {
  33.       character = payload[num];
  34.       content.concat(character);
  35.   }  
  36.   Serial.println(content);
  37.   if (content == "on") {
  38.     ledValue = HIGH;
  39.   }
  40.   if (content == "off") {
  41.     ledValue = LOW;
  42.   }
  43.   digitalWrite(led,ledValue);
  44. }
  45.  
  46. EthernetClient ethClient;
  47. PubSubClient client(server, 1883, callback, ethClient);
  48. Bounce bouncer = Bounce();
  49.  
  50. void setup()
  51. {
  52.   pinMode(led, OUTPUT);
  53.   pinMode(button,INPUT);
  54.   digitalWrite(button,HIGH);
  55.   bouncer .attach(button);
  56.   bouncer .interval(5);
  57.   Serial.begin(9600);
  58.   Ethernet.begin(mac);
  59.   if (client.connect("arduinoClient")) {
  60.     client.publish("led","hello world");
  61.     Serial.println("connected");
  62.     client.subscribe("led");
  63.   }
  64. }
  65.  
  66. void loop()
  67. {
  68.   if (bouncer.update()) {
  69.     if (bouncer.read() == HIGH) {
  70.       if (ledValue == LOW) {
  71.         ledValue = HIGH;
  72.         client.publish("led","on");
  73.       } else {
  74.         ledValue = LOW;
  75.         client.publish("led","off");
  76.       }
  77.     }
  78.   }  
  79.   client.loop();
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement