自己是刚学嵌入式不久,走过很多坑,如果有小白,希望这个文章能帮助你们!!
linux串口编程
第一: 在linux下面使用vscode写串口代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int set_opt(int,int,int,char,int);
void main()
{
int fd,nByte,flag=1;
char *uart3 = "/dev/ttyS2";
char buffer[512];
char *uart_out = "Please input,waiting..\r\n";
char *uart_demo ="Linux uart demo\r\n";
memset(buffer,0,sizeof(buffer));
if ((fd = open(uart3,O_RDWR|O_NONBLOCK))<0)
printf("open %s is failed",uart3);
else
{
set_opt(fd,115200,8,'N',1);
write(fd,uart_demo,strlen(uart_demo));
write(fd,uart_out,strlen(uart_out));
while (1)
{
while (((nByte = read(fd,buffer,512))>0))
{
buffer[nByte+1] = '\0';
write(fd,buffer,strlen(buffer));
memset(buffer, 0, strlen(buffer));
nByte = 0;
}
}
}
}
int set_opt(int fd,int nSpeed,int nBits,char nEvent,int nStop)
{
struct termios newtio,oldtio;
if(tcgetattr(fd,&oldtio) != 0)
{
perror("SetupSerial 1");
return -1;
}
bzero(&newtio,sizeof(newtio));
newtio.c_cflag |= CLOCAL | CREAD;
newtio.c_cflag &= ~CSIZE;
switch (nBits)
{
case 7:
newtio.c_cflag |= CS7;
break;
case 8:
newtio.c_cflag |= CS8;
break;
}
switch (nEvent)
{
case 'O': //ji
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_cflag |= (INPCK | ISTRIP);
break;
case 'E': //ou
newtio.c_cflag |= PARENB;
newtio.c_cflag |= ~PARODD;
newtio.c_cflag |= (INPCK | ISTRIP);
break;
case 'N': //no
newtio.c_cflag |= ~PARENB;
break;
}
switch (nSpeed)
{
case 2400:
cfsetispeed(&newtio,B2400);
cfsetospeed(&newtio,B2400);
break;
case 4800:
cfsetispeed(&newtio,B4800);
cfsetospeed(&newtio,B4800);
break;
case 9600:
cfsetispeed(&newtio,B9600);
cfsetospeed(&newtio,B9600);
break;
case 115200:
cfsetispeed(&newtio,B115200);
cfsetospeed(&newtio,B115200);
break;
default:
cfsetispeed(&newtio,B9600);
cfsetospeed(&newtio,B9600);
break;
}
if (nStop ==1 )
newtio.c_cflag &= ~CSTOPB;
else if (nStop ==2 )
newtio.c_cflag &= CSTOPB;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
tcflush(fd,TCSANOW);
if ((tcsetattr(fd,TCSANOW,&newtio) != 0))
{
perror("com set error");
return -1;
}
printf("set done!\n");
return 0;
}
此代码的意思就是打开你的串口,包含读与写的过程。
代码编写完,需要使用gcc进行编译
我的开发板使用的是arm的 所以我的gcc版本是
gcc-linaro-6.3.1-2017.02-x86_64_arm-linux-gnueabihf.tar
安装链接可参考Index of /armbian-releases/_toolchain/ | 清华大学开源软件镜像站 | Tsinghua Open Source Mirror
基本上都包含了gcc版本
同时该交叉编译工具需要配置,该配置我就不多说了 主要就是解压缩然后需要设置路径
然后使用 arm-linux-gnueabihf-gcc test.c -o test 记住如果是arm一定要使用正确的gcc来编译,否则开发板识别不了,而且还会出现line1,少一个“)”的提示。
代码编译完 可以在linux上面通过scp test root@192.168.0.0:/root/(路径和地址为你开发板的地址) 可通过网线来发送到开发板上面
发送完成后可以在MobaXterm上面进行./test 运行程序,也可以在linux下面使用ssh root@192.168.0.0来连接开发板进行远程操控,同时串口转USB记得连接到主机上面而不是Linux上面,通过这个,你便可以在任意一个串口工具打开进行数据发送了
附图:
出现上图的数据说明代码已经成功在开发板上面运行了,具体的代码详情可查看其他博主!!