Question about If-ElseIF versus Switch-Case.
I have the code that follows setup to read in three digital inputs (set as global unsigned chars) in a user function and then it runs through the possibilities and returns an unsigned char back to the main routine. First, am I setting the conditions correctly in the If’s? Also, would this be better set as a switch case??? And if so, then how to implement the multiple variables in the Switch statement.
Also, all variables are default to = 1 so that the last result is true and kicks out of the user function back to main.
Code:
#include "Main.h"
unsigned char Func_DataPort ( void )
{ // runs the routine to retrieve data port assignments and create a variable with the results
unsigned char Port_Set = 1;
CHAR_PG2 = GetDigitalInput ( 1 ) ;
CHAR_PG1 = GetDigitalInput ( 2 ) ;
CHAR_PG0 = GetDigitalInput ( 3 ) ;
if ( CHAR_PG2 == 0 & CHAR_PG1 == 1 & CHAR_PG0 == 1 )
{
Port_Set = 2 ;
return Port_Set ;
}
else if ( CHAR_PG2 == 1 & CHAR_PG1 == 1 & CHAR_PG0 == 0 )
{
Port_Set = 3 ;
return Port_Set ;
}
else if ( CHAR_PG2 == 1 & CHAR_PG1 == 0 & CHAR_PG0 == 1 )
{
Port_Set = 4 ;
return Port_Set ;
}
else if ( CHAR_PG2 == 1 & CHAR_PG1 == 0 & CHAR_PG0 == 0 )
{
Port_Set = 5 ;
return Port_Set ;
}
else if ( CHAR_PG2 == 0 & CHAR_PG1 == 1 & CHAR_PG0 == 0 )
{
Port_Set = 6 ;
return Port_Set ;
}
else if ( CHAR_PG2 == 0 & CHAR_PG1 == 0 & CHAR_PG0 == 1 )
{
Port_Set = 7 ;
return Port_Set ;
}
else if ( CHAR_PG2 == 0 & CHAR_PG1 == 0 & CHAR_PG0 == 0 )
{
Port_Set = 8 ;
return Port_Set ;
}
else if ( CHAR_PG2 == 1 & CHAR_PG1 == 1 & CHAR_PG0 == 1 )
{
Port_Set = 1 ;
return Port_Set ;
}
}
Thanks for your answers.