Sam
Sam

Reputation: 17

can we use two break statements in a single while(1) loop?

Following is my program. I am trying to read characters at different baud rate and if no character is received within 10 seconds I want to break out of the loop and similarily if any character other than alphabets is received, I again want to break out of the loop? How can I do that. Please guide me.

char read()
{
    while(1)
    {
        delay_ms(10000);
        break;

        if((uart_RxChar() >= 65 && uart_RxChar() <= 90) || (uart_RxChar() >= 97 && uart_RxChar() >= 122))
        {
            uart_TxChar('k');
            Glow_GreenLED();
        }
        else 
        {
            Glow_RedLED();
            break;
        }
    }
}

Upvotes: 1

Views: 170

Answers (2)

Badda
Badda

Reputation: 1369

char read()
{
   while(1)
   {
       delay_ms(10000); // Stops the program
       break; // Then leaves

       if( (uart_RxChar() >= 65 && uart_RxChar() <= 90) || (uart_RxChar() >= 97 && uart_RxChar() >= 122))
       {

           uart_TxChar('k');
           Glow_GreenLED();
       }
       else 
       {
           Glow_RedLED();
           break;
       }
    }
 }

What you are trying to do won't succeed. You have to know that delays don't work that way. When your program will reach to the delay, it will stop everything - inputs too - during the delay. Meaning that whatever you do, it will wait then break.
The only way to achieve what you want to do using delays is to use threads, and have one thread waiting and mesuring the time, and an other thread waiting for an input. A way to do this without threads is using a timer and use the value of the timer as a condition to break. May be this link could help. Nevertheless, it is perfectly possible to have as much break conditions as you want :

if (CONDITION_1) 
    break;
else if (CONDITION_2) 
{ 
      printf("something");
      break;
}
else if (CONDITION_3) 
{
      someFunction();
      break;
}
else 
      break;

Upvotes: 3

CIsForCookies
CIsForCookies

Reputation: 12817

The first break; you get to, will break out of the loop, meaning,

   while(1)
   {
    delay_ms(10000);
     break;

is the same as

delay_ms(10000);

Your second break; as well as your whole if-else is "cut out" since the loop will break before

Upvotes: 2

Related Questions