Search code examples
cstreamraspberry-piserial-portwiringpi

Process incoming serial stream without LF CR


The code below processes incoming RS232 serial data 1 character at a time and works fine.

However the incoming serial feed in my use case does not contain any CR or LF characters which make further delimiting/processing to a piped program difficult. The end delimiter is always a ! exclamation character instead of a CR or LF. e.g. 123456!abcdef!qwerty!

Is there a way to modify the code below to substitute the ! character to a CR (carriage return)? For example, is the incoming string is 123456abcdef! then the program should replace the ! with a CR so it outputs 123456abcdef<carriage return>

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <wiringSerial.h>

int main ()

  for (;;)
  {
    putchar (serialGetchar (fd)) ;
    fflush (stdout) ;
  }
}

Solution

  • You can do it in the same single char basis as:

    #include <stdio.h>
    #include <string.h>
    #include <errno.h>
    #include <wiringSerial.h>
    
    int main ()
    
      for (;;)
      {
        char c = serialGetchar (fd);
        putchar (c == '!' ? '\r' : c) ;
        fflush (stdout) ;
      }
    }
    

    Normally it is used new line with carriage return, in that case would be:

    #include <stdio.h>
    #include <string.h>
    #include <errno.h>
    #include <wiringSerial.h>
    
    int main ()
    
      for (;;)
      {
        char c = serialGetchar (fd);
        if (c == '!')
        {
            putchar ('\r') ;
            putchar ('\n') ;
        }
        else
        {
            putchar (c) ;
        }
        fflush (stdout) ;
      }
    }