Last active
January 11, 2019 21:57
-
-
Save nidayand/47511541716422da073a to your computer and use it in GitHub Desktop.
Arduino IDE code for esp8266 detecting 1-wire ds18b20 temperature and PIR-detector. Connects to wifi and MQTT broker and publishes temperature changes and PIR detections.
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 <OneWire.h> | |
#include <DallasTemperature.h> | |
#include <ESP8266WiFi.h> | |
#include <PubSubClient.h> | |
/* | |
* PIR must have 5V VCC. 3.3V is not enough. Using the USB power that is set to 5V to power it. | |
* PIR - VCC to 5V, Data to GPIO4 | |
* Left trim is sensitivity and right is time | |
* 1wire - Pull up resistor on 2,2kOhm for the data. Data to GPIO_2 | |
*/ | |
#define DELAY 10000 //Check temp every 10 sec | |
#define ONE_WIRE_BUS 2 // DS18B20 pin | |
#define PIR_PIN 4 //PIR pin | |
#define wifi_ssid "SSID" | |
#define wifi_password "password" | |
#define mqtt_server "192.168.2.195" | |
#define mqtt_port 1883 | |
#define mqtt_user "your_username" //if applicable. Change code where client connects to server | |
#define mqtt_password "your_password" //if applicable | |
#define pir_topic "/sensor/pir" | |
#define temperature_topic "/sensor/temperature" | |
#define start_topic "/raw/esp8266/" | |
#include "os_type.h" | |
//Declare onewire bus details | |
OneWire oneWire(ONE_WIRE_BUS); | |
DallasTemperature DS18B20(&oneWire); | |
//Timer for checking temperature | |
os_timer_t tempTimer; | |
float oldTemp; //Prev read temp | |
float temp; //Last read temp | |
//Declare PIR details | |
int oldInputState; | |
//WIFI and MQTT | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
String temp_topic_all; | |
String pir_topic_all; | |
/* Check the temperature data */ | |
void tempTimerCallback(void *pArg){ | |
//Getting the temperature | |
do { | |
DS18B20.requestTemperatures(); | |
temp = DS18B20.getTempCByIndex(0); | |
delay(100); | |
Serial.print("Temperature: "); | |
Serial.println(temp); | |
} while (temp == 85.0 || temp == (-127.0)); | |
if (temp != oldTemp) | |
{ | |
//send teperature | |
Serial.println("Sending updated temperature"); | |
//Send only if MQTT is connected | |
if (client.connected()){ | |
//As this is a timed event let the main loop manage reconnect to broker | |
client.publish(temp_topic_all.c_str(), f2s(temp,2) , false); | |
} | |
oldTemp = temp; | |
} | |
} | |
/* float to string | |
* f is the float to turn into a string | |
* p is the precision (number of decimals) | |
* return a string representation of the float. | |
*/ | |
char *f2s(float f, int p){ | |
char * pBuff; // use to remember which part of the buffer to use for dtostrf | |
const int iSize = 10; // number of bufffers, one for each float before wrapping around | |
static char sBuff[iSize][20]; // space for 20 characters including NULL terminator for each float | |
static int iCount = 0; // keep a tab of next place in sBuff to use | |
pBuff = sBuff[iCount]; // use this buffer | |
if(iCount >= iSize -1){ // check for wrap | |
iCount = 0; // if wrapping start again and reset | |
} | |
else{ | |
iCount++; // advance the counter | |
} | |
return dtostrf(f, 0, p, pBuff); // call the library function | |
} | |
void user_init(){ | |
//Define function to be called upon fired timer | |
os_timer_setfn(&tempTimer, tempTimerCallback, NULL); | |
//Start timer and repeat | |
os_timer_arm(&tempTimer, DELAY, true); | |
} | |
void setup() { | |
Serial.begin(115200); | |
Serial.print("Starting\n"); | |
//Setup WIFI and MQTT | |
setup_wifi(); | |
client.setServer(mqtt_server, mqtt_port); | |
//Setup onewire | |
oldTemp = -1; | |
temp_topic_all = String(start_topic)+String(ESP.getChipId())+String(temperature_topic); //Define the temp unique topic | |
//Setup PIR | |
pinMode(PIR_PIN, INPUT_PULLUP); | |
oldInputState = digitalRead(PIR_PIN); | |
pir_topic_all = String(start_topic)+String(ESP.getChipId())+String(pir_topic); //Deine the pir unique topic | |
//Initialize timer | |
user_init(); | |
} | |
void setup_wifi() { | |
delay(10); | |
// We start by connecting to a WiFi network | |
Serial.println(); | |
Serial.print("Connecting to "); | |
Serial.println(wifi_ssid); | |
WiFi.begin(wifi_ssid, wifi_password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.println("IP address: "); | |
Serial.println(WiFi.localIP()); | |
} | |
void reconnect() { | |
// Loop until we're reconnected | |
while (!client.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
// Attempt to connect | |
// If you do not want to use a username and password, change next line to | |
if (client.connect("ESP8266Client")) { | |
//if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) { | |
Serial.println("connected"); | |
} else { | |
Serial.print("failed, rc="); | |
Serial.print(client.state()); | |
Serial.println(" try again in 5 seconds"); | |
// Wait 5 seconds before retrying | |
delay(5000); | |
} | |
} | |
} | |
void loop() { | |
//Connect MQTT | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
//Checking PIR | |
int inputState = digitalRead(PIR_PIN); | |
if (inputState != oldInputState) | |
{ | |
if (inputState == 0){ | |
Serial.println("OFF"); | |
} else { | |
Serial.println("ON"); | |
} | |
//Send status to MQTT bus if connected | |
if (client.connected()){ | |
client.publish(pir_topic_all.c_str(), String(inputState).c_str(), false); | |
} | |
oldInputState = inputState; | |
} | |
yield(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment