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

如何将模拟读数转换为时间以实现LED每分钟8-40次闪烁?

Hey there! Let's fix this so your LED blinks exactly between 8 and 40 times per minute based on the sensor input. The key issue with your current code is that the delay values you're using are way too small—right now, even the longest delay (80ms) would give you ~375 blinks per minute, which is way faster than your target. Let's break down the math and adjust the code properly.

Step 1: Calculate the Correct Delay Times

First, let's define what a "blink" means: one full cycle of LED on + LED off.

  • For 8 blinks per minute: Each full cycle (on + off) takes 60,000ms / 8 = 7500ms. If we split this equally between on and off, each delay is 7500ms / 2 = 3750ms.
  • For 40 blinks per minute: Each full cycle takes 60,000ms /40 =1500ms, so each delay is 1500ms /2=750ms.

So we need to map your analog sensor input (0-1023) to delay values ranging from 3750ms (slowest blink rate) to 750ms (fastest blink rate).

Step 2: Revised Code

Here's the adjusted code that implements this logic:

int led = 13;
int pinAnalogo = A0;
int analogo;
unsigned long delayTime; // Use unsigned long to avoid overflow with larger values

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  analogo = analogRead(pinAnalogo);
  
  // Map analog input (0-1023) to delay time (3750ms to 750ms)
  // Higher sensor value → shorter delay → faster blink rate (40 BPM)
  // Lower sensor value → longer delay → slower blink rate (8 BPM)
  delayTime = map(analogo, 0, 1023, 3750, 750);
  
  digitalWrite(led, HIGH);
  delay(delayTime);
  digitalWrite(led, LOW);
  delay(delayTime);
}

Key Notes:

  • Using unsigned long: Since delay times can be up to 3750ms, which fits in an int, but using unsigned long is safer to avoid potential overflow if you adjust values later.
  • Reverse Mapping: We're mapping from 3750 to 750 instead of the other way around because higher sensor values should correspond to faster blinks (shorter delays). If you want the opposite (higher sensor = slower blinks), swap the last two numbers in the map function: map(analogo, 0, 1023, 750, 3750).
  • Unequal On/Off Times: If you don't want equal on/off durations, split the cycle time differently. For example, if you want the LED on for 1/3 the cycle and off for 2/3, calculate onTime = (60000 / BPM) * 1/3 and offTime = (60000 / BPM)*2/3, then adjust the map function for each value separately.

Testing the Code

To verify, you can test with fixed values first:

  • Set delayTime = 3750 → LED blinks exactly 8 times per minute.
  • Set delayTime =750 → LED blinks exactly 40 times per minute.

That should do it! Let me know if you need further tweaks.

内容的提问来源于stack exchange,提问作者Ignacio Nieto Larrain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 11:07:36