Created
February 11, 2019 00:46
-
-
Save mcomisso/da39e60125f9cec8a32fed857ce26175 to your computer and use it in GitHub Desktop.
ESP+OneWire temperature
This file contains 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
#include <ESP8266WiFi.h> | |
#include <OneWire.h> | |
#include <PubSubClient.h> | |
#include <DallasTemperature.h> | |
const char* ssid = "SSID"; | |
const char* password = "PASSWORD"; | |
const char* mqtt_server = "X.X.X.X"; | |
#define ONE_WIRE_BUS 2 | |
OneWire oneWire(ONE_WIRE_BUS); | |
DallasTemperature sensors(&oneWire); | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
long lastMsg = 0; | |
char temperatureString[6]; | |
int value = 0; | |
void setup_wifi() { | |
delay(5); | |
Serial.println("Connecting to "); | |
Serial.println(ssid); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
randomSeed(micros()); | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.println("IP Address: "); | |
Serial.println(WiFi.localIP()); | |
// Start sensors | |
sensors.begin(); | |
} | |
void setup() { | |
Serial.begin(115200); | |
setup_wifi(); | |
client.setServer(mqtt_server, 1883); | |
} | |
void reconnect() { | |
// Loop until we're reconnected | |
while (!client.connected()) { | |
Serial.print("Connecting to MQTT, server: "); | |
Serial.print(mqtt_server); | |
// Create a random client ID | |
String clientId = "ESP8266Client-"; | |
clientId += String(random(0xffff), HEX); | |
// Attempt to connect | |
if (client.connect(clientId.c_str())) { | |
Serial.println("connected"); | |
} else { | |
Serial.print("failed, rc="); | |
Serial.print(client.state()); | |
Serial.println(" try again in 5 seconds"); | |
delay(5000); | |
} | |
} | |
} | |
void loop() { | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
long now = millis(); | |
if (now - lastMsg > 30000) { | |
lastMsg = now; | |
Serial.println("Requesting temperature"); | |
sensors.requestTemperatures(); | |
delay(100); | |
float tempC = sensors.getTempCByIndex(0); | |
Serial.println(tempC); | |
dtostrf(tempC, 2, 2, temperatureString); | |
Serial.println("Sending temperature..."); | |
client.publish("home/livingRoom/temp", temperatureString); | |
} | |
delay(100); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment