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

ESP32 Station模式下无法读取心率传感器数据的解决请求

ESP32 Station模式下连接Wi-Fi后无法读取心率传感器数据的问题解决

我使用ESP32 DevKit C板读取心率传感器数据并存储到MySQL数据库,但在Station模式(Wi-Fi已连接)下无法读取数据,请求协助解决。修复后需实现持续监测心率并将读数存入MySQL数据库。

#include <WiFi.h>
#include <HTTPClient.h>

#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.   

//  Variables
const int PulseWire = 2;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 12
const int LED = LED_BUILTIN;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
                               // Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
                               // Otherwise leave the default "550" value. 
int myBPM =0;                               
                               
PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"


String URL = "http://192.168.1.11/sensors_project/insert_data_h.php";

const char* ssid = "";
const char* password = "";


void setup() {   

  Serial.begin(115200);          // For Serial Monitor

  connectWiFi();  //Connect to the network

  // Configure the PulseSensor object, by assigning our variables to it. 
  pulseSensor.analogInput(PulseWire);   
  pulseSensor.blinkOnPulse(LED);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);   

  // Double-check the "pulseSensor" object was created and "began" seeing a signal. 
   if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.  
  }
}



void loop() {

 
  if(WiFi.status() != WL_CONNECTED) {
    connectWiFi();
  }

  if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
    myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
                                                  // "myBPM" hold this BPM value now. 
    Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
    Serial.print("BPM: ");                        // Print phrase "BPM: " 
    Serial.println(myBPM);                        // Print the value inside of myBPM. 
  }

  String postData = "heartbeat=" + String(myBPM);
  
  HTTPClient http;
  http.begin(URL);
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  
  int httpCode = http.POST(postData);
  String payload = "";
  if(httpCode > 0) {
    // file found at server
    if(httpCode == HTTP_CODE_OK) {
      String payload = http.getString();
      Serial.println(payload);
    } else {
      // HTTP header has been send and Server response header has been handled
      Serial.printf("[HTTP] GET... code: %d\n", httpCode);
    }
  } else {
    Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
  }
  
  http.end();  //Close connection

  delay(200);                    // considered best practice in a simple sketch.

}

void connectWiFi() {
  WiFi.mode(WIFI_OFF);
  delay(1000);
  //This line hides the viewing of ESP as wifi hotspot
  WiFi.mode(WIFI_STA);
  
  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi");
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
    
  Serial.print("connected to : "); Serial.println(ssid);
  Serial.print("IP address: "); Serial.println(WiFi.localIP());
}

  

问题分析

从代码和场景来看,核心问题集中在资源抢占和初始化顺序上:

  1. Wi-Fi启动干扰ADC读取:ESP32的Wi-Fi模块启动时会占用大量系统资源,甚至干扰模拟输入(ADC)的采样,而心率传感器依赖ADC获取信号,先连Wi-Fi再初始化传感器会导致信号读取异常。
  2. HTTP请求过于频繁:每200ms就发起一次HTTP请求,持续占用CPU资源,导致心率传感器的信号检测逻辑被抢占,无法及时处理心跳信号。
  3. 阈值未适配硬件:默认的Threshold=550可能不符合你的实际硬件环境,导致有效心跳信号被过滤。

解决方案

1. 调整初始化顺序

先初始化心率传感器,再连接Wi-Fi,避免Wi-Fi启动对ADC的干扰:

void setup() {   
  Serial.begin(115200);          // For Serial Monitor

  // 先初始化心率传感器
  pulseSensor.analogInput(PulseWire);   
  pulseSensor.blinkOnPulse(LED);       
  pulseSensor.setThreshold(Threshold);   

  if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  
  }

  connectWiFi();  // 再连接Wi-Fi
}

2. 优化HTTP请求逻辑

仅在检测到新心跳时发送数据,避免频繁请求占用资源:

void loop() {
  if(WiFi.status() != WL_CONNECTED) {
    connectWiFi();
  }

  bool beatDetected = pulseSensor.sawStartOfBeat();
  if (beatDetected) {            
    myBPM = pulseSensor.getBeatsPerMinute();  
    Serial.println("♥  A HeartBeat Happened ! ");
    Serial.print("BPM: ");                        
    Serial.println(myBPM);                        

    // 仅在检测到心跳时发送数据
    String postData = "heartbeat=" + String(myBPM);
    
    HTTPClient http;
    http.begin(URL);
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    int httpCode = http.POST(postData);
    if(httpCode > 0) {
      if(httpCode == HTTP_CODE_OK) {
        String payload = http.getString();
        Serial.println(payload);
      } else {
        Serial.printf("[HTTP] POST... code: %d\n", httpCode);
      }
    } else {
      Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }
    
    http.end();  //Close connection
  }

  delay(20);  // 缩短延迟,提高传感器检测灵敏度
}

3. 校准传感器阈值

断开Wi-Fi,单独运行心率传感器测试代码,观察Serial Monitor中的信号峰值,将Threshold调整为峰值的一半左右,确保能准确识别心跳。

4. 检查硬件连接

确认心率传感器的紫线确实连接到ESP32的GPIO2(模拟输入引脚),电源和地线连接牢固,避免接触不良导致信号丢失。

内容的提问来源于stack exchange,提问作者Issoufou Sofiane

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:09:55