Reputation: 451
while (1)
{
c = getchar();
switch(state)
{
case 0:
if((GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) == Bit_SET))
{
state=1;
}
if ( c=='p')
{
state = 2;
}
break;
case 1 :
if((GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) != Bit_SET))
{
state = 0;
}
break;
case 2:
iprintf("%s",led_name_arr[i]);
if (c=='r')
{
state=0;
}
break;
}
}
I want to print the printf and then reach state2 .. how can this be achieved .below is what i have tried and where i am stuck .
psuedocode:
if ( c==P)
{
printf(" hi");
state 2;
}
** in this case the printf statement does not get executed ** or
case 2:
iprintf("%s",led_name_arr[i]);
if (c=='r')
{
state=0;
}
break;
** in this case the printf statement keeps printing in a loop **
i dont want the while loop to stop , in a continuous loop i want case 0 keeps working , but when it get the input p .. it pauses and executes the printf ... and waits till it gets a r to resume case 0 .... Thus the program never halts but waits to either get "P" or "R" to execute each case... I hope i make sense
Any help will be appreciated .
Upvotes: 1
Views: 813
Reputation: 1281
Because you are not breaking the while(1) loop. Use one more break for while loop.
Upvotes: 0
Reputation: 171
i am not sure what you are asking but i m pretty sure what you want in case 2 is something like this:
case 2:
iprintf("%s",led_name_arr[i]);
while(c!='r')
{
c = getchar();
}
state=0;
break;
Upvotes: 1
Reputation: 3911
Your break
s are breaking out of the switch ... case
not the while
. You'll need to use some kind of boolean flag to break out of the outer loop, e.g.:
bool someflag = true;
while(someflag){
switch(something){
case a:
someflag = false; // set the flag so we break out of the loop
break; // break out of the switch-case so we don't enter case b
case b:
// do something else
break;
}
}
-------- EDIT, because I misunderstood the question ------------
I think you need an extra state in your logic, right now (ignoring state 1), you have two states:
Wait for a p
, when you get one, goto 2.
printf
for each character until you get an r
, then goto 1
What you want is:
Wait for a p
, when you get one, goto 2.
Do a printf
, then goto 3.
Wait for an r
, when you get one, goto 1.
Upvotes: 3
Reputation: 13300
well, initialize state to 0
compile and run the program
first time enter p // here state =2
then enter r // here state = 0
....continue in a loop due to while(1)
Upvotes: 0
Reputation: 6846
You've created an infinite loop with the while (1) statement that has no possible exit. The break statements within the switch apply to the switch statement, not the while loop. You need another break statement outside the switch.
Upvotes: 1