简体   繁体   中英

How to measure voltage over 10 seconds with Arduino?

I am building a program that measure the voltage of a component (photoswitch). When the potential is under 5 V, the lamp will turn on.

But my problem is, I want the Arduino to turn on the lamp, if the voltage has been under 5 V for 10 seconds or more. For example, if the voltage level is under 5 V for 8 seconds and then it changes to over 5 V again, the lamp should not turn on.

Here is my code so far:

int Pin = 2;
const float baselineVoltage = 5.0;

void setup() {
    Serial.begin(9600);
    pinMode(Pin,OUTPUT);
}

void loop() {
    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1023.0);
    Serial.println(voltage);
    if(voltage < baselineVoltage){
        digitalWrite(2,HIGH);
   }
delay(10);
}

I believe something like this addresses your 10 second delay issue. If you want the same 10 second delay to turn it off, you will need to do something similar.

int Pin = 2;
const float baselineVoltage = 5.0;
int belowBaselineVoltage = false;
unsigned long turnOnAt;
const unsigned long turnOnDelay = 10 * 1000;

void setup() {
    Serial.begin(9600);
    pinMode(Pin, OUTPUT);
}

void loop() {
    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1023.0);
    Serial.println(voltage);

    if (voltage < baselineVoltage)
    {
        if (belowBaselineVoltage == true)
        {
            if (millis() >= turnOnAt)
            {
                digitalWrite(2, HIGH);
            }
        }
        else
        {
            belowBaselineVoltage = true;
            turnOnAt = millis() + turnOnDelay;
        }
    }
    else
    {
        belowBaselineVoltage = false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM