Created
February 6, 2014 16:23
-
-
Save codepope/8847534 to your computer and use it in GitHub Desktop.
The Arduino/MQTT temperature reading program
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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