/* Wokwi 仿真代码
目标:读取 DHT22 -> 显示 OLED -> 串口模拟发送 WiFi 数据
*/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
// --- 硬件定义 ---
#define DHTPIN D2 // 传感器连在 PA1
#define DHTTYPE DHT22 // Wokwi 里用 DHT22
DHT dht(DHTPIN, DHTTYPE);
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
// 1. 初始化串口 (模拟连接 ESP8266)
// 115200 是 ESP8266 的默认波特率
Serial.begin(115200);
// 2. 初始化传感器
dht.begin();
// 3. 初始化 OLED
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("OLED failed"));
for(;;);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
}
void loop() {
// --- 步骤 1: 读取数据 ---
float t = dht.readTemperature();
float h = dht.readHumidity();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// --- 步骤 2: OLED 本地显示 ---
display.clearDisplay();
display.setCursor(0,0);
display.println("Smart Warehouse");
display.setCursor(0,20);
display.print("Temp: "); display.print(t); display.println(" C");
display.setCursor(0,35);
display.print("Humi: "); display.print(h); display.println(" %");
display.display(); // 刷新屏幕
// --- 步骤 3: 模拟无线发送 (重点!) ---
// 这里我们模拟发送 AT 指令给 ESP8266
sendDataToWifi(t, h);
// --- 步骤 4: 延时 2 秒 ---
delay(2000);
}
// --- 模拟无线发送功能的函数 ---
// void sendDataToWifi(float temp, float humi) {
// // 假设我们已经连接上了服务器,现在只做透传发送
// // 1. 准备要发送的数据包 (JSON 格式)
// // 格式: {"temp":25.5, "humi":60.2}
// char dataBuffer[50];
// sprintf(dataBuffer, "{\"temp\":%.1f, \"humi\":%.1f}", temp, humi);
// // 2. 发送 AT 指令告诉模块我要发多长的数据
// int len = strlen(dataBuffer);
// Serial.print("AT+CIPSEND=");
// Serial.println(len);
// // 仿真延时,等待模块回复 ">"
// delay(100);
// // 3. 发送真正的数据
// Serial.println(dataBuffer);
// }
// --- 优化后的发送函数 (不使用 %f) ---
void sendDataToWifi(float temp, float humi) {
char dataBuffer[50];
// 手动拆分温度的小数和整数部分
int temp_int = (int)temp; // 取整数,比如 25
int temp_dec = (int)((temp - temp_int) * 10); // 取一位小数,比如 5
// 手动拆分湿度
int humi_int = (int)humi;
int humi_dec = (int)((humi - humi_int) * 10);
// 【关键】这里用 %d (整数) 代替 %f (浮点数)
// 也就是把 "25.5" 拼成了 "25" + "." + "5"
sprintf(dataBuffer, "{\"temp\":%d.%d, \"humi\":%d.%d}", temp_int, temp_dec, humi_int, humi_dec);
// 下面的逻辑不变
int len = strlen(dataBuffer);
Serial.print("AT+CIPSEND=");
Serial.println(len);
delay(100);
Serial.println(dataBuffer);
}Loading
st-nucleo-c031c6
st-nucleo-c031c6
Loading
ssd1306
ssd1306