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 assume that data has written on a specific port. Now I would like to open another terminal and using separate code want to read the data written on that specific port - how do I do that?
我是使用C在Linux中進行串行編程的新手。我找到了一小段代碼來在串口上寫數據,我在這里分享。運行此代碼后,我可能會認為數據已寫入特定端口。現在我想打開另一個終端並使用單獨的代碼想要讀取寫在該特定端口上的數據 - 我該怎么做?
#include /* Standard input/output definitions */
#include /* String function definitions */
#include /* UNIX standard function definitions */
#include /* File control definitions */
#include /* Error number definitions */
#include /* POSIX terminal control definitions */
/*
* 'open_port()' - Open serial port 1.
*
* Returns the file descriptor on success or -1 on error.
*/
int
open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
/* Could not open the port. */
perror("open_port: Unable to open /dev/ttyS0 - ");
}
else
fcntl(fd, F_SETFL, 0);
n = write(fd, "ATZ\r", 4);
if (n < 0)
fputs("write() of 4 bytes failed!\n", stderr);
return (fd);
}
The code above will write the data on a specific port.
上面的代碼將在特定端口上寫入數據。
2 个解决方案
#1
10
In theory, all you have to do is open the relevant port for reading, and use read() to get the data.
理論上,您所要做的就是打開相關的讀取端口,並使用read()來獲取數據。
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.
有差異;值得注意的是,讀取需要一個緩沖區來放入數據。顯示的代碼丟棄了第一個讀取的消息。請注意,簡短讀取只表示可用數據少於讀取完成時所請求的數據。它不會自動指示錯誤。想一下命令行;一些命令可能是一個或兩個字符(ls),其他命令可能非常復雜(find / some / where -name'* .pdf'-mtime -3 -print)。使用相同緩沖區來讀取兩者的事實不是問題;一個讀取給出3個字符(包括換行符),另外47個左右。
#2
7
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
發布的程序對端口的狀態做了很多假設。在現實世界的應用程序中,您應該明確地執行所有重要的設置。我認為在POSIX下學習串口編程的最佳來源是
Serial Programming Guide for POSIX Operating Systems
POSIX操作系統的串行編程指南
我在這里反映它:http://mirror.datenwolf.net/serial/