0

I would like to read an analog value using analogRead, save this value and compare it to an analogRead value 5 ms later. How would this code look? Because giving a variable the value of analogRead(A0); would mean it is constantly changing, making it impossible to compare two values.

thanks in advance

2 Answers 2

2

The simplest and crudest method:

int val1 = analogRead(A0);
delay(5);
int val2 = analogRead(A0);

if (val2 > val1) {
    // It went up (for example).
}
0

You just need to copy the value into another before you overwrite it with analogRead(A0) and then compare those two variables.

int prev_value = 0;
int value = 0;
unsigned long prev_read_time = 0;

void setup() {
    prev_read_time = millis();
    value = analogRead(A0);
}

void loop() {
    if (millis() - prev_read_time > 5) {
        prev_read_time = millis();
        prev_value = value;
        value = analogRead(A0);
        if (prev_value != value) {
            // value changed
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.