1. 程式人生 > >---串列埠的配置初始化函式------------------

---串列埠的配置初始化函式------------------



#include <stdio.h>
#include <stdlib.h>
#include <termio.h>
#include <unistd.h>
#include <fcntl.h>
#include <getopt.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
int uart_init(int num, int nSpeed)
{
    int fd;
    char port[20];
    struct termios Opt;

    sprintf(port, "/dev/ttySAC%d", num);
    printf("Use port: %s ", port);
	
    fd = open(port, O_RDWR);    //開啟串列埠
    if (fd < 0)
    {
        perror("open ttySAC error");
    }

    tcgetattr(fd, &Opt);        //初始化
    tcflush(fd, TCIFLUSH);

    switch (nSpeed)
    {
      case 2400:
          cfsetispeed(&Opt, B2400);
          cfsetospeed(&Opt, B2400);
          break;
      case 4800:
          cfsetispeed(&Opt, B4800);
          cfsetospeed(&Opt, B4800);
          break;
      case 9600:
          cfsetispeed(&Opt, B9600);
          cfsetospeed(&Opt, B9600);
          break;
      case 57600:
          cfsetispeed(&Opt, B57600);
          cfsetospeed(&Opt, B57600);
          break;
      case 115200:
          cfsetispeed(&Opt, B115200);
          cfsetospeed(&Opt, B115200);
          break;
      case 460800:
          cfsetispeed(&Opt, B460800);
          cfsetospeed(&Opt, B460800);
          break;
      default:
          cfsetispeed(&Opt, B9600);
          cfsetospeed(&Opt, B9600);
          break;
    }

    Opt.c_cflag |= CS8;         //設定資料位
    Opt.c_cflag &= ~PARENB;
    Opt.c_oflag &= ~(OPOST);
    Opt.c_cflag &= ~CSTOPB;
    Opt.c_lflag &= ~(ICANON | ISIG | ECHO | IEXTEN);
    Opt.c_iflag &= ~(INPCK | BRKINT | ICRNL | ISTRIP | IXON);

    Opt.c_cc[VMIN] = 0;
    Opt.c_cc[VTIME] = 0;

    if (tcsetattr(fd, TCSANOW, &Opt) != 0) 
    {
        perror("SetupSerial!");
        close(fd);
        return -1;
    }
	
    return fd;
}