# Using the difference between two potentiometers

Hi all,

I’m attempting to find if the difference between two potentiometers is increasing or decreasing. To do this I’m using two potentiometers and two LED’s. For some reason the red LED is flickering while the green one stays off. Any help would be greatly appreciated, thank you for your time.

``````int oldvalue;

void setup() {
Serial.begin(9600);
int oldvalue = 0;

pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
}

void loop() {

int val = (analogRead(A0) - analogRead(A1));  // take the difference between A0 and A1:

if(val > oldvalue)
{
digitalWrite(3,HIGH);// the difference between the two POTS is increasing so turn on the RED LED
}
else
{
digitalWrite(3,LOW);// turn off the RED LED
}

if (val < oldvalue)
{
digitalWrite(4, HIGH);// the difference between the two POTS is increasing so turn on the RED LED
}
else
{
digitalWrite(4, LOW);// turn off the GREEN LED
}

// get current value into oldvalue for next comparison
oldvalue = val;

}
``````
``````    digitalWrite(4, HIGH);// the difference between the two POTS is increasing so turn on the RED LED
}
else
{
digitalWrite(4, LOW);// turn off the GREEN LED
``````

Are both the red and green LED on pin 4?

I've been staring at your code for a while and still can't make sense of it. Wouldn't this be simpler?

``````  if(val > oldvalue)
{
digitalWrite (3, HIGH);
digitalWrite (4, LOW);
}
else
{
digitalWrite (3, LOW);
digitalWrite (4, HIGH);
}
``````

But you’re NOT basing your LED behaviour on the difference of the pots.

It’s based on the difference of the difference since the last itteration of the loop. So if you’re really fast on the pot it’ll turn on a LED for about 20 MICRO seconds.

On the next itteration of the loop, the difference between the two pots will be the same as it was last time, so any leds that are currently alight will be immediately turned off again.

The red and green LED's are on different pins.

Your code would be the one to use, but I need to use two potentiometers for this project, unfortunately.

Your code is much simpler, thanks Nick. I'm still running into the problem where the red LED stays on the entire time.

Wave222222:
Your code is much simpler, thanks Nick. I’m still running into the problem where the red LED stays on the entire time.

That’ll be because val is never bigger than oldvalue for more than the odd itteration of the loop here and there as you move it. As soon as you stop moving them, oldvalue will always be the same as val.

KenF is right. You need to test the difference between the readings:

``````if (analogRead(A0) < analogRead(A1)) ...
``````