Assignment requires 4 int input to select different mode of LED blinking
- On
- Off
- Blinking
- Reduced duty cycle
Would apperciate advice on a better implementation of control structure.
Current implmentation
int main()
{
wiringPiSetup();
pinMode (23, OUTPUT) ;
pinMode (26, OUTPUT) ;
int select;
printf("\nKey in number: ");
scanf("%d", &select);
if (select == 1)
{
turnOn();
main();
}
else if (select == 0)
{
turnOff();
main();
}
else if (select == 2)
{
blinking();
main();
}
else if (select == 3)
{
pattern();
main();
}
return 0;
}
CodePudding user response:
Calling main everytime is unnecessary if you want to loop back you can just use a while(true) it will stay there forever(you can change this by putting a condition). And using a chain of if else looks bad. Switch case is much better (its faster).
int main() {
wiringPiSetup();
pinMode (23, OUTPUT) ;
pinMode (26, OUTPUT) ;
while(true) {
int select;
printf("\nKey in number: ");
scanf("%d", &select);
switch(select) {
case 0:
turnOff();
break;
case 1:
turnOn();
break;
case 2:
blinking();
break;
case 3:
pattern();
break;
}
}
return 0;
}
CodePudding user response:
void (* const mode[])(void) =
{
turnOff, turnOn, blinking, pattern
};
for (;;)
{
unsigned int select;
printf("\nKey in number: ");
fflush(stdout);
if ((scanf("%u", &select) == 1) &&
(select < sizeof(mode)/sizeof(*mode)))
{
mode[select]();
}
}