1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
| #include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdio.h>
int main()
{
size_t buf_len;
char buf[512];
int fd = open("/dev/pts/5", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1)
return -1;
struct termios tio;
if (tcgetattr(fd, &tio) != 0)
return -2;
tio.c_cflag |= CLOCAL; // 保证程序不占用串口
tio.c_cflag |= CREAD; // 使能读数据
tio.c_cflag &= ~CRTSCTS; // 不使用流控制
tio.c_cflag &= ~CSIZE; // 屏蔽其它标志位
tio.c_cflag |= CS8; // 8位数据位
tio.c_cflag &= ~PARENB; // 无奇偶校验
tio.c_iflag &= ~INPCK;
tio.c_cflag &= ~CSTOPB; // 1位停止位
tio.c_oflag &= ~OPOST; // 原始数据输出
tio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
if (cfsetspeed(&tio, B115200) != 0)
return -3;
if (tcsetattr(fd, TCSANOW, &tio) != 0)
return -4;
for (int i = 0; i < 100; ++i)
write(fd, "1234", 4);
while (1) {
printf("ok\n");
if ((buf_len = read(fd, buf, 512)) != -1) {
for (int i = 0; i < buf_len; ++i)
printf("%c", buf[i]);
}
sleep(1);
}
}
|