ESP32教程:人体移动监测与报警+远程监控

📌 前言

先前我们有使用AHT20温湿度传感器制作一个环境监测站,有朋友问是否可以实现人体感应与报警功能?这是一个非常好的思路!

今天,我们就用 ESP32-C6 开发板,配合PIR人体红外传感器 和 无源蜂鸣器实现一个功能更完整的智能环境监测站。


🎯 项目功能一览

功能

实现方式

🌡️ 温湿度监测

AHT20 传感器,精度高,响应快

🚶 人体移动检测

PIR 红外传感器,检测距离 3-7 米

🔊 声音报警

无源蜂鸣器,PWM 控制

🌐 远程监控

内置 Web 服务器,手机/电脑随时查看

📊 数据统计

移动触发次数统计,一键重置

🔔 实时推送

网页端报警状态实时刷新(2秒/次)


🧩 硬件清单

名称

型号

数量

备注

主控板

ESP32-C6 主板

1

支持 Arduino

温湿度传感器

AHT20

1

I2C 接口

人体红外传感器

AM312

1

无源蜂鸣器

5V 无源蜂鸣器

1

PWM 控制

连接线

杜邦线

若干

电源

USB-C 数据线

1

给 ESP32 供电



🔌 硬件接线(核心!)

引脚连接对照表

模块

引脚

连接到 ESP32-C6

AHT20

VCC

3.3V

GND

GND

SDA

GPIO22

SCL

GPIO23

PIR 传感器模块

VCC

3.3V

GND

GND

OUT

GPIO0

无源蜂鸣器模块

VCC

5V

GND

GND

I/O

GPIO1


💻 软件准备与库安装

按照方法参考如下:

ESP32新手教程

智芯致远,公众号:智芯致远ESP32新手教程:用LCD1602显示AHT20温湿度数据


📝 完整代码

以下为完整代码,只需修改 WiFi 名称和密码即可使用。

#include <WiFi.h>#include <WebServer.h>#include <ArduinoJson.h>#include <Wire.h>#include <Adafruit_AHTX0.h>
// ---------- I2C 引脚 ----------#define MY_I2C_SDA 22#define MY_I2C_SCL 23
// ---------- PIR 和蜂鸣器引脚 ----------#define PIR_PIN     0   // PIR 传感器输出#define BUZZER_PIN  1   // 蜂鸣器引脚
// ---------- PWM 配置 ----------#define BUZZER_FREQ     1000  // 基础频率(Hz)#define BUZZER_RES      8     // 分辨率(8位,占空比 0~255)
// ---------- 网络配置 ----------const char* ssid = "your_wifi";const char* password = "your_password";
// ---------- 硬件对象 ----------Adafruit_AHTX0 aht;float temperature = 0.0;float humidity = 0.0;
// ---------- 报警状态 ----------volatile bool motionDetected = false;volatile unsigned int pirCount = 0;     unsigned long lastBuzzerTime = 0;const unsigned long BUZZER_INTERVAL = 2000; 

// ---------- Web服务器 ----------WebServer server(80);
const char index_html[] PROGMEM = R"rawliteral(<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>ESP32-C6 环境监测站</title><style>body { font-family: Arial, sans-serif; text-align: center; margin: 0; padding: 20px; background: #f0f4f8; }.container { max-width: 400px; margin: auto; background: white; padding: 30px; border-radius: 15px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }h2 { color: #333; margin-bottom: 20px; }.data-box { background: #e3f2fd; margin: 15px 0; padding: 15px; border-radius: 10px; }.data-label { font-size: 1.2em; color: #555; }.data-value { font-size: 3em; font-weight: bold; margin: 10px 0; }.unit { font-size: 1.2rem; color: #777; }.alarm-box { background: #fff3cd; margin: 15px 0; padding: 15px; border-radius: 10px; border-left: 6px solid #ffc107; }.alarm-safe { background: #d4edda; border-left-color: #28a745; }.alarm-danger { background: #f8d7da; border-left-color: #dc3545; }.alarm-label { font-size: 1.2em; font-weight: bold; }.count-box { background: #e8eaf6; margin: 15px 0; padding: 15px; border-radius: 10px; border-left: 6px solid #5c6bc0; }.count-value { font-size: 2.5em; font-weight: bold; color: #3f51b5; margin: 10px 0; }.footer { margin-top: 30px; font-size: 0.8em; color: #888; }.btn-reset { background: #5c6bc0; color: white; border: none; padding: 10px 30px; border-radius: 8px; font-size: 1em; cursor: pointer; margin-top: 10px; }.btn-reset:hover { background: #3f51b5; }</style><script>function fetchData() {  fetch('/data')    .then(response => response.json())    .then(data => {      document.getElementById('temp').innerText = data.temperature.toFixed(1);      document.getElementById('humi').innerText = data.humidity.toFixed(1);      document.getElementById('pirCount').innerText = data.count;
      const alarmDiv = document.getElementById('alarmStatus');      const alarmText = document.getElementById('alarmText');      if (data.motion) {        alarmDiv.className = 'alarm-box alarm-danger';        alarmText.innerText = '⚠️ 检测到移动!';      } else {        alarmDiv.className = 'alarm-box alarm-safe';        alarmText.innerText = '✅ 安全,无移动';      }    })    .catch(error => console.error('Error:', error));}// 重置计数function resetCount() {  fetch('/reset', { method: 'POST' })    .then(response => response.json())    .then(data => {      if (data.success) {        document.getElementById('pirCount').innerText = '0';      }    })    .catch(error => console.error('Error:', error));}setInterval(fetchData, 3000);fetchData();</script></head><body><div class="container">  <h2>🏠 智能环境监测站</h2>  <div class="data-box">    <div class="data-label">🌡️ 温度</div>    <div class="data-value"><span id="temp">--</span><span class="unit"> °C</span></div>  </div>  <div class="data-box">    <div class="data-label">💧 湿度</div>    <div class="data-value"><span id="humi">--</span><span class="unit"> %</span></div>  </div>  <div id="alarmStatus" class="alarm-box alarm-safe">    <div class="data-label">🚨 人体移动报警(当前状态)</div>    <div class="data-value" style="font-size:1.5em;" id="alarmText">✅ 安全,无移动</div>  </div>  <div class="count-box">    <div class="data-label">📊 移动触发次数</div>    <div class="count-value"><span id="pirCount">0</span></div>    <button class="btn-reset" onclick="resetCount()">🔄 重置计数</button>  </div>  <div class="footer">数据每2秒自动更新 | ESP32-C6 + AHT20 + PIR</div></div></body></html>)rawliteral";
