本文共 1811 字,大约阅读时间需要 6 分钟。
1,打开串口
/**打开串口,dev 串口设备名, mode 打开方式,**/
int opendev(char *dev,mode_t mode)
{ int fd; fd = open(dev, mode); if (-1 == fd){ perror("Can't Open Serial Port"); return -1; } else{ fcntl(fd, F_SETFL, FNDELAY); return fd; } }2,写串口
#define FALSE -1
#define TRUE 0 #define NET_PORT 19988 #define MAX_BUF_SIZE 4096 struct net2net_buf{ int len; char buf[MAX_BUF_SIZE]; }; #define RSDEV_NAME "/dev/ttyS1"int main(void)
{ int rsfd = 0; int nwrite; char input_buf[64]; rsfd = opendev(RSDEV_NAME,O_RDWR | O_NOCTTY | O_NDELAY); if(rsfd < 0){ printf("open error:/n"); exit(-1); } set_speed(rsfd,9600); /*设置速率B9600*/ if (set_parity(rsfd,8,1,'N') == FALSE){ /*8位数据位,一位停止位*/ printf("Set Parity Error/n"); exit (-1); } while(1){
fgets(input_buf,sizeof(input_buf),stdin); printf("input_buf = %s", input_buf); nwrite = write(rsfd, input_buf, strlen(input_buf)); if ( nwrite == -1 ) { perror("ERROR!"); exit(1); }else {
printf("ret=%d/n", nwrite); } } }3,读串口
int read_rs232(int rsfd)
{ int retbytes = 0,nread = 0; int all_bytes = 0; struct net2net_buf netbuf; int i; memset(&netbuf,0,sizeof(netbuf)); while((nread = read(rsfd, &netbuf.buf[retbytes], 512))>0) { printf("nread:%d/n",nread); retbytes += nread; all_bytes += nread; } return all_bytes; } int main(void) { int rsfd = 0; int nwrite; fd_set fdR; struct timeval timev; int n = 0; char input_buf[64]; rsfd = opendev(RSDEV_NAME,O_RDWR | O_NOCTTY | O_NDELAY); if(rsfd < 0){ printf("open error:/n"); exit(-1); } set_speed(rsfd,9600); /*设置速率B9600*/ if (set_parity(rsfd,8,1,'N') == FALSE){ /*8位数据位,一位停止位*/ printf("Set Parity Error/n"); exit (-1); } while(1) { FD_ZERO(&fdR); FD_SET(rsfd, &fdR); timev.tv_sec = 0; timev.tv_usec = 100000; n = select(rsfd+1, &fdR, NULL, NULL, &timev); if(n <= 0) continue; if (FD_ISSET(rsfd,&fdR)) { printf("rs232 recv/n"); read_rs232(rsfd); } } }转载地址:http://lbbsi.baihongyu.com/