I'm trying to use the 'switch case' to choose between cases with my accelerometer:
switch(axis) {
case 'X':
code = 0x06; //Return register for X data
return code;
Serial.println("Found X");
break;
case 'Y':
code = 0x07;
return code;
Serial.println("Found Y");
break;
case 'Z':
code = 0x08;
Serial.println("Found Z");
return code;
}
the serial println's are there for debugging, I never see any output so it's never getting to any of the cases. I'm pretty sure it's because it's not correctly comparing the axis being passed in to the character in each case.
Doesn't the "return code;" line cause the program to exit the subroutine, so it never reaches the println command? Try putting the println before the return.
Can you use characters as case variables though? I have the code working using integers but i really want to use characters as it makes the code so much clearer.
IE this works:
switch(axis) {
case 1:
code = 0x06; //Set register for X data
break;
case 2:
code = 0x07;
break;
case 3:
code = 0x08;
break;
}
This code works. Hopefully it'll help you see what you need to do.
void setup() // run once, when the sketch starts
{
Serial.begin(9600); // set up Serial library at 9600 bps
}
void loop() // run over and over again
{
int value;
value = getAccelData('X'); // Notice that 'X' is in single quotes
Serial.println(value);
value = getAccelData('Y'); // Also, case is important
Serial.println(value);
value = getAccelData('Z');
Serial.println(value);
value = getAccelData('@');
Serial.println(value);
}
int getAccelData(char axis) // Notice that axis is defined as type char
{
int code;
switch(axis) {
case 'X': // Notice 'X' is in single quotes
Serial.println("Found X");
code = 0x06; //Return register for X data
return code;
break;
case 'Y':
Serial.println("Found Y");
code = 0x07;
return code;
break;
case 'Z':
Serial.println("Found Z");
code = 0x08;
return code;
break;
default:
Serial.println("default");
return 0;
}
}
AWOL, I agree your code will work, and it's clever.
However, "clever" code is usually harder to maintain in the future, either for others or yourself in a few months. It doesn't adapt well to new requirements. And it can pin the compiler down, even if the compiler could have done it in fewer machine operations on a particular processor.
Write the intent clearly, even if it takes a little more room in the editor window. Let the C compiler figure out the best way of squeezing the actual logic into machine language.