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

Linux 下以 Qt 進行串口編程:select 機制實測

環境:主機 Fedora 12,開發工具 Qt,目標板 MINI6410。

功能:目標板接收 PC 經串口送來的字串並在終端輸出,接收端採用 select 機制等待資料。

widget.h

[cpp]
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QDebug>
#include <QByteArray>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/select.h>
#include <termios.h>

namespace Ui {
    class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
};

// 端口參數結構
typedef struct _Port_Info
{
    int baud_rate;
    int port_fd;
    char parity;
    char stop_bit;
    char flow_ctrl;
    char data_bits;
} *Port_Info;

int open_port(char *port);                       // 打開串口
void close_port(int fd);                         // 關閉串口
int get_baud_rate(unsigned long baud_rate);      // 波特率對應的設定參數
int set_port(Port_Info p_info);                  // 設定端口參數

#endif // WIDGET_H

widget.cpp

[cpp]
#include "widget.h"
#include "ui_widget.h"

int Fd_Com;
#define COM "/dev/ttySAC1"

char buffer_read_com[1024];

// 打開串口
int open_port(char *port)
{
    int fd;
    if ((fd = open(port, O_RDWR | O_NOCTTY | O_NONBLOCK)) == -1)
    {
        perror("can not open com port!");
        return -1;
    }
    return fd;
}

// 關閉指定串口
void close_port(int fd)
{
    close(fd);
}

// 依波特率取得對應的設定參數
int get_baud_rate(unsigned long baud_rate)
{
    switch (baud_rate)
    {
    case 2400:   return B2400;
    case 4800:   return B4800;
    case 9600:   return B9600;
    case 19200:  return B19200;
    case 38400:  return B38400;
    case 57600:  return B57600;
    case 115200: return B115200;
    case 230400: return B230400;
    default:     return -1;
    }
}

// 設定端口
int set_port(Port_Info p_info)
{
    struct termios old_opt, new_opt;
    int baud_rate, parity;

    memset(&old_opt, 0, sizeof(old_opt));
    memset(&new_opt, 0, sizeof(new_opt));

    cfmakeraw(&new_opt);
    tcgetattr(p_info->port_fd, &old_opt);

    // 設定波特率
    baud_rate = get_baud_rate(p_info->baud_rate);
    cfsetispeed(&new_opt, baud_rate);
    cfsetospeed(&new_opt, baud_rate);

    // 不讓程式佔用串口
    new_opt.c_cflag |= CLOCAL;
    // 允許從串口讀取資料
    new_opt.c_cflag |= CREAD;

    // 資料流控制
    switch (p_info->flow_ctrl)
    {
    case '0':   // 不使用流控
        new_opt.c_cflag &= ~CRTSCTS;
        break;
    case '1':   // 硬體流控
        new_opt.c_cflag |= CRTSCTS;
        break;
    case '2':   // 軟體流控
        new_opt.c_cflag |= IXON | IXOFF | IXANY;
        break;
    }

    // 資料位
    new_opt.c_cflag &= ~CSIZE;
    switch (p_info->data_bits)
    {
    case '5': new_opt.c_cflag |= CS5; break;
    case '6': new_opt.c_cflag |= CS6; break;
    case '7': new_opt.c_cflag |= CS7; break;
    case '8': new_opt.c_cflag |= CS8; break;
    default:  new_opt.c_cflag |= CS8; break;
    }

    // 奇偶校驗位
    switch (p_info->parity)
    {
    case '0':   // 無校驗
        new_opt.c_cflag &= ~PARENB;
        break;
    case '1':   // 偶校驗
        new_opt.c_cflag |= PARENB;
        new_opt.c_cflag &= ~PARODD;
        break;
    case '2':   // 奇校驗
        new_opt.c_cflag |= PARENB;
        new_opt.c_cflag |= PARODD;
        break;
    }

    // 停止位
    if (p_info->stop_bit == '2')
        new_opt.c_cflag |= CSTOPB;
    else
        new_opt.c_cflag &= ~CSTOPB;

    new_opt.c_oflag &= ~OPOST;   // 原始資料輸出
    new_opt.c_cc[VMIN] = 1;      // 每次至少讀 1 個字元
    new_opt.c_cc[VTIME] = 1;     // 首字元等待 0.1 秒

    // 若發生溢出,丟棄既有輸入
    tcflush(p_info->port_fd, TCIFLUSH);

    int result = tcsetattr(p_info->port_fd, TCSANOW, &new_opt);
    if (result == -1)
    {
        perror("cannot set the serial port parameters");
        return -1;
    }

    tcgetattr(p_info->port_fd, &old_opt);
    return result;
}

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 打開串口
    Fd_Com = open_port(COM);

    // 設定通信參數:115200, 8, N, 1
    struct _Port_Info info;
    info.baud_rate = 115200;
    info.data_bits = 8;
    info.flow_ctrl = 0;
    info.port_fd = Fd_Com;
    info.stop_bit = 1;
    info.parity = 0;

    if (set_port(&info) == -1)
    {
        printf("set com para wrong!!!!!!!!!!!!!");
    }

    int err = 0;
    struct timeval wait_time;
    fd_set read_fds;
    int len_com = 0;

    // 先送三個字元做測試
    char *data = "jdh";
    int len = write(Fd_Com, data, 3);
    if (len != 3)
    {
        qDebug() << "yi chu";
        tcflush(Fd_Com, TCOFLUSH);
    }

    while (1)
    {
        wait_time.tv_sec = 0;
        wait_time.tv_usec = 20000;
        FD_ZERO(&read_fds);
        FD_SET(Fd_Com, &read_fds);

        err = select(Fd_Com + 1, &read_fds, NULL, NULL, NULL);
        if (err < 0)
        {
            perror("select fail");
            continue;
        }
        else
        {
            if (err == 0)
                continue;   // 超時返回
        }

        // 串口可讀
        if (FD_ISSET(Fd_Com, &read_fds))
        {
            qDebug() << "du qu sheng ka";
            len_com = read(Fd_Com, buffer_read_com, 1024);
            qDebug() << "read com byte = " << len_com;

            QByteArray temp;
            temp.append(buffer_read_com, len_com);
            qDebug() << temp;
        }
    }

    qDebug() << "end";
}

Widget::~Widget()
{
    delete ui;
}

說明

串口在驅動層有一個緩衝區,收到的資料會先存在裡面。如果一次送出大量資料、而讀取間隔很短,那麼每次 read() 拿到的都只是整個封包的一部分片段。因此實務上通常需要自行定義封包邊界(例如以固定長度或結束符號判斷),把多次讀到的片段組回完整的一筆訊息。

Copyright © Linux教程網 All Rights Reserved