10 years, 3 months ago.

Seriel receive not working

Hello, I want to receive some data of 30byte approx. I am following this code please can anyone tell me where i am wrong?

  1. include "mbed.h"

Serial pc(USBTX, USBRX); tx, rx Serial device(NC, p10); tx, rx

int main() { int i,o; char c; char stru[40]; pc.baud(9600); pc.format(8,SerialBase::None,1); while(1) {

o=device.readable(); if(o==1) { pc.printf ("started"); for(i=0;i<40;i++){

c=device.getc(); if(c=='\n') break; stru[i]=c;} pc.printf("%s",stru); }

} }

1 Answer

10 years, 3 months ago.

Hi Deepak,

There could be a few things wrong with the code there, but one thing i noticed is that you're calling Serial::getc() 40 times while only making sure that something is in the buffer once.

To fix it, change this...

...
while(1) 
{
     o=device.readable();
     if(o==1) 
     {
          pc.printf ("started");
          for(i=0;i<40;i++)
          {
               c=device.getc(); 
               if(c=='\n') 
                    break; 
               stru[i]=c;
          } 
          pc.printf("%s",stru); 
     }
...

into this...

...
int i = 0;
...
while(1) 
{
     if( device.readable() && (i <= 39) && (i >= 0) ) // Check if something is in the input buffer
     {
          if( i == 0 )
               pc.printf ("\r\n started");

          c = device.getc(); // Copy and take one char out of the buffer
          if( (c == '\n') || ( i >= 40  ) // Prevent overflow
               break;
          stru[i++] = c; // Copy the char to the array
     }
     if( i >= 40 )
     {
          pc.printf( "\r\n %s", stru ); 
          i = -1; // Recieve and print 40 chars only once
     }
}
...

Otherwise you end up trying to read 40 chars while the buffer most likely has only one char (the mbed instruction clock is much faster than the serial baud rate).

Hope that helps :)

Accepted Answer

getc() blocks though until there is a character available to read. So that shouldn't be an issue (not that blocking is ideal, which your code prevents).

@Deepak, try changing your serial terminal settings. IIRC teraterm doesn't send \n by default but \r. You can in the settings changes transmit to LF, that might solve it.

posted by Erik - 20 Jan 2014