使用 PWM 使 ESP32 Huzzah 上的 LED 闪烁 (MicroPython)

Using PWM to Blink LED on ESP32 Huzzah (MicroPython)

我编写了以下程序来使 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)

据我所知,调用 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)