一、使用的硬件:
1.ESP32
2.SHT40温湿度传感器
3.OLED显示屏
4.风扇(PWM调速)
5.自己打一个IIC总线的电路板
6.杜邦线(越多越好
二、对应管脚
模块 | 管脚 | ESP32对应管脚 |
风扇 | S | D16 |
SHT40和oled | SCL | D22 |
SDA | D21 |
三、软件代码
#include <Arduino.h>
#include "Adafruit_SHT4x.h"
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
// 创建OLED对象
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
const int fanPin = 16; //D16 for fan
const int freq = 5000;
const int fanChannel = 0;
const int resolution = 8;
int dutyCycle = 200;
Adafruit_SHT4x sht40 = Adafruit_SHT4x();
//配置Web Server
const char* ssid = "****"; //wifi名称
const char* password = "****"; //wifi密码
WiFiServer server(80); // Set web server port number to 80
String header; // Variable to store the HTTP request
unsigned long currentTime = millis(); // Current time
unsigned long previousTime = 0; // Previous time
const long timeoutTime = 2000; // Define timeout time in milliseconds (example: 2000ms = 2s)
// 读取温湿度,串口显示
void read_Humidity(float * tempHum){
sensors_event_t humidity, temp;
uint32_t timestamp = millis();
sht40.getEvent(&humidity, &temp); // populate temp and humidity objects with fresh data
timestamp = millis() - timestamp;
tempHum[0] = temp.temperature;
tempHum[1] = humidity.relative_humidity;
Serial.print("Temperature: "); Serial.print(temp.temperature); Serial.println(" 'C");
Serial.print("Humidity: "); Serial.print(humidity.relative_humidity); Serial.println(" % rH");
}
void OLED_Humidity(float Humidity){
display.clearDisplay(); // Clear display buffer
int16_t i;
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(10, 10);
// Display static text
display.print("Humidity: ");
display.print(Humidity);
display.print(" % rH");
display.display();
}
void setup() {
//配置串口
Serial.begin(115200);
while(!Serial){
delay(10);
}
//初始化SHT40传感器
Serial.println("SHT4x test");
if(!sht40.begin()){
Serial.println("Couln't find sht40");
while(1)delay(10);
}
Serial.println("Finded sht40 sensor");
Serial.print("sht40 address: 0x");
Serial.println(sht40.readSerial(), HEX);
sht40.setPrecision(SHT4X_HIGH_PRECISION);
switch(sht40.getPrecision()){
case SHT4X_HIGH_PRECISION:
Serial.println("High precision");
break;
case SHT4X_MED_PRECISION:
Serial.println("Medium precision");
break;
case SHT4X_LOW_PRECISION:
Serial.println("Low precision");
break;
}
//初始化风扇 PWM
//配置pwm的工作参数
ledcSetup(fanChannel, freq, resolution);
//连接PWM通道与IO口
ledcAttachPin(fanPin, fanChannel);
//初始化OLED
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
float tempHum[2];
read_Humidity(tempHum);
float Temperature = tempHum[0];
float Humidity = tempHum[1];
OLED_Humidity(Humidity);
// 开始时风扇的速度始终
ledcWrite(fanChannel, dutyCycle);
// 风扇转速根据湿度来改变
if (Humidity >= 60)
{
dutyCycle++;
if(dutyCycle > 225){
dutyCycle = 225;
}
} else {
dutyCycle--;
if(dutyCycle < 50){
dutyCycle = 50;
}
}
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the table
client.println("<style>body { text-align: center; font-family: \"Trebuchet MS\", Arial;}");
client.println("table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }");
client.println("th { padding: 12px; background-color: #0043af; color: white; }");
client.println("tr { border: 1px solid #ddd; padding: 12px; }");
client.println("tr:hover { background-color: #bcbcbc; }");
client.println("td { border: none; padding: 12px; }");
client.println(".sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px; }");
// Web Page Heading
client.println("</style></head><body><h1>ESP32 with SHT40</h1>");
client.println("<table><tr><th>MEASUREMENT</th><th>VALUE</th></tr>");
client.println("<tr><td>Humidity</td><td><span class=\"sensor\">");
client.println(Humidity);
client.println(" %</span></td></tr>");
client.println("<tr><td>Temperature</td><td><span class=\"sensor\">");
client.println(Temperature);
client.println(" 'C</span></td></tr>");
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
运行效果:
web端显示:
视频展示:
IMG_5693