Search code examples
craspberry-piusbserial

Raspberry pi, communicate with Serial Device


I try to communicate from Raspberry pi to the a serial device with out success.

I connect, write data but never read data back.

The serial device works fine in windows with the following settings on the com port - Baud Rate: 9600, Parity: None, Bit: 8, Stop bit: 1.

For communication I use a USB to Serial FTDI adaptor.

My working c code is :

int set_interface_attribs(int serialPort)
{
  struct termios tty;
  if (tcgetattr(serialPort, &tty) < 0) {
    printf("Error from tcgetattr: %s\n", strerror(errno));
    return -1;
  }
  printf("Old Serial port flags, i:%d, o:%d, c:%d\n", (int)tty.c_iflag, (int)tty.c_oflag, (int)tty.c_cflag);
  int speed = B9600;
  cfsetospeed(&tty, (speed_t)speed);
  cfsetispeed(&tty, (speed_t)speed);
  tty.c_cflag = CS8 |  CLOCAL | CREAD;
  tty.c_iflag = IGNPAR;
  tty.c_oflag = 0;
  tty.c_lflag = 0;
  tcflush(serialPort, TCIFLUSH);
  if (tcsetattr(serialPort, TCSANOW, &tty) != 0) {
    printf("Error from tcsetattr: %s\n", strerror(errno));
    return -1;
  }
  printf("New Serial port flags, i:%d, o:%d, c:%d\n", (int)tty.c_iflag, (int)tty.c_oflag, (int)tty.c_cflag);
  return 0;
}

int main( int argc, char *argv[] ) {
  printf("Start program\n");
  int serialPort=0;
  //if ((serialPort=open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK))<0) {
  if ((serialPort=open("/dev/ttyUSB0", O_RDWR | O_NOCTTY))<0) {
    printf("Error opening port: %s\n", strerror(errno));
    return 1;
  }
  set_interface_attribs(serialPort);
  long n;
  char strSend[20];
  sprintf(strSend,"98000001%c%c", 0x0D,0x0A);
   if ((n = write(serialPort, strSend, strlen(strSend)) ) < 0 ){
    perror("Error write to serialPort");
    return 0;
  }
  printf("Write (%d) chars (%s) to serialPort\n", (int)n, strSend);
  sleep(1);
  printf("Start reading from serialPort\n");
  char wData[20];
  memset(wData, '\0', sizeof(wData));
  if ( (n = read(serialPort, wData, 20) ) <= 0 ){
    printf("Error %d read from serialPort\n", (int)n);
  } else{
    wData[n] = 0;
    printf("Read:%d, %s\n", (int)n, wData);
  }
  printf("Close serialPort\n");
  close(serialPort);
  return 0;
}

and the out put is :

Start program
Old Serial port flags, i:4, o:0, c:2224
New Serial port flags, i:4, o:0, c:2224
Write (10) chars (98000001
) to serialPort
Start reading from serialPort
Error 0 read from serialPort
Close serialPort

any iden or suggestion ;


Solution

  • The reading should be at the same time that the write.

    You should do an infinite loop. This bucle should always be reading the port. It is recomended to make a buffer into a thread (you could use lpthread.h).

    The life cycle:

    • Configure serial port
    • Open serial port
    • Create thread to read
    • Write (to test it)
    • Close serial port.

    On the other hand, the best option (if you want to test your code) is make a jumper on RX and TX pinouts.

    So all you write you will be able to read it.