Potentiometer coding, switch gives wrong values.

Hi guys

I’m a college student and just started to learn arduino coding. The program worked fine without a SWITCH (connect pin A2 directly to GND.) But now that I implemented the SWITCH coding, it malfunctions.

Here is the code:

float voltage;
float sum;
float average;
const byte PINNUMBER = A1;
const byte SWITCH = A2;
boolean valuePinA2;
const int TIMER = 1000;
byte counter;
String message;

float voltageInput( byte pinLocal){
float readValue = analogRead(pinLocal);
float voltageLocal = readValue * 5.0 / 1023.0;
return voltageLocal;

void setup() {
// put your setup code here, to run once:
counter = 0;
sum = 0.0;

void loop() {
// put your main code here, to run repeatedly:
valuePinA2 = digitalRead(SWITCH);

if (valuePinA2 = HIGH){
voltage = voltageInput(PINNUMBER);
sum = sum + voltage;
average = sum / counter;
message = “The voltage is " + String(voltage) + " V. The average is " + String(average) + " V.”;

Anyone that can help a brother out?

Why do you have the switch connected to an analog pin?

Turning on the internal pullup resistor may be interfering with the ADC. If you must use an analog pin to read the switch, use an external pullup resistor.

You also define


but you read that pin:

voltage = voltageInput(PINNUMBER);

float voltageInput( byte pinLocal){
  float readValue = analogRead(pinLocal);
if (valuePinA2 = HIGH){

in an if statement use == not just =

Thank you all, I changed everything and it works now :slight_smile: