0

我编写了以下程序来使 ESP32 Huzzah 板上的板载 LED 闪烁。我已经将超声波距离传感器连接到板上,如果一个物体距离传感器超过 30 厘米(或者传感器正在输出垃圾值),那么我希望 LED 以 1 Hz 的频率闪烁。否则 LED 应以 2 Hz 的频率闪烁。

该代码使用 5 个连续样本计算平均距离,并计算这些样本的方差。如果平均距离小于 30 cm,方差小于 2 cm^2,则 PWM 频率应为 2 Hz,否则应为 1 Hz。方差有助于过滤掉垃圾读数。

数学部分工作正常,我可以打印出平均距离和方差,但 LED 不闪烁。当我停止 REPL 时(我使用的是 Thonny Python IDE),频率是基于在停止 REPL 之前为真的任何条件。

在不停止 REPL 的情况下,我需要什么来改变使 LED 闪烁(并根据距离改变频率)?

任何帮助将不胜感激。

# Import required modules.
from machine import Pin, PWM
import time
from hcsr04 import HCSR04

# Define hardware output pin.
# Pin 13 is the onboard LED.
# Initialize distance sensor, the trigger pin is 26 and the echo pin is 25.

frequency = 1
led_board = Pin(13, Pin.OUT)
led_pwm = PWM(led_board, freq = frequency, duty = 512)
sensor = HCSR04(trigger_pin = 26, echo_pin = 25)
temp_0 = [0, 0, 0, 0, 0]

# Main never ending loop which makes the onboard LED blink at 1 Hz (ON for 500 milliseconds...
# ... and OFF for 500 milliseconds) if an object is more than 30 cm away from the sensor,...
# ...otherwise the LED blinks at 2 Hz (ON for 250 milliseconds and OFF for 250 milliseconds).
while True:
    for i in range(5):
        temp_0[i] = sensor.distance_cm()
        
    mean_distance = sum(temp_0)/5
    temp_1 = [j - mean_distance for j in temp_0]
    temp_2 = [k**2 for k in temp_1]
    var_distance = sum(temp_2)/5
    
    if mean_distance < 30 and var_distance < 2:
        frequency = 2
    else:
        frequency = 1
        
    print(mean_distance, ' ', var_distance)
    
    led_pwm.freq(frequency)
4

1 回答 1

0

据我所知,调用PWM.freq(frequency)实际上会重置 LEDC 计时器,因此通过在每个循环中调用它,您不会允许控制器运行并闪烁 LED。如果频率发生变化,请尝试仅调用该方法:

# Check if the frequency has changed, if so, set the new frequency of the LED
if (led_pwm.freq() != frequency):
  led_pwm.freq(frequency)
于 2020-07-04T23:18:42.753 回答