printf() before break

09 Apr 2012

In the following code printf() before break is not executed ; An explanation please Thank you Markos Thanos

 main() { 
    
    while(1) { 
        kbrd_char=pc.getc();
        
        if ( kbrd_char=='a') { printf(" Hallow ");
                             };
        if ( kbrd_char=='b') { printf(" Bye "); break;
                             };                       

              }; // while (1) 
}// main


09 Apr 2012

This happens because your program finishes immediately after the break and the magic interface chip doesnt have time to complete the printf . You should use a while(1) as final instruction.

<<code>>

.......

}; while (1)

while(1) {};

} main <</code>>

09 Apr 2012

Alternatively, you could just wait a few seconds before calling the "break". EX. put the statement wait(3); after printf.

09 Apr 2012

Add fflush(stdout); before you exit your program

#include <mbed.h>

Serial pc(USBTX, USBRX);

main() { 
    
    while(1) { 
        char kbrd_char=pc.getc();
        
        if ( kbrd_char=='a') { printf(" Hallow ");
                             };
        if ( kbrd_char=='b') { printf(" Bye "); break;
                             };                       

              }; // while (1) 
              
    fflush(stdout);
    
}// main
09 Apr 2012

You aren't seeing the printf("Bye") output because stdout is line buffered so it won't actually be sent out the serial port until a newline is sent or you do something with stdin (which is what calling pc.getc() on the next loop iteration after printf("Hallow") is equivalent to.) However, if you use pc.printf() instead of printf() then you switch to using unbuffered output and you won't see the above problem.

#include <mbed.h>

Serial pc(USBTX, USBRX);

main() 
{
    while(1) 
    { 
        int kbrd_char=pc.getc();
        
        if (kbrd_char=='a') 
        { 
            pc.printf(" Hallow ");
        }
        else if (kbrd_char=='b') 
        { 
            pc.printf(" Bye "); 
            break;
        }                       
    }
}

Hope that helps,

Adam

10 Apr 2012

Thank you Adam pc.printf() works fine. Markos