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

ESP32使用FreeRTOS运行HC-SR04时读取数据异常求助

问题:FreeRTOS任务中HC-SR04测距偶尔出现数据跳变,loop中运行正常

我正在学习FreeRTOS,尝试把HC-SR04超声波测距的示例代码整合为一个独立任务,仅将测距结果打印到串口,但偶尔会出现数据读取错误:当被测物体静止时,测距值会从8跳变至25(正常范围应该在10-12之间)。但如果把这段代码放在loop()循环里运行,就能正常工作。

相关代码如下:

//Use only one core for complexity purposes
#if CONFIG_FREERTOS_UNICORE
  static const BaseType_t app_cpu = 0;
#else
  static const BaseType_t app_cpu = 1;
#endif

// defines pins numbers
static const uint8_t trigPin = 2;
static const uint8_t echoPin = 4;

void task_distance(void *parameter)
{
   while(1){
     long duration;
      int distance;

        // Clears the trigPin
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);

      // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      // Reads the echoPin, returns the sound wave travel time in microseconds
      duration = pulseIn(echoPin, HIGH);

      // Calculating the distance
      distance = duration * 0.034 / 2;

      // Prints the distance on the Serial Monitor
      Serial.print("Distance: ");
      Serial.println(distance);

       vTaskDelay(100 / portTICK_PERIOD_MS );
   }
    
}

void setup() {

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication

  xTaskCreatePinnedToCore(task_distance, "Senzor distanta", 2048, NULL, 1, NULL, app_cpu);
}
void loop() {
}

(配有测距数据异常的截图:[测距数据跳变异常截图])

内容的提问来源于stack exchange,提问作者Stefan Mihai Lorincz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:35:19