Search code examples
linuxserial-port

How to read from a Linux serial port


I am working on robot which has to control using wireless serial communication. The robot is running on a microcontroller (by burning a .hex file). I want to control it using my Linux (Ubuntu) PC. I am new to serial port programming. I am able to send the data, but I am not able to read data.

A few piece of code which is running over at the microcontroller:

Function to send data:

void TxData(unsigned char tx_data)
{
    SBUF = tx_data;  // Transmit data that is passed to this function
    while(TI == 0)   // Wait while data is being transmitted
        ;
}

I am sending data through an array of characters data_array[i]:

  for (i=4; i<=6; i++)
  {
      TxData(data_array[i]);
      RI = 0;              // Clear receive interrupt. Must be cleared by the user.
      TI = 0;        // Clear transmit interrupt. Must be cleared by the user.
  }

Now the piece of code from the C program running on Linux...

while (flag == 0) {
    int res = read(fd, buf, 255);
    buf[res] = 0; /* Set end of string, so we can printf */
    printf(":%s:%d\n", buf, res);
    if (buf[0] == '\0')
        flag = 1;
}

It prints out value of res = 0.

Actually I want to read data character-by-character to perform calculations and take further decision. Is there another way of doing this?

Note: Is there good study material (code) for serial port programming on Linux?

How can I read from the Linux serial port...


Solution

  • First, take a look at /proc/tty/driver/serial to see that everything is set up correctly (i.e., you see the signals you should see). Then, have a look at the manual page for termios(3), you may be interested in the VMIN and VTIME explanation.