21,595
社区成员
发帖
与我相关
我的任务
分享
/*
* @author:xxx
* history :xxxxx
*
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <termios.h>
#include <memory.h>
#include <time.h>
#define MCX "/dev/ttymxc2"
int set_opt(int fd, int nSpeed, int nBits, char nEvent, int nStop){
struct termios newtio, oldtio;
if(tcgetattr(fd, &oldtio) != 0){
printf("setup serial error\n");
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;
}
//'O' odd, 'E' enb
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 115200:
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);
//valid quickly
if(tcsetattr(fd, TCSANOW, &newtio) != 0){
printf("com set error\n");
return -1;
}
printf("set down \n");
return 0;
}
int open_port(int fd){
fd = open(MCX, O_RDWR | O_NOCTTY | O_NDELAY);
if(fcntl(fd, F_SETFL, 0) < 0)
printf("fcntl failed\n");
else
printf("fcntl = %d\n", fcntl(fd, F_SETFL, 0));
if(isatty(STDIN_FILENO) == 0)
printf("standard input is not a terminal device\n");
else
printf("isatty success\n");
if(fd == -1){
printf("open /dev/ttymxc2 error\n");
return -1;
}else
printf("=================================== success open pve_mxc2-----------------------------------------------\n");
return fd;
}
int main(void){
int fd = 0;
char rbuffer[512];
int i;
int nread;
if((fd = open_port(fd))< 0){
printf(" pve_mcx2 is opened error\n");
return -1;
}
if(i=set_opt(fd, 115200, 8, 'N', 1)){
printf("set opt error \n");
}
while(1){
if((nread = read(fd, rbuffer, 512))>0){
printf("\nLen %d\n",nread);
rbuffer[nread+1] = '\0';
printf( "\n%s", rbuffer);
}else {
printf("\n ====================== no data from gps ====================");
perror("Read err");
sleep(5);
}
}
close(fd);
return 0;
}