// ---------- 处理根请求 ----------void handleRoot() {  server.send(200, "text/html", index_html);}
// ---------- 处理 /data ----------void handleData() {  String jsonData;  StaticJsonDocument<256> doc;  doc["temperature"] = temperature;  doc["humidity"] = humidity;  doc["motion"] = motionDetected;  doc["count"] = pirCount;     serializeJson(doc, jsonData);  server.send(200, "application/json", jsonData);}
// ---------- 处理 /reset(重置计数) ----------void handleReset() {  pirCount = 0;  StaticJsonDocument<64> doc;  doc["success"] = true;  String jsonData;  serializeJson(doc, jsonData);  server.send(200, "application/json", jsonData);  Serial.println("🔄 计数已重置");}
// ---------- 蜂鸣器发声函数(PWM控制) ----------void triggerBuzzer() {  // unsigned long now = millis();  // if (now - lastBuzzerTime < BUZZER_INTERVAL) return;  // lastBuzzerTime = now;
  ledcWriteTone(BUZZER_PIN, 3000);   // 启动PWM,频率3000Hz  delay(1000);  ledcWriteTone(BUZZER_PIN, 0);      // 关闭PWM(静音)}
// ---------- setup ----------void setup() {  Serial.begin(115200);  Serial.println("\n正在启动...");
  // --- I2C ---  Wire.begin(MY_I2C_SDA, MY_I2C_SCL);
  // --- AHT20 ---  if (!aht.begin()) {    Serial.println("❌ 传感器初始化失败!");    while (1) delay(10);  }  Serial.println("✅ AHT20 已就绪");
  // --- PIR 引脚 ---  pinMode(PIR_PIN, INPUT);
  ledcAttach(BUZZER_PIN, BUZZER_FREQ, BUZZER_RES);  ledcWriteTone(BUZZER_PIN, 0);   // 初始静音  Serial.println("✅ 蜂鸣器 PWM 已初始化");

  // --- WiFi ---  WiFi.mode(WIFI_STA);  WiFi.begin(ssid, password);  Serial.print("WiFi 连接中");  while (WiFi.status() != WL_CONNECTED) {    delay(500);    Serial.print(".");  }  Serial.println("\n✅ WiFi 已连接");  Serial.print("👉 http://");  Serial.println(WiFi.localIP());


  // --- Web Server ---  server.on("/", handleRoot);  server.on("/data", handleData);  server.on("/reset", HTTP_POST, handleReset);    server.begin();  Serial.println("✅ Web服务器启动");
  // --- PIR 预热 ---  Serial.println("⏳ PIR 预热中...");  for (int i = 3; i > 0; i--) {    Serial.print(i);    Serial.print(" ");    delay(1000);  }  Serial.println("\n✅ PIR 已就绪");}
// ---------- loop ----------void loop() {  server.handleClient();
  //--- 温湿度 ---  sensors_event_t humidity_event, temp_event;  aht.getEvent(&humidity_event, &temp_event);  temperature = temp_event.temperature;  humidity = humidity_event.relative_humidity;

  // --- PIR 上升沿检测 ---  static int lastPirState = LOW;  int pirValue = digitalRead(PIR_PIN);
  if (pirValue == HIGH && lastPirState == LOW) {    // 上升沿:检测到移动    motionDetected = true;    pirCount++;   // 计数 +1    triggerBuzzer();    Serial.println("🚨 移动检测到(上升沿)");  } else if (pirValue == LOW) {    motionDetected = false;  }
  lastPirState = pirValue;
  // --- 串口调试 ---  Serial.print("温度: ");  Serial.print(temperature);  Serial.print(" °C, 湿度: ");  Serial.print(humidity);  Serial.print(" %, 移动: ");  Serial.println(motionDetected ? "有" : "无");
  delay(1000);}

🚀 上传与运行

  1. 将代码复制到 Arduino IDE,修改 WiFi 名称和密码。

  2. 连接 ESP32-C6 到电脑,选择正确的开发板和端口。

  3. 点击 上传 按钮(→)。

  4. 打开 串口监视器(波特率 115200),等待启动完成。

  5. 串口会打印出 IP 地址,例如 http://192.168.1.13。

  6. 在手机或电脑浏览器(同一 WiFi)输入该地址,即可看到监测页面。

🎉 效果展示

手机端或电脑端都可以访问IP地址相应网址http://192.168.1.13


🎉 总结

    现在,你已经拥有了一套功能完整的智能环境监测系统!无论是监测温湿度,还是当作简易安防报警器,都非常实用!

    如果你需要远在千里之外使用手机进行监测,请访问如下教程。

    Negro外网穿透教程

    智芯致远,公众号:智芯致远想让你制作的ESP32 webserver温湿度监测站,能被远在千里之外的你随时访问吗?


      #ESP32教程#PIR人体感应#buzzer蜂鸣器#

      发表评论