Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The Arduino/MQTT temperature reading program
/*
Sensor to MQTT basic example
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
byte server[] = { 192, 168, 111, 50 };
byte ip[] = { 192, 168, 111, 240 };
int sensorPin=5;
int lastTemperature;
unsigned long lastTime;
char buffer[10];
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived (no messages expected though)
}
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup() {
Ethernet.begin(mac, ip);
if (client.connect("arduinoClient")) {
client.publish("demo/status/arduino01","online");
lastTemperature=0;
lastTime=0;
}
}
void loop() {
int reading=analogRead(sensorPin);
int temperature = ((reading * 0.004882)-0.50)*100;
if(temperature!=lastTemperature) {
if(millis()>(lastTime+1000)) {
sprintf(buffer,"%d",temperature);
client.publish("demo/device/arduino01",buffer);
lastTemperature=temperature;
lastTime=millis();
}
}
client.loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment