【发布时间】:2018-12-06 03:41:14
【问题描述】:
我是使用 C 在 Linux 中进行串行编程的新手。我找到了一小段代码来在串行端口上写入数据,我在这里分享。运行此代码后,我可能会假设数据已写入特定端口。现在我想打开另一个终端并使用单独的代码来读取写入在该特定端口上的数据 - 我该怎么做?
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* 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);
}
上面的代码会将数据写入特定的端口。
【问题讨论】:
-
请注意,write 函数可能(理论上)返回 3 表示它成功写入了 4 个字节中的 3 个。您可以决定是否将“短写入”视为错误,或者是否重试写入缓冲区的剩余部分。
标签: c linux serial-port