#include <OneWire.h>
#include <Arduino.h>
#include <Ticker.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "DHT.h"
#include <SPI.h>
#include <Adafruit_MPU6050.h>
#include <SD.h>
#include <WiFiManager.h>
#define TRIGGER_PIN 0
Adafruit_MPU6050 mpu;
bool wm_nonblocking = false; // change to true to use non blocking
WiFiManager wm; // global wm instance
WiFiManagerParameter custom_field; // global param ( for non blocking w params )
unsigned long previousMillis = 0;
String dataString ="";
File sensorData;
const int CS = 5;
// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;
// Setup a oneWire instance to communicate with any OneWire devices
//OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
//DallasTemperature sensors(&oneWire);
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
#include "DHTesp.h" // Click here to get the library: http://librarymanager/All#DHTesp
#ifndef ESP32
#pragma message(THIS EXAMPLE IS FOR ESP32 ONLY!)
#error Select ESP32 board.
#endif
/** Initialize DHT sensor 1 */
DHTesp dhtSensor1;
/** Initialize DHT sensor 2 */
DHTesp dhtSensor2;
/** Initialize DHT sensor 3 */
//DHTesp dhtSensor3;
/** Task handle for the light value read task */
TaskHandle_t tempTaskHandle = NULL;
/** Pin number for DHT11 1 data pin */
int dhtPin1 = 17;
/** Pin number for DHT11 2 data pin */
int dhtPin2 = 16;
/** Pin number for DHT11 3 data pin */
//int dhtPin3 = 27;
/** Ticker for temperature reading */
Ticker tempTicker;
/** Flags for temperature readings finished */
bool gotNewTemperature = false;
/** Data from sensor 1 */
TempAndHumidity sensor1Data;
/** Data from sensor 2 */
TempAndHumidity sensor2Data;
/** Data from sensor 3 */
//TempAndHumidity sensor3Data;
/* Flag if main loop is running */
bool tasksEnabled = false;
/**
* Task to reads temperature from DHT11 sensor
* @param pvParameters
* pointer to task parameters
*/
void tempTask(void *pvParameters) {
Serial.println("tempTask loop started");
while (1) // tempTask loop
{
if (tasksEnabled && !gotNewTemperature) { // Read temperature only if old data was processed already
// Reading temperature for humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
sensor1Data = dhtSensor1.getTempAndHumidity(); // Read values from sensor 1
sensor2Data = dhtSensor2.getTempAndHumidity(); // Read values from sensor 1
//sensor3Data = dhtSensor3.getTempAndHumidity(); // Read values from sensor 1
gotNewTemperature = true;
}
vTaskSuspend(NULL);
}
}
/**
* triggerGetTemp
* Sets flag dhtUpdated to true for handling in loop()
* called by Ticker tempTicker
*/
void triggerGetTemp() {
if (tempTaskHandle != NULL) {
xTaskResumeFromISR(tempTaskHandle);
}
}
/**
* Arduino setup function (called once after boot/reboot)
*/
void setup() {
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
Serial.begin(115200);
Serial.setDebugOutput(true);
delay(3000);
Serial.println("\n Starting");
if(!mpu.begin()) {
Serial.println("MPU6050 not found");
//while(1);
}
pinMode(CS, OUTPUT);
pinMode(35, INPUT);
pinMode(TRIGGER_PIN, INPUT);
pinMode(26, OUTPUT);
pinMode(33, OUTPUT);
digitalWrite(33, LOW);
digitalWrite(26, HIGH);
if(wm_nonblocking) wm.setConfigPortalBlocking(false);
// add a custom input field
int customFieldLength = 40;
const char* custom_radio_str = "<br/><label for='customfieldid'>Custom Field Label</label><input type='radio' name='customfieldid' value='1' checked> One<br><input type='radio' name='customfieldid' value='2'> Two<br><input type='radio' name='customfieldid' value='3'> Three";
new (&custom_field) WiFiManagerParameter(custom_radio_str); // custom html input
wm.addParameter(&custom_field);
wm.setSaveParamsCallback(saveParamCallback);
std::vector<const char *> menu = {"wifi","info","param","sep","restart","exit"};
wm.setMenu(menu);
// set dark theme
wm.setClass("invert");
wm.setConfigPortalTimeout(10); // auto close configportal after n seconds
bool res;
res = wm.autoConnect("AutoConnectAP","password"); // password protected ap
if(!res) {
Serial.println("Failed to connect or hit timeout");
}
else {
digitalWrite(26, LOW);
digitalWrite(33, HIGH);
Serial.println("connected...yeey :)");
}
sensors.begin();
while (!Serial) { ; } // wait for serial port to connect. Needed for native USB port only
Serial.println("Initializing SD card...");
if (!SD.begin(CS)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
delay(2000);
display.clearDisplay();
display.setTextSize(3);
display.setTextColor(WHITE);
display.setCursor(0, 10);
// Display static text
display.println("WELCOME");
display.display();
//Init WiFi as Station, start SmartConfig
WiFi.mode(WIFI_AP_STA);
WiFi.beginSmartConfig();
Serial.println("Example for 3 DHT11/22 sensors");
// Initialize temperature sensor 1
//dhtSensor1.setup(dhtPin1, DHTesp::DHT22);
// Initialize temperature sensor 2
dhtSensor2.setup(dhtPin1, DHTesp::DHT22);
// Initialize temperature sensor 3
//dhtSensor3.setup(dhtPin3, DHTesp::DHT11);
// Start task to get temperature
xTaskCreatePinnedToCore(
tempTask, /* Function to implement the task */
"tempTask ", /* Name of the task */
4000, /* Stack size in words */
NULL, /* Task input parameter */
5, /* Priority of the task */
&tempTaskHandle, /* Task handle. */
1); /* Core where the task should run */
if (tempTaskHandle == NULL) {
Serial.println("[ERROR] Failed to start task for temperature update");
} else {
// Start update of environment data every 30 seconds
tempTicker.attach(10, triggerGetTemp);
}
// Signal end of setup() to tasks
tasksEnabled = true;
} // End of setup.
void ReadFile(const char * path){
// open the file for reading:
sensorData = SD.open(path);
if (sensorData) {
Serial.printf("Reading file from %s\n", path);
// read from the file until there's nothing else in it:
while (sensorData.available()) {
Serial.write(sensorData.read());
}
sensorData.close(); // close the file:
}
else {
// if the file didn't open, print an error:
Serial.println("error opening data");
}
}
void checkButton(){
// check for button press
if ( digitalRead(TRIGGER_PIN) == LOW ) {
// poor mans debounce/press-hold, code not ideal for production
delay(50);
if( digitalRead(TRIGGER_PIN) == LOW ){
Serial.println("Button Pressed");
// still holding button for 3000 ms, reset settings, code not ideaa for production
delay(3000); // reset delay hold
if( digitalRead(TRIGGER_PIN) == LOW ){
Serial.println("Button Held");
Serial.println("Erasing Config, restarting");
wm.resetSettings();
ESP.restart();
}
// start portal w delay
Serial.println("Starting config portal");
wm.setConfigPortalTimeout(120);
if (!wm.startConfigPortal("OnDemandAP","password")) {
Serial.println("failed to connect or hit timeout");
delay(3000);
// ESP.restart();
} else {
//if you get here you have connected to the WiFi
digitalWrite(26, LOW);
digitalWrite(33, HIGH);
Serial.println("connected...yeey :)");
}
}
}
}
String getParam(String name){
//read parameter from server, for customhmtl input
String value;
if(wm.server->hasArg(name)) {
value = wm.server->arg(name);
}
return value;
}
void saveParamCallback(){
Serial.println("[CALLBACK] saveParamCallback fired");
Serial.println("PARAM customfieldid = " + getParam("customfieldid"));
}
/**
* loop
* Arduino loop function, called once 'setup' is complete (your own code
* should go here)
*/
void loop() {
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
int so = analogRead(35);
// Calculate the direction of the sensor movement
int x = a.acceleration.x;
int y = a.acceleration.y;
int z = a.acceleration.z;
if(wm_nonblocking) wm.process(); // avoid delays() in loop when non-blocking and other long running code
//checkButton();
unsigned long currentMillis = millis();
// if WiFi is down, try reconnecting every CHECK_WIFI_TIME seconds
if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=1000)) {
Serial.print(millis());
Serial.println("Reconnecting to WiFi...");
digitalWrite(33, LOW);
digitalWrite(26, HIGH);
display.setCursor(3, 40);
display.setTextSize(1);
// Display static text
display.println("NOT CONNECTED");
display.display();
WiFi.disconnect();
WiFi.reconnect();
previousMillis = currentMillis;
}
if ((WiFi.status() == WL_CONNECTED) && (currentMillis - previousMillis >=10000)) {
Serial.print(millis());
Serial.println("Reconnecting to WiFi...");
digitalWrite(33, HIGH);
digitalWrite(26, LOW);
display.setTextSize(1);
display.setCursor(3, 40);
// Display static text
display.println("CONNECTED");
display.display();
previousMillis = currentMillis;
}
if (gotNewTemperature) {
Serial.println("Sensor 1 data:");
Serial.println("x" + String(x,2) + " y" + String(y,2) + " z" + String(z,2) );
Serial.println("Sensor 2 data:");
Serial.println("Temp: " + String(sensor2Data.temperature,2) + "'C Humidity: " + String(sensor2Data.humidity,1) + "%");
//Serial.println("Sensor 3 data:");
//Serial.println("Temp: " + String(sensor3Data.temperature,2) + "'C Humidity: " + String(sensor3Data.humidity,1) + "%");
sensors.requestTemperatures();
float temperatureC = sensors.getTempCByIndex(0);
Serial.print(temperatureC);
Serial.println("ºC");
Serial.println(so);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 10);
display.println("x" + String(x,3) + " y " + String(y,3) + " z " + String(z,3) );
display.setCursor(1, 20);
display.println("dt11 T:" + String(sensor2Data.temperature,2) + "' H:" + String(sensor2Data.humidity,1) + "%");
display.setCursor(2, 30);
display.println("sound " + String(so));
display.display();
gotNewTemperature = false;
dataString = + "dth11," +String(sensor2Data.temperature) + ", dth22," + String(sensor1Data.temperature) + ", sound," + String(so);
// check the card is still there
// now append new data file
sensorData = SD.open("/data.csv", FILE_APPEND);
if (sensorData){
sensorData.println(dataString);
Serial.println("Stored data:");
sensorData.close(); // close the file
}
ReadFile("/data.csv");
}
} // End of loop