LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   serial port problem in C (https://www.linuxquestions.org/questions/programming-9/serial-port-problem-in-c-819755/)

knobby67 07-14-2010 06:37 AM

serial port problem in C
 
hi All,
I've written some code which reads in the serial port, it all appeared to work well except I've reached a problem when I send 0xff my code ignores this as the read function sees -1 as a nothing on the port. My code is as follows

unsigned char RxChar(COMPORT *port)
{
unsigned char readletter[1];
pthread_mutex_lock( &rxmutex );

if(read(port->id, readletter, 1)==-1) /* comms port has nothing*/
{
pthread_mutex_unlock( &rxmutex);
return(0xff);
}
else
{
pthread_mutex_unlock( &rxmutex);
return(readletter[0]);

}

pthread_mutex_unlock( &rxmutex);
return(-1);
}


Is there a way I can check to see if there is anything in the serial buffer without pulling it out using read?

Normally I would call the fucntion with something like

rx = RxChar(&Comms_1)'
if( rx ! = 0xff)
{
....
}

how can I make it something like
if(RxBufferEmpry(&Coms_1)
{

.....

}
So basically test to see if the comms port buffer is empty without pulling the character is in it? thanks :D

dwhitney67 07-14-2010 06:54 AM

I would suggest that you do not read the comm port unless you know for a fact that there is data to be read. You can verify that data is available using select().

As for your function RxChar(), it has a declaration/definition issue. You have indicated that it will return an unsigned char, yet in one place you return a -1. This is equivalent to 255 decimal, or 0xFF. If 0xFF is considered a valid return value, then you are going to have to redefine the function to return a wider set of data.

I would suggest that you define RxChar() to return an int value, which if needed, can be cast to an unsigned char when you have determined that you have valid data. For example:
Code:

#include <stdio.h>

int function()
{
  int rtn = -1;

  if (1)
  {
      rtn = 0xFF;
  }

  return rtn;
}

int main()
{
  int val = function();

  if (val == -1) {
      printf("error, val = %d\n", val);
  }
  else {
      unsigned char data = val;
      printf("success, data = %x\n", data);
  }

  return 0;
}

Btw, you should also refactor RxChar(). Consider the following:
Code:

int RxChar(COMPORT *port)
{
  int          rtn = -1;
  unsigned char readletter;

  pthread_mutex_lock(&rxmutex);

  if(read(port->id, &readletter, sizeof(readletter)) > 0)
  {
      rtn = readletter;
  }

  pthread_mutex_unlock(&rxmutex);

  return rtn;
}

And of course, always post code within CODE tags.

knobby67 07-15-2010 02:49 AM

thanks, I was hoping not to use an int, i thought like in an embedded system there would be some way to see if anything was in the UHART rather the just pulling it out to see. I'll look into select()


All times are GMT -5. The time now is 01:10 PM.