You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP32 Dev Module编译报错求助:JSON格式改造后编译失败

ESP32 + DHT传感器JSON上传编译错误修复方案

基于ESP32和DHT传感器的项目,在改用DynamicJsonDocument封装JSON数据后出现编译错误:Exit status 1 Error compiling for board ESP32 Dev Module,以下是问题代码的核心错误点及修复方案。

核心错误点

  • 缺失DHT库引用:代码实例化了DHT对象,但未包含对应头文件,导致编译时找不到类定义。
  • 重复包含JSON库:重复引入Arduino_JSON.h,可能引发符号冲突。
  • HTTP请求Content-Type不匹配:使用JSON格式发送数据,但设置的Content-Type为application/x-www-form-urlencoded,不符合要求。
  • HTTP对象重复初始化:在loop中调用http.begin后,又在请求函数内重复处理,导致资源占用冲突。

修复后的完整代码

#include <ESP_WiFiManager.h>
#include <Arduino_JSON.h>
#include <ArduinoJson.h>
#include <DHT.h>  // 添加DHT库引用

//----------------------------------------Support libraries and sensor parameters.
#ifdef ESP32
  #include <WiFi.h>
  #include <HTTPClient.h>
  #include <WebServer.h>
  #include <ESPmDNS.h>
#else
//  #include <ESP8266WiFi.h>
//  #include <WiFiClient.h>
//  #include <ESP8266HTTPClient.h>
//  #include <ESP8266WebServer.h>
//  #include <ESP8266mDNS.h>
#endif

#define ON_Board_LED 2
#define DHT_PIN 27
#define DHT_SENSOR_TYPE DHT11
DHT dht_sensor(DHT_PIN, DHT_SENSOR_TYPE);
//----------------------------------------

/*
  SEND DHT DATA TO THE SERVER BASED ON 
  PROJECT API_KEY
  06-02-023
*/

//----------------------------------------Network credentials definition.
const char* ssid = ""; //--> Your wifi name or SSID.
const char* password = ""; //--> Your wifi PASSWORD.
String apiKeyValue = "";
const char* server_url = "";
//----------------------------------------


//----------------------------------------Control variables.
int temperature;
int humidity;
int humid_threshold;
int temp_threshold;
String payload;
WiFiClient client;
HTTPClient http;
String httpRequestData= "0";
int httpResponseCode= 0;
unsigned long lastTime = 0;
unsigned long timerDelay = 5000;
//----------------------------------------


void setup() {
  
  Serial.begin(115200);
  delay(10);
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  pinMode(ON_Board_LED,OUTPUT);     //--> On Board LED port Direction output
  digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board

  Serial.print("Connecting.");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    //----------------------------------------Make the On Board Flashing LED on the process of connecting to the wifi router.
    digitalWrite(ON_Board_LED, LOW);
    delay(250);
    digitalWrite(ON_Board_LED, HIGH);
    delay(250);
    //----------------------------------------
  }
  //----------------------------------------
  digitalWrite(ON_Board_LED, LOW); //--> Turn off the On Board LED when it is connected to the wifi router.
  //----------------------------------------If successfully connected to the wifi router, the IP Address that will be visited is displayed in the serial monitor
  Serial.println("");
  Serial.print("Successfully connected to : ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  
  dht_sensor.begin(); // initialize the DHT sensor
  //----------------------------------------

  Serial.println("Server started");
  Serial.println(WiFi.localIP());
  Serial.println("");
  delay(1000);
  Serial.print("connecting...");

  delay(2000);
}

void loop() {
  
  // take sensor readings
  humidity  = dht_sensor.readHumidity();
  temperature = dht_sensor.readTemperature();

  // check whether the reading is successful or not
  if ( isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  //  get server response from handler fn
  String dht_data = httpPostRequest(server_url);

  // decode response
  JSONVar json_res_data = JSON.parse(dht_data);

  // validate response type
  if(JSON.typeof(json_res_data) == "undefined"){
    Serial.println("Parsing input failed!");
    return;
  }

  // decode actual dht data
  humidity = (const int)(json_res_data["humidity"]);
  temperature = (const int)(json_res_data["temperature"]);
  humid_threshold = (const int)(json_res_data["humid_threshold"]);
  temp_threshold = (const int)(json_res_data["temp_threshold"]);
  
  Serial.println("");
  Serial.println("Temp: " + String(temperature));
  Serial.println("Humidity: " + String(humidity));
  Serial.println("Temp threshold: " + String(temp_threshold));
  Serial.println("Humid threshold: " + String(humid_threshold));

  delay(60000);

}

//  POST request function(修正函数名与实际请求类型一致)
String httpPostRequest(const char* serverName) {
  // Initialize http protocol(移到函数内初始化,避免重复)
  http.begin(client, serverName);
  
  //Specify content-type header(修正为JSON格式的Content-Type)
  http.addHeader("Content-Type", "application/json");   

  // Prepare POST request data
  DynamicJsonDocument doc(1024);
  doc["dht_sensor_API_KEY"] = apiKeyValue;
  doc["temperature"] = temperature;
  doc["humidity"] = humidity;

  // Serialize data to JSON
  serializeJson(doc, httpRequestData);
    
  // Send POST request
  httpResponseCode = http.POST(httpRequestData);

  if (httpResponseCode == 200) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
    Serial.println("");
    Serial.print("Payload: ");
    Serial.print(payload);
    Serial.println("");
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

关键修改说明

  1. 添加DHT库引用:新增#include <DHT.h>,解决DHT类未定义的编译错误。
  2. 移除重复库引用:删除重复的#include <Arduino_JSON.h>,避免符号冲突。
  3. 修正Content-Type:将application/x-www-form-urlencoded改为application/json,匹配JSON数据格式。
  4. 调整HTTP初始化逻辑:将http.begin移到httpPostRequest函数内部,避免loop中重复初始化导致的资源问题,同时修正函数名与实际请求类型一致。
  5. 移除冗余代码:删除loop中多余的http.begin调用,避免重复初始化HTTP客户端。

内容的提问来源于stack exchange,提问作者ochieno Eliud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 03:32:57