Analog sensors (photo resistor and moisture sensor) do not work in combination with wifi function of ESP32

huangapple go评论57阅读模式
英文:

Analog sensors (photo resistor and moisture sensor) do not work in combination with wifi function of ESP32

问题

我正在尝试构建一个传感器服务,其中连接了几个传感器(DHT22、光敏电阻和湿度传感器以及额外的温度传感器)到一个ESP WROOM 32。连线是正确的。现在我已经将所有传感器连接到我的ESP32,我想要将数据发送到一个额外的服务器,我已经成功连接了。我可以通过POST请求发送我的数据,但只能发送来自我的数字传感器的数据。

现在我的问题是:我的光敏电阻和湿度传感器是模拟传感器,不像DHT22,如果我尝试连接到我的WiFi并从模拟传感器获取数据,只有我的模拟传感器发送虚假/静态/默认数据。

我的ESP连接到我的电脑上,所以我不知道我的电源供应是否可能是问题所在。我的代码也不是很大,只占用了我的存储空间的(72%)。我的模拟传感器连接到D2和D4引脚。

有没有人有建议,我可以怎么做来解决我的问题。我知道每个传感器都能工作,也能一起工作,只是没有WiFi/POST/GET请求功能。

这是我的优秀代码,有很好的德语和英语注释。(我希望你能理解我的讽刺)。

#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

// Libraries are configured
DHT dht(DHTPIN, DHTTYPE);
OneWire oneWire(KY001_Signal_PIN);
DallasTemperature sensors(&oneWire);

int sensorPin = 4;  // 光敏电阻
int soilMoistPin = 2;  // 土壤湿度

const int soilMoistLevelLow = 533;    // 这个值应根据您的需求进行调整
const int soilMoistLevelHigh = 258;   // 这个值应根据您的需求进行调整

const size_t bufferSize = JSON_OBJECT_SIZE(5); // 定义JSON字段的数量

const char* ssid = "ssid";
const char* password = "password";

AsyncWebServer server(80);

// 下面的变量是无符号长整数,因为时间以毫秒为单位测量,将很快变成一个比int可以存储的更大的数字。
unsigned long lastTime = 5000;
// 设置定时器为30秒
unsigned long timerDelay = 30000;

void setup() {
  Serial.begin(115200);
  // 传感器初始化
  wifiSetup();
  dht.begin();
  sensors.begin();
  pinMode(soilMoistPin, INPUT);
  getRequestFunc();
}

void wifiSetup() {
  WiFi.begin(ssid, password);
  Serial.println("连接中");
  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("已连接到WiFi网络,IP地址是:");
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.status());
  Serial.println("定时器设置为5秒(timerDelay变量),将在发布第一个读数之前等待5秒。");
}

float getMoisture() {
  int soilMoist = analogRead(soilMoistPin);
  Serial.print("模拟值:");
  Serial.print(soilMoist);
  // 湿度百分比
  int percentSoilMoist = map(soilMoist, soilMoistLevelHigh, soilMoistLevelLow, 100, 0);
  Serial.print("\t");
  Serial.print(percentSoilMoist);
  Serial.println(" %");
  return percentSoilMoist;
}

float getTemperature() {
  float temperature;
  sensors.requestTemperatures();
  // 输出测得的温度
  temperature = sensors.getTempCByIndex(0);
  Serial.print("温度:");
  Serial.print(sensors.getTempCByIndex(0));
  Serial.println(" °C");
  return temperature;
}

void getDHTData() {
  delay(2000);
  // 读取温度和湿度,此传感器读取温度和湿度需要时间,约250毫秒
  // 传感器读数也可能是最多2秒的“旧”读数(它是一个非常慢的传感器)
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("无法从DHT传感器读取数据!"));
    return;
  }
  float hif = dht.computeHeatIndex(f, h);
  float hic = dht.computeHeatIndex(t, h, false);
  Serial.print(F("湿度:"));
  Serial.print(h);
  Serial.print(F("%  温度:"));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  体感温度:"));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));
}

float getFotowiderstand() {
  float rawValue = analogRead(sensorPin);
  float voltage = ((4095 - rawValue) / 4095) * 100;
  Serial.print("当前亮度:");
  Serial.print(voltage);
  Serial.print(" %");
  Serial.print("实际电压:");
  Serial.print(rawValue);
  Serial.println(" mV");
  Serial.println("---------------------------------------");
  return voltage;
}

void getRequestFunc() {
  server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request) {
    // 处理请求
    float temperature = getTemperature();
    String temperatureString = String(temperature, 2);  // 以2位小数格式化温度
    request->send(200, "text/plain", temperatureString);
    postFunction();
  });
  // 启动服务器
  server.begin();
}

void postFunction() {
  HTTPClient http;
  http.begin("https://sensor-backend-iwillnotsharethat/sensor/post");
  http.addHeader("Content-Type", "application/json");
  int httpResponseCode = http.POST

<details>
<summary>英文:</summary>

i&#39;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&#39;t know if my power supply can be the problem. My Sketch is also not that big and &quot;only&quot; 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(&quot;Aktuelle Helligkeit:&quot;); Serial.print(voltage); Serial.print(&quot; %&quot;);
Serial.print(&quot;Eigentliche Spannung:&quot;); Serial.print(rawValue); Serial.println(&quot;mV&quot;);
Serial.println(&quot;---------------------------------------&quot;);
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(&quot;https://sensor-backend-iwillnotsharethat/sensor/post&quot;);
http.addHeader(&quot;Content-Type&quot;, &quot;application/json&quot;);
int httpResponseCode = http.POST(mapToJson());
if(httpResponseCode&gt;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(&quot;Error on sending POST: &quot;);
Serial.println(httpResponseCode);
}
http.end();
}

String mapToJson(){

StaticJsonDocument&lt;bufferSize&gt; jsonDocument;
float fotowiderstand = getFotowiderstand();
jsonDocument[&quot;temperature&quot;] = dht.readTemperature();
jsonDocument[&quot;sensorId&quot;] = &quot;100&quot;;
jsonDocument[&quot;humidity&quot;] =  dht.readHumidity();
jsonDocument[&quot;light&quot;] =  fotowiderstand;
jsonDocument[&quot;moisture&quot;] = 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();
}`


</details>
# 答案1
**得分**: 2
ADC2(GPIO 0、2、4、12 - 15 和 25 - 27)被WiFi使用,不幸的是你不能同时使用它。
解决方法:使用ADC1(GPIO 32 - 39)。
链接:https://docs.espressif.com/projects/esp-idf/en/v4.2/esp32/api-reference/peripherals/adc.html
<details>
<summary>英文:</summary>
ADC2 (GPIOs 0, 2, 4, 12 - 15 and 25 - 27) is used by WiFi, unfortunately you can&#39;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
</details>

huangapple
  • 本文由 发表于 2023年6月6日 02:21:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409057.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定