Skip to content

Instantly share code, notes, and snippets.

@empi89
Created June 13, 2016 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save empi89/32e1866902578be811808f330a5ececf to your computer and use it in GitHub Desktop.
Save empi89/32e1866902578be811808f330a5ececf to your computer and use it in GitHub Desktop.
#include <SPI.h>
#include <PubSubClient.h>
#include <Ethernet.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define DEBUG
#ifdef DEBUG
#define DEBUG_PRINT(x) Serial.println (x)
#else
#define DEBUG_PRINT(x)
#endif
byte mac[]= {0x90, 0xA2, 0xDA, 0x0D, 0x88, 0x5E} ; // change by your arduino mac address
char server[] = "192.168.XXX.XXX";
unsigned int port = 1883;
char topicPrefix[] = "/my/topic/"; // topic where to publish; must be under your root topic
char deviceName[] = "myarduino";
int delayTime = 5000;
EthernetClient client;
PubSubClient arduinoClient(server, port, 0, client) ; //no callback function is specified as we only publish
// DS18S20 Temperature chip i/o
OneWire ds(2);
DallasTemperature dallas(&ds);
void setup() {
Serial.begin(9600);
DEBUG_PRINT(F("Initialisation"));
beginOneWire();
beginConnection();
}
int sensorCount;
void beginOneWire() {
dallas.begin();
sensorCount = dallas.getDeviceCount();
Serial.print(F("Found sensor count: "));
Serial.println(sensorCount, DEC);
}
void beginConnection(){
DEBUG_PRINT(F("Entering beginConnection"));
if (Ethernet.begin(mac) == 0) {
Serial.println(F("Failed to configure Ethernet using DHCP"));
exit(-1);
};
DEBUG_PRINT(F("Obtained IP Address:"));
DEBUG_PRINT(Ethernet.localIP());
if (arduinoClient.connect(deviceName)) {
DEBUG_PRINT(F("Connected to MQTT Server..."));
} else {
Serial.println(F("Failed to connect to the MQTT Server"));
exit(-1);
}
}
void loop(void) {
if (arduinoClient.loop()){
DEBUG_PRINT(F("Arduino Client loop ok"));
dallas.requestTemperatures();
for (int i = 0; i < sensorCount; i++) {
DeviceAddress da;
if (!dallas.getAddress(da, i)) {
Serial.print(i);
DEBUG_PRINT(F(" sensor index not found"));
continue;
}
float temp = dallas.getTempC(da);
char topic[60];
sprintf(topic, "%s%02X%02X%02X%02X%02X%02X%02X%02X", topicPrefix, da[0], da[1], da[2], da[3], da[4], da[5], da[6], da[7]);
Serial.print(F("ID:"));
Serial.print(topic);
Serial.print(F(" Temp:"));
Serial.println(temp);
char buffer[15];
dtostrf(temp, 4, 2, buffer);
arduinoClient.publish(topic, buffer);
}
} else {
DEBUG_PRINT(F("Arduino Client loop nok"));
if (!arduinoClient.connected()) {
DEBUG_PRINT(F("arduinoClient is not connected"));
beginConnection();
} else {
DEBUG_PRINT(F("arduinoClient is connected"));
}
}
delay(delayTime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment