Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jamesabruce/c599c979611dc1af49ef to your computer and use it in GitHub Desktop.
Save jamesabruce/c599c979611dc1af49ef to your computer and use it in GitHub Desktop.
/*
Basic MQTT example
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Our first sensor, a cheap DHT11 temperature and humidty sensor
#include <DHT.h>
#define DHTPIN 7
#define DHTTYPE DHT11 //21 or 22 also an option
DHT dht(DHTPIN, DHTTYPE);
unsigned long readTime;
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 151);
IPAddress server(192, 168, 1, 99);
char message_buff[100]; // this buffers our incoming messages so we can do something on certain commands
EthernetClient ethClient;
PubSubClient client(ethClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
int i=0;
for (i=0;i<length;i++) {
Serial.print((char)payload[i]);
message_buff[i] = payload[i];
}
message_buff[i] = '\0';
String msgString = String(message_buff);
if (msgString.equals("OFF")) {
client.publish("openhab/himitsu/command","acknowedging OFF");
}
else if(msgString.equals("ON")){
client.publish("openhab/himitsu/command","acknowedging ON");
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("openhab","himitsu sensor, reporting in");
// ... and resubscribe
client.subscribe("openhab/himitsu/command");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(57600);
client.setServer("192.168.1.99", 1883);
client.setCallback(callback);
Ethernet.begin(mac);
dht.begin();
// Allow the hardware to sort itself out
delay(1500);
Serial.println(Ethernet.localIP());
readTime = 0;
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
//check if 5 seconds has elapsed since the last time we read the sensors.
if(millis() > readTime+60000){
sensorRead();
}
}
void sensorRead(){
readTime = millis();
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
char buffer[10];
dtostrf(t,0, 0, buffer);
client.publish("openhab/himitsu/temperature",buffer);
//Serial.println(buffer);
dtostrf(h,0, 0, buffer);
client.publish("openhab/himitsu/humidity",buffer);
//client.publish("inTopic/humidity",sprintf(buf, "%f", h));
/*Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F"); */
}
@chandini95
Copy link

mqtt
mqtt1

kindly tell me how to execute this..i am a newbie and here i am using an arduino ethernet shield and arduino uno with LM35 temperature sensor to publish data..kindly reply asap

thanks in advance

@Jcappsiv
Copy link

I'm trying to do something similar with my Raspberry Pi is there a way to adapt this code for it? I'm using a DHT11 via GPIO pins and want to publish it to mqtt to monitor for OpenHab

@45Matches
Copy link

The way you've written your article, and the structure of this file has made MQTT for OpenHab, Arduino, PI finally click. Wandering out of the dark, into the light. (Somewhere somewhat lighter anyway). Much appreciated, thanks.

The concept of listening to a command channel, and publishing sensor readings to sensor channels - without trying to connect the two - was the thing that I was having difficulty getting my head around, in terms of implementation.

@rxbot420
Copy link

rxbot420 commented Apr 16, 2018

server Raspberry Pi3 (mqtt, Node Red) + Arduino Uno+ethernet shield w5100 (DHT11 + 2 diodes switch and slider)
sketch:

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

// Our first sensor, a cheap DHT11 temperature and humidty sensor
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11 //21 or 22 also an option
DHT dht(DHTPIN, DHTTYPE);
unsigned long readTime;

// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 28);
IPAddress server(192, 168, 0, 15);
char message_buff[100]; // this buffers our incoming messages so we can do something on certain commands

EthernetClient ethClient;
PubSubClient client(ethClient);

const int ledPin6 = 6;
const int ledPin7 = 7;

void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
// Feel free to add more if statements to control more Pins with MQTT
// If a message is received on the topic home/livingroom/arduino/ledPin6
// It's a value between 0 and 255 to adjust the LED brightness
if(String(topic)=="home/livingroom/arduino/ledPin6"){
Serial.print("Changing Digital Pin 6 Brithness to ");
Serial.print(messageTemp);
analogWrite(ledPin6, messageTemp.toInt());
}
// If a message is received on the topic home/livingroom/arduino/ledPin7,
//you check if the message is either 1 or 0. Turns the Arduino Digital Pin according to the message
if(String(topic)=="home/livingroom/arduino/ledPin7"){
Serial.print("Changing Digital Pin 7 to ");
if(messageTemp == "1"){
digitalWrite(ledPin7, HIGH);
Serial.print("On");
}
else if(messageTemp == "0"){
digitalWrite(ledPin7, LOW);
Serial.print("Off");
}
}
Serial.println();
}

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
// Subscribe or resubscribe to a topic
// You can subscribe to more topics (to control more LEDs in this example)
client.subscribe("home/livingroom/arduino/ledPin6");
client.subscribe("home/livingroom/arduino/ledPin7");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

void setup()
{
pinMode(ledPin6, OUTPUT);
pinMode(ledPin7, OUTPUT);

Serial.begin(57600);

client.setServer("192.168.0.15", 1883); // can be replaced by: client.setServer(server, 1883);
client.setCallback(callback);

Ethernet.begin(mac);

dht.begin();
// Allow the hardware to sort itself out
delay(1500);
Serial.println(Ethernet.localIP());
readTime = 0;
}

void loop()
{

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

client.loop();

//check if 5 seconds has elapsed since the last time we read the sensors.
if(millis() > readTime+6000){
sensorRead();
}

}

void sensorRead(){
readTime = millis();
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);

// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);

char buffer[10];
dtostrf(t,0, 0, buffer);
client.publish("openhab/himitsu/temperature",buffer);
//Serial.println(buffer);
dtostrf(h,0, 0, buffer);
client.publish("openhab/himitsu/humidity",buffer);

//client.publish("inTopic/humidity",sprintf(buf, "%f", h));
/*Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F"); */
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment