Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux 下 2410 開發板串口讀寫關鍵程式碼

前言

在嵌入式 Linux 環境中,串口是常見的對外通訊方式。以下整理 2410 開發板上常見的串口初始化、設定、讀取與寫入程式碼。

開啟串口

int openport(char *Dev) {
    int fd = open(Dev, O_RDWR | O_NOCTTY | O_NDELAY);
    if (-1 == fd) {
        perror("Can't Open Serial Port");
        return -1;
    }
    return fd;
}

設定串口參數

設定項目包含波特率、資料位、停止位與同位元檢查。核心概念是透過 termios 結構設定 c_cflag、c_iflag、c_oflag 與 c_cc。

int setport(int fd, int baud, int databits, int stopbits, int parity) {
    struct termios newtio;
    tcgetattr(fd, &newtio);
    bzero(&newtio, sizeof(newtio));

    newtio.c_cflag |= (CLOCAL | CREAD);
    newtio.c_cflag &= ~CSIZE;
    newtio.c_cflag |= CS8;

    cfsetispeed(&newtio, baud);
    cfsetospeed(&newtio, baud);

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

讀取與寫入

int readport(int fd, char *buf, int len, int maxwaittime) {
    fd_set readfd;
    struct timeval tv;
    FD_ZERO(&readfd);
    FD_SET(fd, &readfd);
    tv.tv_sec = maxwaittime / 1000;
    tv.tv_usec = (maxwaittime % 1000) * 1000;

    int rc = select(fd + 1, &readfd, NULL, NULL, &tv);
    if (rc > 0) {
        return read(fd, buf, len);
    }
    return -1;
}

void writeport(int fd, char *buf, int len) {
    write(fd, buf, len);
}

執行緒概念

實務上常會開啟一個執行緒持續讀取串口,另一個執行緒處理 GUI 或主流程。若資料格式不符,可呼叫 tcflush 清除輸入輸出緩衝區。

Copyright © Linux教程網 All Rights Reserved