我是靠谱客的博主 眯眯眼发夹,这篇文章主要介绍Linux应用层对串口的使用操作,现在分享给大家,希望可以做个参考。

在Linux中串口作为字符设备,设备节点在/dev/目录下,使用普通的open,close,write和read等系统调用即可使用。这其中会涉及到一些串口的基本属性的设置,如:波特率,奇偶校验,停止位,数据位以及有无流控等。一些特殊的系统调用和数据结构会被使用。

参考:

https://blog.csdn.net/u013485792/article/details/51006790

 

下面是一个简单的示例: 

复制代码
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <stdio.h> #include <string.h> #include <sys/types.h> #include <errno.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> #include <stdlib.h> int uart_init(int fd) { struct termios newtio, oldtio; fcntl(fd,F_SETFL,0);/*恢复串口为阻塞状态*/ if ( tcgetattr(fd, &oldtio ) != 0) { perror("tcgetattr error"); return -1; } bzero( &newtio, sizeof(newtio) ); newtio.c_cflag |= B115200 | CLOCAL | CREAD; // 设置波特率,本地连接,接收使能 newtio.c_cflag &= ~CSIZE; newtio.c_cflag |= CS8; // 数据位为 8 ,CS7 for 7 newtio.c_cflag &= ~CSTOPB; // 一位停止位, 两位停止为 |= CSTOPB newtio.c_cflag &= ~PARENB; // 无校验 //newtio.c_cflag |= PARENB; //有校验 //newtio.c_cflag &= ~PARODD // 偶校验 //newtio.c_cflag |= PARODD // 奇校验 //newtio.c_cc[VTIME] = 0; // 等待时间,单位百毫秒 (读)。后有详细说明 //newtio.c_cc[VMIN] = 0; // 最小字节数 (读)。后有详细说明 tcflush(fd, TCIOFLUSH); // TCIFLUSH刷清输入队列。 //TCOFLUSH刷清输出队列。 //TCIOFLUSH刷清输入、输出队列。 tcsetattr(fd, TCSANOW, &newtio); // TCSANOW立即生效; //TCSADRAIN:Wait until everything has been transmitted; //TCSAFLUSH:Flush input and output buffers and make the change return 0; } int main(int argc, char *argv[]) { char buff[50] = {0}; //char w_buff[] = {0xaa, 0x55, 0x00, 0x30, 0x00, 0x08, 0x00, 0x00, 0xff, 0x07, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x00, 0x00, 0x0d, 0x0a }; char w_buff[] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa}; int read_size = 0, i = 0, write_size = 0; //int fd = open("/dev/ttyAMA0", O_RDWR|O_NOCTTY|O_NDELAY); int fd = open("/dev/ttyAMA0", O_RDWR|O_NOCTTY); if(-1 == fd){ perror("can't open serialport"); return -1; } uart_init(fd); while(1) { write_size = write(fd, w_buff, sizeof(w_buff)); if(write_size < 0){ perror("serial port write is error"); } read_size = read(fd, buff, sizeof(buff)); printf("write_size = %d .receive length:%d data:", write_size, read_size); for(i = 0; i < read_size; i++){ printf("%02x ", buff[i]); } printf("n"); usleep(300000); } }

 

最后

以上就是眯眯眼发夹最近收集整理的关于Linux应用层对串口的使用操作的全部内容,更多相关Linux应用层对串口内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部