串口"/>
orangepi基于c库开发串口
基于c库开发串口其实就是一串标准化的流程
其中涉及串口的打开
设置波特率、数据位、停止位、校验位
给串口发送数据、读取串口中的数据(串口中的数据一旦读走就没了)
1.unrtTool.h
int myserialOpen (const char *device, const int baud);
int myserialPutstring(int fd,char *c);
int myserialGetstring(int fd,char *c);
2.unrtTool.c
//串口相关Api的实现
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "wiringSerial.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>int myserialOpen (const char *device, const int baud)
{struct termios options ;speed_t myBaud ;//波特率int status, fd ;switch (baud){case 9600: myBaud = B9600 ; break ;case 115200: myBaud = B115200 ; break ;default:return -2 ;}if ((fd = open (device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK)) == -1)return -1 ;tcgetattr (fd, &options) ;cfmakeraw (&options) ;cfsetispeed (&options, myBaud) ;cfsetospeed (&options, myBaud) ;options.c_cflag |= (CLOCAL | CREAD) ;options.c_cflag &= ~PARENB ;options.c_cflag &= ~CSTOPB ;//停止位options.c_cflag &= ~CSIZE ;options.c_cflag |= CS8 ;//数据位options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG) ;options.c_oflag &= ~OPOST ;options.c_cc [VMIN] = 0 ;options.c_cc [VTIME] = 100 ; // Ten seconds (100 deciseconds)tcsetattr (fd, TCSANOW, &options) ;ioctl (fd, TIOCMGET, &status);status |= TIOCM_DTR ;status |= TIOCM_RTS ;ioctl (fd, TIOCMSET, &status);usleep (10000) ; // 10mSreturn fd ;
}int myserialPutstring(int fd, char *c){int n_send;n_send=write(fd,c,strlen(c));if (n_send!=1)return -1;return n_send;
}
int myserialGetstring(int fd, char *c){int n_read;n_read=read(fd,c,32);if(n_read!=1)return -1;return n_read;}
3. 串口的代码实现(unrt.c)
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "wiringSerial.h"
#include <sys/stat.h>
#include <fcntl.h>
#include "unrtTool.h"
#include <string.h>
#include <pthread.h>
int fd;
void *send(){char sendbuf[32];while(1){memset(sendbuf,'\0',sizeof(sendbuf));scanf("%s",sendbuf);myserialPutstring(fd,sendbuf);}}void *get(){char readbuf[32];while(1){memset(readbuf,'\0',sizeof(readbuf));myserialGetstring(fd,readbuf);printf("GET-> %s\n",readbuf);usleep(500000);}}
int main(int argc,char **argv){char filename[32];pthread_t p1;pthread_t p2;if(argc<2){printf("uage:%s /dev/ttyS*\n",argv[0]);}memset(filename,'\0',sizeof(filename));strcpy(filename,argv[1]);if((fd=myserialOpen(filename,115200))==-1){return -1;}pthread_create(&p1,NULL,send,NULL);pthread_create(&p2,NULL,get,NULL);while(1){sleep(10);}
}
4.编译
gcc unrt.c unrtTool.c unrtTool.h -lpthread
5.运行
在运行时必须添加串口的驱动
./a.out /dev/ttyS5
更多推荐
orangepi基于c库开发串口
发布评论