柚子快報(bào)邀請(qǐng)碼778899分享:運(yùn)維 [Linux] 串口讀寫(xiě)
柚子快報(bào)邀請(qǐng)碼778899分享:運(yùn)維 [Linux] 串口讀寫(xiě)
直接通過(guò)終端控制串口
cd 進(jìn)入 /dev
ls 查看當(dāng)前文件夾文件
在這里操作,ttyS*為串口的格式
可以直接操作串口1/3,在這里使用串口3
設(shè)置波特率(stty命令)
stty -F /dev/ttyS3 115200
在這里使用 stty 設(shè)置串口的屬性為115200,校驗(yàn)位等都是通過(guò)這個(gè)命令設(shè)置
串口數(shù)據(jù)讀寫(xiě)操作
使用echo向串口發(fā)送數(shù)據(jù),如echo “hello linux” > /dev/ttyS3
輸出為
可以使用cat來(lái)讀取串口中的數(shù)據(jù),如cat /dev/ttyS3,注意 在這里使用cat的時(shí)候串口會(huì)回顯輸入的數(shù)據(jù),例如我在這里串口輸入 123 ,注意點(diǎn)發(fā)送新行
得到的結(jié)果是:
也可以讀取數(shù)據(jù)并保存到txt文本文件中,如cat /dev/ttyS3 > test.txt,這里不演示
C語(yǔ)言控制串口
持續(xù)串口交互
使用C語(yǔ)言在vim上開(kāi)發(fā)
用到的頭文件主要為 "termios.h"
讀取函數(shù)為 read(fd,&readbuf,sizeof(readbuf));
輸出函數(shù)為write(fd,&writebuf,sizeof(writebuf));
在這里貼一個(gè)串口回傳實(shí)驗(yàn):
#include
#include
#include
#include
#include
#include
/* 115200, 8, N, 1 */
int uart_setup(int fd)
{
struct termios options;
// 獲取原有串口配置
if (tcgetattr(fd, &options) < 0) {
return -1;
}
// 修改控制模式,保證程序不會(huì)占用串口
options.c_cflag |= CLOCAL;
// 修改控制模式,能夠從串口讀取數(shù)據(jù)
options.c_cflag |= CREAD;
// 不使用流控制
options.c_cflag &= ~CRTSCTS;
// 設(shè)置數(shù)據(jù)位
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
// 設(shè)置奇偶校驗(yàn)位
options.c_cflag &= ~PARENB;
options.c_iflag &= ~INPCK;
// 設(shè)置停止位
options.c_cflag &= ~CSTOPB;
// 設(shè)置最少字符和等待時(shí)間
options.c_cc[VMIN] = 1; // 讀數(shù)據(jù)的最小字節(jié)數(shù)
options.c_cc[VTIME] = 0; //等待第1個(gè)數(shù)據(jù),單位是10s
// 修改輸出模式,原始數(shù)據(jù)輸出
options.c_oflag &= ~OPOST;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
// 設(shè)置波特率
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
// 清空終端未完成的數(shù)據(jù)
tcflush(fd, TCIFLUSH);
// 設(shè)置新屬性
if(tcsetattr(fd, TCSANOW, &options) < 0) {
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
int fd;
int ret;
char readbuf[20]={0};
char writebuf[20]={0};
/* 打開(kāi)串口 */
fd = open("/dev/ttyS3", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd < 0) {
printf("open dev fail!\n");
return -1;
} else {
printf("Open uart OK \n");
fcntl(fd, F_SETFL, 0);
}
/* 設(shè)置串口 */
ret = uart_setup(fd);
if (ret < 0) {
printf("uart setup fail!\n");
close(fd);
return -1;
}
printf("setup uart OK \n");
/* 串口回傳實(shí)驗(yàn) */
while (1) {
ret = read(fd, &readbuf, sizeof(readbuf));
if (ret != -1) {
ret=write(fd,&readbuf,sizeof(readbuf));
ret=write(fd,"\r\n",2);
}
}
close(fd);
}
運(yùn)行后的結(jié)果為:
通過(guò)串口輸入內(nèi)容會(huì)通過(guò)串口返回
柚子快報(bào)邀請(qǐng)碼778899分享:運(yùn)維 [Linux] 串口讀寫(xiě)
參考閱讀
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場(chǎng)。
轉(zhuǎn)載請(qǐng)注明,如有侵權(quán),聯(lián)系刪除。