Search code examples
cstringcharserial-portvxworks

Serial Port Reading VxWorks String conversion gibberish


I am reading in data from a serial port to a ueipac 600-1G linux box with VxWorks installed. I am supposed to read in string data. However when I send in a string, for testing i used "this is a test" my log file reads "this is a test¤ -p". I altered my code to read the hex values and got " 74 68 69 73 20 69 73 20 61 20 74 65 73 74 0a" which when plugged into a hex converter reads "this is a test".

I have done multiple test with different input strings and the gibberish changes each time. I am wondering how to filter out this gibberish I think it has something to do with how C is converting hex data to string, with the 0a character.

my code is as follows

void readandlog_serial(){

// read error throwing int
int n=0;
int bytes_counter=0;
int bytes=256; /*num of bytes to read at a time*/
int i=0; /* for the for loop*/
int bytes_written=0; 
// hold the file descriptor
int fd=0;
/* dev name from iosDevShow output */ 
char dev_name[] = "/tyCo/0"; 
/* buffer to receive read */ 
char re[bytes]; 
/* length of string to read */ 
int re_len = bytes; 
/* open the device for reading. */ 
fd = open( "/tyCo/0", O_RDWR, 0);
outputfile=fopen ("LOGFILE.txt","a"); /* open output file*/
//check for open error
if(fd<0)
    fprintf("outputfile","%s","\nerror opening file\n");
//while(n = read( fd, re, re_len)>0)
    //bytes_counter=bytes_counter+n;

n = read( fd, re, re_len); /* read */
if(n<0)
    fprintf("outputfile","%s","\nerror reading file\n");
close( fd ); /* close */ 
for (i=0; i<n;++i){
    bytes_written=bytes_written+( fprintf(outputfile," %02x", re[i]) );
}
//fprintf(outputfile,"%c",'\n');
// pull only string data
//bytes_written=fprintf(outputfile,"%s",re);   *****************************

fclose(outputfile);
printf("readandlog executed number of bytes written: %d\n",bytes_written);
}

the for loop is commented out for the string reading builds, and the fprintf line with the astriks next to it is commented out for the hex data read builds.


Solution

  • Hex output is correct, your string + 0A newline.

    You using uninitialised variable re, printing HEX was correct, beacause you print HEX value for n char, but fprintf(outputfile,"%s",re); will print null terminated string (your string + OA + garbage + \0).

    change char re[bytes]; to char re[bytes] = {}; or use function bzero/memset set buffer to 0.