Skip to content

Instantly share code, notes, and snippets.

@binarybucks
Last active April 9, 2016 15:54
Show Gist options
  • Save binarybucks/fa32b0988aa7e209a9ee to your computer and use it in GitHub Desktop.
Save binarybucks/fa32b0988aa7e209a9ee to your computer and use it in GitHub Desktop.
Particle Photon HTU21D temperature/humidity sensor readings to MQTT
// This #include statement was automatically added by the Particle IDE.
#include "MQTT/MQTT.h"
#include "HTU21D/HTU21D.h"
int mqtt_port = 1883;
byte mqtt_host[] = { 192,168,1,4 };
String device_id = System.deviceID();
String mqtt_topic_temp = "sensors/"+ device_id + "/temp";
String mqtt_topic_humidty = "sensors/" + device_id + "/humidity";
String mqtt_topic_version = "sensors/" + device_id + "/version";
uint32_t timeMqttRetry;
char mqtt_message[20];
HTU21D htu;
MQTT mqttClient;
float humd;
float temp;
bool cloudConnecting;
SYSTEM_MODE(AUTOMATIC);
SYSTEM_THREAD(ENABLED);
// recieve message
void mqttCallback(char* topic, byte* payload, unsigned int length) {
delay(1000);
}
void conectMqtt() {
mqttClient.connect(device_id);
}
void setup() {
RGB.brightness(16);
htu = HTU21D();
while(!htu.begin()){
delay(1000);
}
mqttClient = MQTT(mqtt_host, 1883, mqttCallback);
conectMqtt();
}
void loop() {
if (mqttClient.isConnected()) {
timeMqttRetry = millis();
mqttClient.loop();
} else {
if(WiFi.ready() && Particle.connected()){
if((millis() - timeMqttRetry) >= 10000){
timeMqttRetry = millis();
conectMqtt();
}
}
}
humd = htu.readHumidity();
temp = htu.readTemperature();
sprintf(mqtt_message, "%f", temp);
mqttClient.publish(mqtt_topic_temp,mqtt_message);
sprintf(mqtt_message, "%f", humd);
mqttClient.publish(mqtt_topic_humidty,mqtt_message);
for(int i = 0; i<6; i++) { // sleep 30s but run mqtt client loop every 5 seconds
mqttClient.loop();
delay(5000);
}
if (!Particle.connected()) {
if (!cloudConnecting) {
Particle.connect();
cloudConnecting = true;
}
} else {
cloudConnecting = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment