MeiOokami
Posts: 9
Joined: Tue Mar 05, 2013 8:43 pm

UART Recive Buffer?

Mon Mar 25, 2013 3:54 pm

Hi,
I'm trying to interface the pi's to the xbee using uart and api codes. I can send the commands, but when it comes to reading back responses for the analog sampling I ran into a bit of an issue with needing to hit enter to what seems to be the only way to fill the uart buffer. As you can see by my c code below i have tried adding the '\r' in two methods of reading at the end of the amount of bits I want to read with no luck.

long story short: Is there a way to read in a exact amount of chars from the uart without hitting enter after?

Code: Select all

#if 1
i = 0;
do
{
   n = read(fd, (void*)&c, 1);
  if (n > 0)
  {
    buf[i++] = c;
  }
 if (i==16) {c='\r';}
}
while (c != '\r' && i < 16 && n > 0);
buf[i] = '\0';

#endif
#if 0
for(i=0;i<16;i++) // reading temp
{
   n = read(fd, (void*)&c, 1);
  if (n > 0)
  {
    buf[i] = c;
  }
 if (i==15) {c='\r';}
}
buf[i] = '\0';
//Bytes received
#endif

printf("%i bytes read : %s\n", i, buf); // write read data to terminal.
UART initialization:

Code: Select all

     int fd,n;
  // Open the Port. We want read/write, no "controlling tty" status, and ope$
  fd = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);
  if (fd == -1) {
    perror("open_port: Unable to open /dev/ttyAMA0 - ");
    return(-1);
  }

struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
tcsetattr(fd, TCSANOW, &options);

// Turn off blocking for reads, use (fd, F_SETFL, FNDELAY) if you want that
  fcntl(fd, F_SETFL, FNDELAY);
EDIT: Problem Resolved sorry for the wasted post, but here was my solution just needed to mess around with the blocking options of the uart configuration.

New UART initialization:

Code: Select all

 struct termios oldtio,newtio;

        fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
        if (fd <0) {perror(MODEMDEVICE); return(-1); }

        tcgetattr(fd,&oldtio); /* save current port settings */

        bzero(&newtio, sizeof(newtio));
        newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
        newtio.c_iflag = IGNPAR;
        newtio.c_oflag = 0;

        /* set input mode (non-canonical, no echo,...) */
        newtio.c_lflag = 0;

        newtio.c_cc[VTIME]    = 0;   /* inter-character timer unused */
        newtio.c_cc[VMIN]     = 1;   /* blocking read until 1 chars received */

        tcflush(fd, TCIFLUSH);
        tcsetattr(fd,TCSANOW,&newtio);

Return to “C/C++”