How do I read data from serial port in Linux using C?

前端 未结 2 1154
忘了有多久
忘了有多久 2020-12-08 12:02

I am new to serial programming in Linux using C. I have found a small piece of code to write data on serial port which I am sharing here. After running this code I may assum

相关标签:
2条回答
  • 2020-12-08 12:31

    In theory, all you have to do is open the relevant port for reading, and use read() to get the data.

    int
    read_port(void)
    {
        int fd = open("/dev/ttyS0", O_RDONLY | O_NOCTTY);
        if (fd == -1)
        {
            /* Could not open the port. */
            perror("open_port: Unable to open /dev/ttyS0 - ");
        }
    
        char buffer[32];
        int n = read(fd, buffer, sizeof(buffer));
        if (n < 0)
            fputs("read failed!\n", stderr);
        return (fd);
    }
    

    There are differences; notably, the read needs a buffer to put the data in. The code shown discards the first message read. Note that a short read simply indicates that there was less data available than requested at the time when the read completed. It does not automatically indicate an error. Think of a command line; some commands might be one or two characters (ls) where others might be quite complex (find /some/where -name '*.pdf' -mtime -3 -print). The fact that the same buffer is used to read both isn't a problem; one read gives 3 characters (newline is included), the other 47 or so.

    0 讨论(0)
  • 2020-12-08 12:34

    The program posted makes a lot of assumptions about the state of the port. In a real world application you should do all the important setup explicitly. I think the best source for learning serial port programming under POSIX is the

    Serial Programming Guide for POSIX Operating Systems

    I'm mirroring it here: https://www.cmrr.umn.edu/~strupp/serial.html

    0 讨论(0)
提交回复
热议问题