If...Else not working as expected? variable value conversion

Im trying to write a sketch that will read a 4-bit switch input, then depending on what the switch value is, change another variable value and print that on the serial monitor.

The switch reading code and the serial code are working just find (not my own code!), but my use of If...Else If to do the conversion doesnt work - it just sets the variable 'MHZ' to 1 (first If...) regardless of what the read value is,

In my mind this should work but clearly it doesnt, either ive done something very silly or im just not getting how to do this, any thoughts?

// Test sketch for reading 4-bit switch, converting and sending to serial monitor
// Set up initial variables
byte dip1pins[] = {2,3,4,5};

void setup() {
  // set up serial comms
  Serial.begin(9600);
  // set pins to inputs
  for (int cnt1 = 0; cnt1 < sizeof(dip1pins); cnt1++)
  {
    pinMode(dip1pins[cnt1], INPUT_PULLUP);
  }

}

void loop() {
  // read pins, store each pin in assigned bit
  byte val = 0;
  byte MHZ = 0;
  for (int cnt1 = 0; cnt1 < sizeof(dip1pins); cnt1++)
  {
    val |= (!digitalRead(dip1pins[cnt1])) << cnt1;
  }
Serial.print("Value = ");
Serial.println(val);
if (val=8)
{
  MHZ=1;
}
else if (val=1)
{
  MHZ=2;
}
else if (val=9)
{
  MHZ=3;
}
else if (val=5)
{
  MHZ=4;
}
else if (val=13)
{
  MHZ=5;
}
else if (val=3)
{
  MHZ=6;
}
else if (val=11)
{
  MHZ=7;
}
else if (val=7)
{
  MHZ=8;
}
else if (val=15)
{
  MHZ=9;
}
else
{
  MHZ=0;
}
delay(1000);
Serial.print("MHZ = ");
Serial.println(MHZ);
}

Your variable dip1pins is only ever 2, 3, 4, or 5. Index values 0, 1, 2, 3.
It's never equal to 8.
Sizeof() made certain of that in your for loop.

Dan95:
Your variable dip1pins is only ever 2, 3, 4, or 5. Index values 0, 1, 2, 3.
It's never equal to 8.
Sizeof() made certain of that in your for loop.

No, dip1pins is a byte derived from reading the four input pins (actually it will only ever be a nibble) and can be anything from 0 to 15, depending how I set the switches. That part of the code works fine.

Ah! Never mind! Silly mistake!

used = instead of the correct ==

working as expected now and giving me converted values of 0 to 9 (equivalent to the markings on the rotary switch im mimicing)

Hi,

if (val=15)

ALL your if statements should be like this below;

if (val==15)

single = is assigning 15 to val, not doing a comparison.
https://www.arduino.cc/en/Reference/If

Tom.. :slight_smile:

cheers Tom,

I'd been puzzling over it for around half an hour before thinking i'd ask, then right after posting, i had a cup of tea and realised what i'd done wrong!

Dont recall it being this way in Spectrum BASIC back in the '80's!

Hi,
Yes it happens.....
Its amazing what sitting back and having a cuppa will do, stimulates "ze gray cells"

Tom... :slight_smile: