ESP32-C3 uses AsyncWebServer and HTTP client to realize dual computer communication

Because I just need to use dual computer communication to do my homework. By the way, I have found many methods on the Internet. I have tried to use Bluetooth communication, but I can only send strings (my personal ability can only reach this step, and I will further study Bluetooth communication later). The final implementation method is AsyncWebServer and HTTP client to realize dual computer communication.

Here, I regard the ESP32-C3 connected to the temperature and humidity sensor and air alarm as the server, and the ESP32-C3 connected to the OLED display as the client, one sending data and one receiving data.

1, Server

1. Environment configuration

You need to download the ESPAsyncWebServer library. You can download it on the official website or use the same resources I stored in Baidu online disk. After downloading, add the download library as before

Link: https://pan.baidu.com/s/1Yr8efIupvVDV9nMvxpvd2Q
Extraction code: xi0x

2. Code writing

2.1 call header file

#include "WiFi.h"
#include "FS.h"
#include "ESPAsyncWebServer.h"
#include "DHT.h"
#include <Wire.h>

2.2 define pin interface and server port

#Define dhtpin 7 / / DHT data port
#define DHTTYPE DHT11   // DHT 11
DHT dht(DHTPIN, DHTTYPE);
const int airtwo =6;   //Air alarm analog port

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

2.3 reading data

The function written here is to read the data first to facilitate data encapsulation, and because the temperature and humidity data function is encapsulated in the library, what if we want other sensor data? Here I wrote an air alarm, which can be used for reference.

//temperature
String readTemp() {
  return String(dht.readTemperature());
}

//humidity
String readHumi() {
  return String(dht.readHumidity());
}
//air
String readAir() {
  return String(Air());
}


String Air(){

  int newStat1 = digitalRead(airtwo);
   if(newStat1==HIGH)
  {
    Serial.println("Gas threshold exceeded\n");
    String a ="1";
    return a;
  }
  else{
    String a ="0";
    return a; 
  }
}

2.4 sending data

The "/ temperature" can be defined according to yourself. Here are three pages corresponding to different data.

  server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readTemp().c_str());
  });
  server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readHumi().c_str());
  });
 server.on("/Air", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readAir().c_str());
  });
  

2.5 to obtain the ip address of the server, we can view it through the serial port assistant or open the mobile authentication of the computer

  Serial.print("IP Address:");
  Serial.println(WiFi.localIP());
3. Problems encountered

When burning the code, a library problem was reported, saying it was an IPAddress problem. There was no problem using the ESP32 development board, but an error was reported using the ESP32-C3 development board. At the beginning, I also searched online for a long time, but I still didn't find the relevant solutions. Later, I searched one by one according to the wrong address. At the point where I found the wrong address, I deleted 0U and it can be used.

4. Server complete code
// Import required libraries
#include "WiFi.h"
#include "FS.h"
#include "ESPAsyncWebServer.h"
#include "DHT.h"
#include <Wire.h>

#define DHTPIN 7  
#define DHTTYPE DHT11   // DHT 11
DHT dht(DHTPIN, DHTTYPE);

const char* ssid = "3671";
const char* password = "05210835";
const int airtwo =6;

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

String readTemp() {
  return String(dht.readTemperature());
}

String readHumi() {
  return String(dht.readHumidity());
}
String readAir() {
  return String(Air());
}
String Air(){

  int newStat1 = digitalRead(airtwo);
   if(newStat1==HIGH)
  {
    Serial.println("Gas threshold exceeded\n");
    String a ="1";
    return a;
  }
  else{
    String a ="0";
    return a;
   
  }
}
void setup(){
  pinMode(airtwo,INPUT);  //The air alarm is an input
  // Serial port for debugging purposes
  Serial.begin(115200);
  dht.begin();
  WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print("Connecting----\n");       
    }

    Serial.print("WIFI Connected\n");
    Serial.print("IP Address:");
    Serial.println(WiFi.localIP());
  
  server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readTemp().c_str());
  });
  server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readHumi().c_str());
  });
 server.on("/Air", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readAir().c_str());
  });
  
  // Start server
  server.begin();
}

void setupWifi(){
  WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print("Connecting----\n");
        
    }

    Serial.print("WIFI Connected\n");
    Serial.print(WiFi.localIP());
}
void loop(){
float h = dht.readHumidity(); 
float t = dht.readTemperature(); 
float f = dht.readTemperature(true);
String a =Air();
int newStat1 = digitalRead(airtwo);
  if(newStat1==HIGH)
  {
    Serial.println("Gas threshold exceeded\n");

  }
  else{  
  }
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!\n"));
    return;
  }
  //Let's view the data through the serial port
  Serial.print(F("Air: "));   
  Serial.print(a);
  Serial.print(F("  Humidity: "));        
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("*C  \n "));
 
  if (!WiFi.isConnected()) //First, check whether WIFI is still connected
  {
    setupWifi();
  }
}

2, Client

The last blog has talked about the use of OLED, so I'll mention it here. Talk about how the client obtains the data of the server.

1. Call header file

#include <WiFi.h>
#include <HTTPClient.h>
/* Using 0.96 inch OLED screen needs to use the header file */
#include "SSD1306Wire.h"

2. ip address of the server

Corresponding to the data stored on the three pages of the server

//ip address of the server
const char* serverNameTemp = "http://192.168.137.82/temperature";  
const char* serverNameHumi = "http://192.168.137.82/humidity";
const char* serverNameAir = "http://192.168.137.82/Air";

3. Get http page function

String httpGETRequest(const char* serverName) {
  HTTPClient http;
    
  // Your IP address with path or Domain name with URL path 
  http.begin(serverName);
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  
  String payload = "--"; 
  
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

4. The acquired data is displayed on the display

   String temperature = httpGETRequest(serverNameTemp);
   String Humidity = httpGETRequest(serverNameHumi);
   String Airpost  =httpGETRequest(serverNameAir);
   unsigned long currentMillis = millis();
  if(Airpost =="0"){
    oled.drawString(0,40, "Air:warning"); // A value of 0 indicates warning
    }
  else
  {
     oled.drawString(0,40, "Air:normal"); // A value of 1 indicates normal
  }
   /* 1. Display letters */
  oled.setFont(ArialMT_Plain_16);       // Set font
  oled.drawString(0,0, "Temp:" +temperature+"C"); // Writes the letters to be displayed to the cache
  oled.drawString(0,20, "Humidity:"+Humidity+"%"); // Writes the letters to be displayed to the cache
  oled.display();                       // Display the text in the cache on the screen
  delay(10000);
  oled.clear(); 
  oled.display();         // Clear screen

5. Client complete code

#include <WiFi.h>
#include <HTTPClient.h>
/* This header file is required to use 0.96 inch OLED screen */
#include "SSD1306Wire.h"
const char* ssid = "3671";
const char* password = "05210835";
//Your IP address or domain name with URL path
//ip address of the server
const char* serverNameTemp = "http://192.168.137.82/temperature";
const char* serverNameHumi = "http://192.168.137.82/humidity";
const char* serverNameAir = "http://192.168.137.82/Air";



/* Set information about oled screen */
const int I2C_ADDR = 0x3c;              // I2c address of oled screen
#define SDA_ Pin 5 / / SDA pin, default gpio4(D2)
#define SCL_ Pin 4 / / SCL pin, default gpio5(D1)

/* To create a new oled screen object, you need to enter IIC address, SDA and SCL pin number */
SSD1306Wire oled(I2C_ADDR, SDA_PIN, SCL_PIN);

unsigned long previousMillis = 0;
const long interval = 5000; 


void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
      
   /* 2. oled Screen initialization */
  oled.init();
  oled.flipScreenVertically();          // Set screen flip
  oled.setContrast(255);                // Set screen brightness
  drawRect();                           // Test screen display
  oled.clear(); oled.display();         // Clear screen
}

void drawRect(void) {
  for (int16_t i=0; i<oled.getHeight()/2; i+=2) {
    oled.drawRect(i, i, oled.getWidth()-2*i, oled.getHeight()-2*i);
    oled.display();
    delay(50);
  }
}

void loop() {
   String temperature = httpGETRequest(serverNameTemp);
   String Humidity = httpGETRequest(serverNameHumi);
   String Airpost  =httpGETRequest(serverNameAir);
   unsigned long currentMillis = millis();
  if(Airpost =="0"){
    oled.drawString(0,40, "Air:warning"); // Writes the letters to be displayed to the cache
    }
  else
  {
     oled.drawString(0,40, "Air:normal"); // Writes the letters to be displayed to the cache
  }
   /* 1. Display letters */
  oled.setFont(ArialMT_Plain_16);       // Set font
  oled.drawString(0,0, "Temp:" +temperature+"C"); // Writes the letters to be displayed to the cache
  oled.drawString(0,20, "Humidity:"+Humidity+"%"); // Writes the letters to be displayed to the cache
  oled.display();                       // Display the text in the cache on the screen
  delay(10000);
  oled.clear(); 
  oled.display();         // Clear screen

  if(currentMillis - previousMillis >= interval) {
     // Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED ){ 
      Serial.println("Temperature: " + temperature + " *C - Humidity: " + Humidity+ "%" );
     
      // save the last HTTP GET Request
      previousMillis = currentMillis;
    }
    else {
      Serial.println("WiFi Disconnected");
    }
  }
}

String httpGETRequest(const char* serverName) {
  HTTPClient http;
    
  // Your IP address with path or Domain name with URL path 
  http.begin(serverName);
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  
  String payload = "--"; 
  
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

3, Effect display



Write here, finally go home on holiday, and continue to work hard in the New Year!!!
Winter is gone and the stars are bright. Everything is going well in the new year

Keywords: C IoT stm32

Added by jharbin on Tue, 25 Jan 2022 22:26:55 +0200