If value drop do something....


A have a little problem with my code…

Basically a want to do something if my analog value drops… Let say


If analogRead > 1000
do something

If analogRead “goes down”
do something else

if analogRead < 700
do something else

The value can easily drop directly from 1023 to 500. So somehow i need detect that the value has gone from a higher level towards a lower…

Hope you know what i mean… Can it be done?


You'll be happy to know that yes, it can be done.
Usually, it is best to keep a short history of previous values.

Can it be done?

Yes of course.
Put the analog read into a variable then use that variable to compare your latest reading. By subtracting one from the other you get an idea of how much it has changed and you can use the if statement to control what you do.

The hardest part is deciding exactly what you want to do.


Yeah, i was on to something like that..

But it wont work...

I'll have to try some more :slight_smile:

I'm quite sure it will work.


Thanks guys!

You may post the code so people with the same problem can see how you solved it ,


Here we go!

#include <LiquidCrystal.h>

int x;
int lastVal = 0;               //set initial value to 0

LiquidCrystal lcd(11, 10, 5, 4, 3, 2);  // initialize the library with the numbers of the interface pins

void setup()

    lcd.begin(20, 4);            // set up the LCD's number of columns and rows: 
  Serial.begin( 9600 );          // initialize the serial communications:

void loop()
  x = analogRead(A0);
  if (x > 1000)
      lcd.setCursor(0, 0);

  else if (x < lastVal)
      lcd.setCursor(0, 1);
   lcd.print("goes down");
   else if (x < 700)
      lcd.setCursor(0, 2);

  lastVal = x;                // 'save' the value of x to next iteration

Just a little test code i made…


You know the IDE can do code layout by pressing CTRL-T ?

Damn! You just made my life easier.. 8)

You are awesome.. :astonished:

int x;
int lastVal = 0;               //set initial value to 0

You know, most people in a situation like this would use names like currVal and prevVal to hold the current value and the previous value. But, if these names work for you, fine.

Tell me, though, how x and lastVal will relate to each other a month from now when you look at this code.

Yeah i know :blush: ... hehe.

But as i mentioned, it was just made for testing... 8)