首页 > 解决方案 > 将模拟读数转换为时间范围

问题描述

我正在尝试使带有模拟传感器的 LED 每分钟闪烁 8 到 40 次

我已经尝试过这段代码,但我意识到我必须将 valorSensor 转换为时间。如何做到这一点?

int led = 13;
int pinAnalogo = A0;
int analogo;
int valorSensor;

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

void loop() {
  analogo = analogRead(pinAnalogo);
  valorSensor = map(analogo, 0, 1023, 4, 80);
  digitalWrite(led, HIGH);   
  delay(valorSensor);                       
  digitalWrite(led, LOW);    
  delay(valorSensor);                      

}

标签: timearduino

解决方案


这里的问题不在于代码,而在于生物学。要看到闪烁(而不仅仅是闪烁,您需要 250 毫秒及以上的时间)24 帧/秒被视为运动,因此要获得“闪烁”,您可以从 4 帧/秒(=250 毫秒)开始所以我的建议是无延迟闪烁作为功能和用于测试的调整参数 (blinkSpeedMultiplyer)

 /* Blink without Delay as function
    Turns on and off a light emitting diode (LED) connected to a digital pin,
  without using the delay() function. This means that other code can run at the
  same time without being interrupted by the LED code.*/

// constants won't change. Used here to set a pin number:
const int blinkSpeedMultiplyer = 50; // very low
const int ledPin = 13;
const int pinAnalogo = A0;
// Variables will change:
// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long startTime = millis();        // will store last time LED was updated
unsigned long blinkTime;           // interval at which to blink (milliseconds)
int analogo;
int valorSensor;
int ledState = LOW;             // ledState used to set the LED

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

void loop() {
  analogo = analogRead(pinAnalogo);
  valorSensor = map(analogo, 0, 1023, 4, 80);
  blinkLed(valorSensor); // call the function
}

// Function to blink without blocking delay
void blinkLed(int inValue) {
  blinkTime = blinkSpeedMultiplyer * inValue;
  if (millis() - startTime >= blinkTime) {
    // save the last time you blinked the LED
    startTime = millis();

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

推荐阅读