` 本帖最后由 renshengrumeng 于 2017-5-23 15:28 编辑
串口是我们常用到的通信,做嵌入开发也经常会用到串口通信,nanopi Mi Plus 开发板自带一个串口是用来打印日志功能的,想在搞个串口出来用来做其他功能使用。
查看了下开发板的功能图和引出的引脚,发现引出了2个串口引脚。引脚功能如图:
通过查看初始化日志发现开机后板子初始化了ttyS1,ttyS2,ttyS3.ttyS0用作了console.查看方式如图:
这次我愿用了ttyS1 根据引脚功能连接串口模块连接电脑。如图:
接下来就是程序了,我直接上源码了。
#include
#include
#include
#include
#include
#include
#include
#include
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':
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_iflag |= ( INPCK | ISTRIP );
break;
case 'E':
newtio.c_iflag |= ( INPCK | ISTRIP );
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 'N':
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, B115200);
cfsetospeed( &newtio, B115200);
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, TCIFLUSH);
}
if(( tcsetattr( fd, TCSANOW, &newtio)) != 0){
perror("com set error
");
return -1;
}
return 0;
}
int main(int argc, char* argv[])
{
int fd, wr_static, i = 10;
char *uart1 = "/dev/ttyS1";
char *buffer = "hello word!
";
printf("
write uart1 test
");
if((fd = open(uart1, O_RDWR | O_NOCTTY | O_NDELAY)) < 0){
printf("open %s failed!
", uart1);
}
else{
printf("open %s is success!
", uart1);
set_opt(fd, 115200, 8, 'N', 1);
while(i--){
wr_static = write(fd, buffer, strlen(buffer));
if(wr_static < 0){
printf("write failed
");
}
else{
printf("wr_static is %d
", wr_static);
}
sleep(1);
}
}
close(fd);
return 0;
}
通过ARM-linux-gnueablhf-gcc -o uart1 uart1.c -static 编译。
通过./uart1运行。
运行效果如图:
简单的串口通信就这么搞定了。
`
|