i'm trying to build an sensor service where a couple of sensors (DHT22, photo resistor and moisture sensor and an extra temperature sensor) are connected to an esp wroom 32. The wiring is correct. And now that i have connected all my sensors to my esp32, i want to send my data to an extra server, where i already succeeded. I can send my data with an post request but only data from my digital sensors.
Now my Problem: My photo resistor and moisture sensor are analog sensors not like the dht22 and if i try to connect to my wifi and get data from my analog sensors, only my analog sensors are sending false/static/default data.
My ESP is connected to my PC so i don't know if my power supply can be the problem. My Sketch is also not that big and "only" takes (72%) of my storage space. My analog sensors are connected to D2 and D4 Pin.
Has anybody a suggestion what i can do, to fix my problem. I know that every sensor works and also all together just without the wifi/post/get request function.
This is my great code. with great german and english comments. (i hope you get my irony).
#include <WiFi.h>
#include <HTTPClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ArduinoJson.h>
#include <ESPAsyncWebSrv.h>
#include "DHT.h"
#define DHTPIN 21
#define KY001_Signal_PIN 5
#define DHTTYPE DHT22
// Bibliotheken werden konfiguriert
DHT dht(DHTPIN, DHTTYPE);
OneWire oneWire(KY001_Signal_PIN);
DallasTemperature sensors(&oneWire);
int sensorPin = 4; //fotowiderstand der nicht geht
int soilMoistPin = 2; // bodenfeuchte
const int soilMoistLevelLow = 533; //Dieser Wert soll von euch entsprechend angepasst werden
const int soilMoistLevelHigh = 258; //Dieser Wert soll von euch entsprechend angepasst werden
const size_t bufferSize = JSON_OBJECT_SIZE(5); // hier wird die anzahl der json felder definiert
const char* ssid = "ssid";
const char* password = "password";
AsyncWebServer server(80);
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 5000;
// Set timer to 30 seconds
unsigned long timerDelay = 30000;
void setup() {
Serial.begin(115200);
// Sensor intialisierung
wifiSetup();
dht.begin();
sensors.begin();
pinMode(soilMoistPin, INPUT);
getRequestFunc();
}
void wifiSetup(){
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(300);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println(WiFi.status());
Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
float getMoisture(){
int soilMoist = analogRead(soilMoistPin);
Serial.print("Analog Value: ");
Serial.print(soilMoist);
// Auswertung der Bodenfeuchtigkeit in Prozent
int percentSoilMoist = map(soilMoist, soilMoistLevelHigh, soilMoistLevelLow, 100, 0);
Serial.print("\t");
Serial.print(percentSoilMoist);
Serial.println(" %");
return percentSoilMoist;
}
float getTemperature(){
float temperature;
sensors.requestTemperatures();
// ... und die gemessene Temperatur wird ausgeben
temperature = sensors.getTempCByIndex(0);
Serial.print("Temperatur: ");
Serial.print(sensors.getTempCByIndex(0));
Serial.println(" °C");
return temperature;
}
void getDHTData(){
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("°C "));
Serial.print(f);
Serial.print(F("°F Heat index: "));
Serial.print(hic);
Serial.print(F("°C "));
Serial.print(hif);
Serial.println(F("°F"));
}
float getFotowiderstand(){
// Aktueller Spannungswert wird gemessen...
float rawValue = analogRead(sensorPin);
float voltage = ((4095 - rawValue) / 4095) * 100;
// Helligkeit in Prozent = ((Maximalwert - Aktuelle Spannung) / Maximalwert) * 100
// float resitance = 10000 * ( voltage / ( 5000.0 - voltage) );
// ... und hier auf die serielle Schnittstelle ausgegeben
Serial.print("Aktuelle Helligkeit:"); Serial.print(voltage); Serial.print(" %");
Serial.print("Eigentliche Spannung:"); Serial.print(rawValue); Serial.println("mV");
Serial.println("---------------------------------------");
return voltage;
}
// String getMac(){
// uint8_t mac[6];
// WiFi.macAddress(mac);
// // Convert MAC address to string
// char macStr[18];
// sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
// // Print the MAC address
// Serial.print("MAC Address: ");
// Serial.println(macStr);
// return macStr;
// }
void getRequestFunc(){
server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request) {
// Request handling
float temperature = getTemperature();
String temperatureString = String(temperature, 2); // Format the temperature with 2 decimal places
request->send(200, "text/plain", temperatureString);
postFunction();
});
// Start the server
server.begin();
}
void postFunction(){
// WiFiClient client;
HTTPClient http;
http.begin("https://sensor-backend-iwillnotsharethat/sensor/post");
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(mapToJson());
if(httpResponseCode>0){
String response = http.getString(); //Get the response to the request
Serial.println(httpResponseCode); //Print return code
Serial.println(response); //Print request answer
}
else{
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
}
String mapToJson(){
StaticJsonDocument<bufferSize> jsonDocument;
float fotowiderstand = getFotowiderstand();
jsonDocument["temperature"] = dht.readTemperature();
jsonDocument["sensorId"] = "100";
jsonDocument["humidity"] = dht.readHumidity();
jsonDocument["light"] = fotowiderstand;
jsonDocument["moisture"] = getMoisture();
String jsonString;
serializeJson(jsonDocument, jsonString);
Serial.println(jsonString);
return jsonString;
}
void loop() {
checkIfAllSensorsAlive();
//Send an HTTP POST request every 30 seconds minutes
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
postFunction();
}
else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
delay(5000);
}
void checkIfAllSensorsAlive(){
getMoisture();
getDHTData();
getFotowiderstand();
getTemperature();
}`
ADC2 (GPIOs 0, 2, 4, 12 - 15 and 25 - 27) is used by WiFi, unfortunately you can't use it at the same time.
Solution: use ADC1 (GPIOs 32 - 39).
https://docs.espressif.com/projects/esp-idf/en/v4.2/esp32/api-reference/peripherals/adc.html