歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下打開串口設置

Linux下打開串口設置

日期:2017/3/1 9:31:11   编辑:Linux編程

給出Linux下打開串口函數

int open_tty(char tty[])
{
int fd;
char tty_path[32]={0};
sprintf(tty_path,"/dev/%s",tty);
fd=tty_open_port(tty_path);
// PORT_SPEED是一個定義的宏,表示傳輸速率。數據位為8,無校驗位,停止位為1
tty_set_opt(fd,PORT_SPEED,8,'N',1);
return fd;
}

該函數接受一個參數,表示你要打開的串口名稱,如“ttyS1”,返回串口操作描述符,在調用該函數後,可以根據返回值來判斷是否設置成功,如果fd大於0,則返回成功。

該函數還依賴於兩個函數,下面也給出(包括用到的頭文件)。

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <error.h>
#include <sys/stat.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include <stdlib.h>
extern int tty_open_port(char *tty_num);
extern int tty_set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop);
int tty_open_port(char *tty_num)
{
int fd = open (tty_num, O_RDWR | O_NOCTTY | O_NDELAY );
//阻塞 fcntl(fd,F_SETFL,0) ; //block
//非阻塞 fcntl(fd,F_SETFL,FNDELAY) ;
if (fd == -1)
{
printf ("Can't Open Serial Port %s !\n",tty_num);
return -1;
}
else
{
//將串口設置成非阻塞的操作
fcntl(fd,F_SETFL,FNDELAY);
return fd;
}

}
/**************************************************************************************
* 功 能:set serial port speed
* 修改歷史: 2011.6.29.
**************************************************************************************/
int tty_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; //mask the character size bits

switch( nBits )
{
case 7:
newtio.c_cflag |= CS7; //data: 7bits
break;
case 8:
newtio.c_cflag |= CS8; //data: 8bits
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 ) //set the bps
{
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 19200:
cfsetispeed(&newtio, B19200);
cfsetospeed(&newtio, B19200);
break;
case 115200:
cfsetispeed(&newtio, B115200);
cfsetospeed(&newtio, B115200);
break;
case 460800:
cfsetispeed(&newtio, B460800);
cfsetospeed(&newtio, B460800);
break;
default:
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
}

if( nStop == 1 ) //set the 1bit stop
newtio.c_cflag &= ~CSTOPB;
else if ( nStop == 2 ) //set the 2bit stop
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;
}
printf("Current serial speed is %d\n",nSpeed);
return 0;
}

代碼中給出了可以設置成阻塞和非阻塞的操作。

Copyright © Linux教程網 All Rights Reserved