Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Basic MQTT example
- - connects to an MQTT server
- - publishes "hello world" to the topic "led"
- - subscribes to the topic "led"
- - controls an led on pin 3
- - reads a button on pin 2
- - turns on/off the led when it receives "on"/"off" from the "led" topic
- - sends "on"/"off" to the "led" topic when the button is pressed
- */
- #include <SPI.h>
- #include <Ethernet.h>
- #include <PubSubClient.h>
- #include <Bounce2.h>
- int led = 3;
- int button = 2;
- int ledValue = LOW;
- // Arduino MAC address is on a sticker on your Ethernet shield
- byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x7D, 0x3A };
- // IP Address of your MQTT broker
- byte server[] = { 192, 168, 1, 101 };
- void callback(char* topic, byte* payload, unsigned int length) {
- // handle message arrived
- String content="";
- char character;
- for (int num=0;num<length;num++) {
- character = payload[num];
- content.concat(character);
- }
- Serial.println(content);
- if (content == "on") {
- ledValue = HIGH;
- }
- if (content == "off") {
- ledValue = LOW;
- }
- digitalWrite(led,ledValue);
- }
- EthernetClient ethClient;
- PubSubClient client(server, 1883, callback, ethClient);
- Bounce bouncer = Bounce();
- void setup()
- {
- pinMode(led, OUTPUT);
- pinMode(button,INPUT);
- digitalWrite(button,HIGH);
- bouncer .attach(button);
- bouncer .interval(5);
- Serial.begin(9600);
- Ethernet.begin(mac);
- if (client.connect("arduinoClient")) {
- client.publish("led","hello world");
- Serial.println("connected");
- client.subscribe("led");
- }
- }
- void loop()
- {
- if (bouncer.update()) {
- if (bouncer.read() == HIGH) {
- if (ledValue == LOW) {
- ledValue = HIGH;
- client.publish("led","on");
- } else {
- ledValue = LOW;
- client.publish("led","off");
- }
- }
- }
- client.loop();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement