Search Forums
Forum Recent Posts
MQTT LED with Button Sketch
Views 299
Sweets 0
Images 3

10 months ago Topic

DaVaR
Offline
Administrator
Total Posts: 33
Joined: August 27, 2017
Posted: January 23, 2020 @ 06:56 PM
This is a simple sketch that allows the Arduino to communicate with an MQTT server. The Arduino updates the server and gets information from the server as to what it needs to do. So if a user pushes the button connected to the Arduino, the Arduino sends a message to the server. The Arduino then checks the server to see if the leds should be on or off. I created this sketch to get help familiarize myself with this style of setup. Hope to integrate with current Home Automation Boards. This sketch also utilizes an auth connection to the MQTT server with username and password needed. I used Node-Red to mange the flow with my MQTT server.
Code

/**
 * MyArduinoHome - www.myarduinohome.com
 * MQTT LED with Button
 * 
 * Connects to server with auth username and password
 * 
 * Topics used in this sketch:
 * mah-controller, LEDA, LEDB
 * 
 * Arduino reads topics from MQTT server to set LEDs as on or off.
 * Arduino reads button status and updates MQTT server topics
 */

#include <Ethernet.h>
#include <PubSubClient.h>
#include <ctype.h>

// Ethernet Settings
// Ethernet MAC address - must be unique on your local network
byte mac[] = { 0xDE, 0xAD, 0xEB, 0xEF, 0xFE, 0x24 };

// Debug Settings
#define DEBUG 0   // 1 For Debugging - 0 To Disable Debugging
// Debug takes up too much memory for UNO

// MQTT Server Connection Settings
const char* mqtt_server = "mqtt.myarduinohome.com";  // Server IP or Domain
const char* mqtt_username = "*****************"; // Server Username 
const char* mqtt_password = "*****************"; // Server Password

// Setup LEDs
const int LEDA = 7;
const int LEDB = 8;
const int buttonPin = 6;

int buttonState = 0;
int buttonReading;
int lastButtonState = 0;
int lightState = LOW;
int lastLightState = LOW;

// Try send data from callback to loop
String cbdata =  "";
String payload_buffer = "";

void callback(char* topic, byte* payload, unsigned int length) {
  if( DEBUG ) Serial.print("Message arrived [");
  if( DEBUG ) Serial.print(topic);
  if( DEBUG ) Serial.print("] ");
  for (int i=0;i<length;i++) {
    if( DEBUG ) Serial.print((char)payload[i]);
    if(isdigit((char)payload[i])){
      payload_buffer += (char)payload[i];
    }
  }
  if( DEBUG ) Serial.print("payload_buffer callback : ");
  if( DEBUG ) Serial.println(payload_buffer);
  if( DEBUG ) Serial.println();

  // Turn LEDs on or off based on data from server.
  if(strcmp(topic,"LEDA")==0){
    if((char)payload[0] == '1'){
      digitalWrite(LEDA, HIGH);
    }else{
      digitalWrite(LEDA, LOW);
    }
  }
  if(strcmp(topic,"LEDB")==0){
    if((char)payload[0] == '1'){
      digitalWrite(LEDB, HIGH);
    }else{
      digitalWrite(LEDB, LOW);
    }
  }

  if(payload_buffer){
    cbdata = payload_buffer;
    if( DEBUG ) Serial.print("cbdata callback : ");
    if( DEBUG ) Serial.println(cbdata);
  }
  payload_buffer = "";
}

EthernetClient ethClient;
PubSubClient client(ethClient);

// Let system know if internet is working or not
bool internetEnabled = true;

unsigned long lastMillis = 0;

/** Connect to MQTT Broker **/
void connect_mqtt() {
  Serial.println("Connecting to MQTT Broker");
  while (!client.connect("arduino", mqtt_username, mqtt_password)) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("\nconnected!");
  client.subscribe("mah-controller");
}

// Connect/Reconnect to MQTT server if not connected
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("arduino", "davar", "TDiwtcm3165*%")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("mah-controller","hello from arduino");
      // ... and resubscribe
      client.subscribe("mah-controller");
      client.subscribe("LEDA");
      client.subscribe("LEDB");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
    client.publish("mah-controller", "Reconnected to Arduino");
  }
}

// Display incoming messages
void messageReceived(String &topic, String &payload) {
  if( DEBUG ) Serial.println("incoming: " + topic + " - " + payload);
}

/** Setup **/
void setup() {
  Serial.begin(57600);

  // Ready the LEDs and Button
  pinMode(LEDA,OUTPUT);
  pinMode(LEDB,OUTPUT);
  pinMode(buttonPin, INPUT);

  // Set MQTT settings
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  // Connect to the local network
  if (Ethernet.begin(mac) == 0){
    Serial.println(" | Failed to connect to local network.  Running in   ");
    Serial.println(" | No Internet Mode.  Website and other internet     ");
    Serial.println(" | devices will NOT work.  Please check your network ");
    Serial.println(" | and reset the Arduino controller.                 ");
    Serial.println(" --------------------------------------------------- ");
    Serial.println("");
    Serial.println("");
    internetEnabled = false;
  }else{
    Serial.print(" | IP Address        : ");
    Serial.println(Ethernet.localIP());
    Serial.print(" | Subnet Mask       : ");
    Serial.println(Ethernet.subnetMask());
    Serial.print(" | Default Gateway IP: ");
    Serial.println(Ethernet.gatewayIP());
    Serial.print(" | DNS Server IP     : ");
    Serial.println(Ethernet.dnsServerIP());
    Serial.println(" --------------------------------------------------- ");
    Serial.println("");
    Serial.println("");
    internetEnabled = true;
  }

  delay(5000);
}

/** Loop **/
void loop() {

  // Read button's status
  buttonReading = digitalRead(buttonPin);
  if(buttonReading == HIGH && lastButtonState == LOW){    
    // Get button state and control LED based on that
    if (buttonState == HIGH){
      buttonState = LOW;
    }else{
      buttonState = HIGH;
    }
  }

  if (!client.connected()) {
    reconnect();
  }

  client.loop();

  // publish a message roughly every 10 seconds.
  if (millis() - lastMillis > 10000) {
    lastMillis = millis();
    client.publish("mah-controller", "loop ping");
  }

  // Check status of button and led
  if(buttonState == HIGH){ 
    if(lastLightState == LOW){     
      client.publish("LEDA", "1");
      lightState = HIGH;
    }
  }else{
    if(lastLightState == HIGH){
      client.publish("LEDA", "0");
      lightState = LOW;
    }
  }

  // Set the current light and button settings for next loop
  lastLightState = lightState;
  lastButtonState = buttonReading;

}
Here is the Node-Red flow
Code

[{"id":"ab47feb1.fbc318","type":"tab","label":"Flow 1","disabled":false,"info":""},{"id":"29c95fc8.f16cc8","type":"inject","z":"ab47feb1.fbc318","name":"light on","topic":"mah-controller","payload":"lighton","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":170,"y":140,"wires":[["bf7279d1.e40448"]]},{"id":"bf7279d1.e40448","type":"mqtt out","z":"ab47feb1.fbc318","name":"","topic":"mah-controller","qos":"","retain":"","broker":"b16335e9.c8c3b8","x":510,"y":140,"wires":[]},{"id":"cff0a85f.454aa","type":"mqtt in","z":"ab47feb1.fbc318","name":"","topic":"mah-controller","qos":"2","datatype":"auto","broker":"b16335e9.c8c3b8","x":190,"y":240,"wires":[["2a3c385.c9fb7c8"]]},{"id":"2a3c385.c9fb7c8","type":"debug","z":"ab47feb1.fbc318","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","x":490,"y":240,"wires":[]},{"id":"58d9c20.28f84c","type":"inject","z":"ab47feb1.fbc318","name":"LED A OFF","topic":"LEDA","payload":"0000000000000000","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":170,"y":400,"wires":[["e6ed666a.544648"]]},{"id":"e6ed666a.544648","type":"mqtt out","z":"ab47feb1.fbc318","name":"","topic":"LEDA","qos":"","retain":"","broker":"b16335e9.c8c3b8","x":490,"y":380,"wires":[]},{"id":"c9edfefb.fc94a8","type":"inject","z":"ab47feb1.fbc318","name":"LED A ON","topic":"LEDA","payload":"1111111111111111","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":160,"y":360,"wires":[["e6ed666a.544648"]]},{"id":"dd4c6643.eb3448","type":"inject","z":"ab47feb1.fbc318","name":"LED B OFF","topic":"LEDB","payload":"0000000000000000","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":170,"y":560,"wires":[["f4968a9a.bbe4c"]]},{"id":"f4968a9a.bbe4c","type":"mqtt out","z":"ab47feb1.fbc318","name":"","topic":"LEDB","qos":"","retain":"","broker":"b16335e9.c8c3b8","x":490,"y":540,"wires":[]},{"id":"f7734762.619808","type":"inject","z":"ab47feb1.fbc318","name":"LED B ON","topic":"LEDB","payload":"1111111111111111","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":160,"y":520,"wires":[["f4968a9a.bbe4c"]]},{"id":"3fc00992.2042be","type":"mqtt in","z":"ab47feb1.fbc318","name":"","topic":"LEDA","qos":"2","datatype":"auto","broker":"b16335e9.c8c3b8","x":130,"y":440,"wires":[["2ca0fa27.ad9eae"]]},{"id":"2ca0fa27.ad9eae","type":"debug","z":"ab47feb1.fbc318","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","x":510,"y":440,"wires":[]},{"id":"59f3ce4b.7d3958","type":"mqtt in","z":"ab47feb1.fbc318","name":"","topic":"LEDB","qos":"2","datatype":"auto","broker":"b16335e9.c8c3b8","x":130,"y":600,"wires":[["a46a3d8e.8a9d6"]]},{"id":"a46a3d8e.8a9d6","type":"debug","z":"ab47feb1.fbc318","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","x":510,"y":600,"wires":[]},{"id":"b16335e9.c8c3b8","type":"mqtt-broker","z":"","name":"DaVaR","broker":"mqtt.myarduinohome.com","port":"1883","tls":"9e96a21f.8261e","clientid":"davar","usetls":false,"compatmode":false,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"9e96a21f.8261e","type":"tls-config","z":"","name":"","cert":"","key":"","ca":"","certname":"","keyname":"","caname":"","servername":"","verifyservercert":true}]


Signature Send me a PM if your interested in purchasing any of the PCBs I've created.

Reply By: DaVaR
10 months ago #1

DaVaR
Offline
Administrator
Total Posts: 33
Joined: August 27, 2017
Posted: January 23, 2020 @ 07:29 PM
Arduino With Breadboard

Signature Send me a PM if your interested in purchasing any of the PCBs I've created.
Image Attachments

Forum Permissions
You cannot post in this forum.
You cannot moderate this forum.
You cannot administrate this forum.