Coding Comparing with 2 Potentiometer

So I've decided to go back to coding, and needed a refresher on an old topic.

Similar to a DC motor positioning controller, I worked on a code that will compare the value of 2 pots and show the results with an RBG led;

Blue is when pot 1 < pot 2
Green is when pot 1 = pot 2
Red is when pot 1 > pot 2

However, I can't graph it on the plotter without the two values going back and forth from one reading to the other, and it keeps skipping one of the if statements when running.

Any suggestions? Code source below:

</>
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
pinMode(2, OUTPUT);
pinMode(4, OUTPUT);
pinMode(7, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
int sensorCompair = analogRead(A5);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
int voltage0 = sensorValue * (5.0 / 1023.0);
int voltage1 = sensorCompair * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage0);
Serial.println(voltage1);

if (voltage0 < voltage1) {
digitalWrite(4, HIGH);
delay(50);
digitalWrite(4, LOW);
} else if (voltage0 > voltage1) {
digitalWrite(2, HIGH);
delay(50);
digitalWrite(2, LOW);
} else {
digitalWrite(7, HIGH);
delay(50);
digitalWrite(7, LOW);
}
}
</>

Forget all the voltage comparisons. Just use the raw values from the A/D converter. That is ALL you need to care about.

Click once on the code tags symbol and place the code there. Don't type the characters.

Don't expect them to get equal. Use a deadband like 510 - 514, or wider, as "equal".

That's a very small (unstable) window.
Shouldn't you widen that a bit.

Try this (untested).
Leo..

int difference;

void setup() {
  pinMode(2, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(7, OUTPUT);
}

void loop() {
  difference = analogRead(A0) - analogRead(A5);
  if (difference > 1) {
    digitalWrite(4, HIGH);
    digitalWrite(2, LOW);
    digitalWrite(7, LOW);
  }
  else if (difference < -1) {
    digitalWrite(2, HIGH);
    digitalWrite(4, LOW);
    digitalWrite(7, LOW);
  }
  else {
    digitalWrite(7, HIGH);
    digitalWrite(2, LOW);
    digitalWrite(4, LOW);
  }
}

The Serial Plotter will show a separate line for each value ON THE SAME LINE OF TEXT. Since you are displaying one value on each line of text the plotter thinks they are all the same value to be plotted. You want:

Serial.print(voltage0);
Serial.print(' '); // Space separator
Serial.println(voltage1);

Another trick is to plot constants at the same time, like 5 and 0 (or 1023 and 0,) so the scale doesn't keep readjusting alla time.

a7

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.