树莓派4:LED预期闪烁16次,实际仅闪烁8次问题排查
问题:LED闪烁次数与预期不符(实际8次vs预期16次)
观察LED闪烁次数可知,实际仅闪烁8次,与预期的16次不符。预期16次的计算依据为:每0.25秒闪烁一次,持续4秒(4÷0.25=16)。请帮忙排查问题所在,我的计算假设是否存在错误?
我的代码:
// include onoff to interact with RPi board GPIO pins var gpio = require("onoff").Gpio; // specify GPIO27 pin as output and we connected and LED+ resistor to this pin already var ledPin = new gpio(27,'out'); // set blinking time for 250 ms; Executing following line alone makes LED flash continuously var blinkInterval = setInterval(blinkLedFunction,250) // Now define the blinkLedFunction var ledBlink = 0; function blinkLedFunction(){ // Start blinking LED // Check if LED presently set to OFF or 0 if (ledPin.readSync()===0){ // Then, set this to ON ledBlink++; console.log("LED blink "+ledBlink) ledPin.writeSync(1); // else, set it off }else {ledPin.writeSync(0);} } // set turn off time of LED blinking for 5s var stopBlinking = setTimeout(stopBlinkingFunction,4000); // Now define the stopBlinkingFunction function stopBlinkingFunction(){ // stop the function clearInterval(blinkInterval); // set ledPin to low ledPin.writeSync(0); // Unexport GPIO to free resources; I still don't know yet. Maybe, we freeing the pin, in this case 27, for use elsewhere ledPin.unexport(); }
问题分析与解决:
你的计算假设存在核心错误:对「一次闪烁」的定义混淆了。
代码逻辑里的闪烁计数规则:
你只在LED从灭转亮的时候(ledPin.readSync()===0时)给ledBlink加1,也就是每两次setInterval触发(亮250ms + 灭250ms)才会被计数为一次“闪烁”。时间计算偏差:
4秒内setInterval总共会触发4000ms / 250ms = 16次,其中只有8次是LED从灭转亮的操作,所以最终计数是8次,这和实际的完整闪烁次数完全一致。
调整方案(二选一):
- 如果想要16次完整的亮灭循环:
把setInterval的间隔改成125ms,这样每250ms完成一次闪烁(亮125ms+灭125ms),4秒内刚好完成16次完整闪烁。 - 如果想要LED点亮16次(即
ledBlink计数到16):
把setTimeout的延迟时间改成7750ms(因为第16次点亮是第31次setInterval触发,31*250=7750),或者直接在blinkLedFunction里判断ledBlink === 16时主动停止定时器。
内容的提问来源于stack exchange,提问作者Mainland
相关产品推荐
相关产品推荐

