Created
June 13, 2017 11:51
-
-
Save Ynn/dc763734d86e32fd3dabdf7945019722 to your computer and use it in GitHub Desktop.
Retrieve temperature from lm35 and publish it to sensor/temperature/1 Use cloudmqtt Requires : PubSubClient and ESP8266WiFi
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
/* | |
Retrieve temperature from lm35 and publish it to sensor/temperature/1 | |
Use cloudmqtt | |
Requires : PubSubClient and ESP8266WiFi | |
Licence : MIT | |
Inpired from : http://www.projetsdiy.fr/esp8266-dht22-mqtt-projet-objet-connecte/ | |
*/ | |
#include <Arduino.h> | |
#include <ESP8266WiFi.h> | |
#include <PubSubClient.h> | |
#define wifi_ssid "android-3G" | |
#define wifi_password "cvuvjyvv" | |
#define mqtt_server "m21.cloudmqtt.com" | |
#define mqtt_user "user" | |
#define mqtt_password "passw0rd" | |
#define mqtt_port 18029 | |
#define temperature_topic "sensor/temperature/1" | |
const int SENSOR_PIN = A0; | |
char message_buff[100]; | |
bool debug = false; | |
//Création des objets | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
//Connexion au réseau WiFi | |
void setup_wifi() { | |
delay(10); | |
Serial.println(); | |
Serial.print("Connect to "); | |
Serial.println(wifi_ssid); | |
WiFi.begin(wifi_ssid, wifi_password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println(" Established ... "); | |
Serial.print("IP : "); | |
Serial.print(WiFi.localIP()); | |
} | |
void setup() { | |
Serial.begin(9600); | |
setup_wifi(); | |
client.setServer(mqtt_server, mqtt_port); | |
} | |
void reconnect() { | |
while (!client.connected()) { | |
Serial.print("Connect to MQTT..."); | |
if (client.connect("ESP8266Client1", mqtt_user, mqtt_password)) { | |
Serial.println("OK"); | |
} else { | |
Serial.print("KO, Error : "); | |
Serial.print(client.state()); | |
Serial.println(" Wait ..."); | |
delay(5000); | |
} | |
} | |
} | |
long last = 0; | |
void loop() { | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
long now = millis(); | |
if (now - last > 1000 * 5) { | |
last = now; | |
int rawvoltage= analogRead(SENSOR_PIN); | |
float millivolts= (rawvoltage/1024.0) * 3300; | |
float celsius= millivolts/10; | |
float t = celsius; | |
if ( debug ) { | |
Serial.print("Temperature : "); | |
Serial.print(t); | |
} | |
client.publish(temperature_topic, String(t).c_str(), true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment