Hi guys
I'm trying to do a switch case from the digitalread of various pins, for them to be taken as a binary number and that number would be the case in the switch to execute a function. But I'm not quiet sure on how to do it, would someone guide me into the correct way to declare it and to compile it?
for example:
int E0 = A0;
int E1 = A1;
int E2 = A2;
int E3 = A3;
void setup()
{
lcd.being(16,2);
pinMode(A0, INPUT);
pinMode(A1, INPUT);
pinMode(A2, INPUT);
pinMode(A3, INPUT);
}
void loop()
{
int inputs=(digitalRead(A3), digitalRead(A2), digitalRead(A1), digitalRead(A0)):
switch(inputs)
{
case0:
lcd.print("hello");
case 1:
lcd.print("Case1");
case 2:
lcd.print("case2");
case 3:
lcd.print("case3");
}
So, if my arduino is reading on A1 a HIGH input but on A0,A2 and A3 is LOW, it should be something like this (0,0,1,0), that's 2 on decimal so it will execute case#2.
If it reads on A3 a HIGH input and LOW input on the others. it will be (1,0,0,0) executing case#8.
I hope I explain myself well, I'm not an advance programmer neither fluent on C/C++.
While that code looks fine and will work, I would use bit shifting ( << shift left ) and the inclusive or operation | to join them together:-
// int inputs=(digitalRead(A3), digitalRead(A2), digitalRead(A1), digitalRead(A0)):
// would be written as:-
int inputs=((digitalRead(A3)<<3) | (digitalRead(A2)<<2) | (digitalRead(A1)<<1) | digitalRead(A0)):
Note that your case statement would use the numbers formed by this operation. So the inputs variable would be a number between 0 and 15 depending on what combination of ones and zeros there are in the number. So your case statement would have 16 cases in it depending on what buttons you pressed. If you want to only look at single button presses then your code for the case statement would be:-
case0: // this is the case where nothing is pressed
lcd.print("hello");
case 1: // button only A0 pressed
lcd.print("A0 pressed");
case 2: // button only A1 pressed
lcd.print("A1 pressed");
case 4: // button only A2 pressed
lcd.print("A2 pressed");
case 8: // button only A3 pressed
lcd.print("A3 pressed");