• 36835阅读
  • 24回复

qt串口编程 [复制链接]

上一主题 下一主题
离线tomoowang
 

只看楼主 倒序阅读 楼主  发表于: 2008-01-09
qt串口编程
— 本帖被 XChinux 执行加亮操作(2008-04-22) —
[serial.cpp]
#include <qapplication.h>
#include <qmainwindow.h> 

#include "mainwindow.h"
int main(int argc, char *argv[])
{
    QApplication a(argc,argv);
  MainWindow m;
   
    a.setMainWidget(&m);
    m.show();
  return a.exec();
}


[mainwindow.h]
#ifndef MAIN_WINDOW_H
#define MAIN_WINDOW_H

#include <qmainwindow.h>

class QLabel;
class QPushButton;
class QLineEdit;
class QPixmap;
class SerialThread;

class MainWindow:public QMainWindow {
    Q_OBJECT
public:
    MainWindow(QWidget * parent = 0, const char * name= 0) ;
    ~MainWindow(){};
   
    void setCounter(int no);
    void setMsgText(char* txt);
public slots:   
    void serialOperate();
    void loadJPEGFile();
   
protected:
    void    paintEvent( QPaintEvent * );
   
private:
 
    QLineEdit *msg;
    QPushButton *btn;
    QPushButton *btn2LoadImg;
    QPixmap *pix;
    QLabel *lab;
    SerialThread *a;
    int counter;
};

#endif


[mainwindow.cpp]

#include <qlabel.h>     
#include <qpushbutton.h> 
#include <qvbox.h> 
#include <qapplication.h>
#include <qlineedit.h>
#include <qpixmap.h>
#include <qpainter.h>
#include <qimage.h>
#include <qstring.h>


#include "mainwindow.h"   
#include "serialthread.h"   

void MainWindow::paintEvent( QPaintEvent * )
{
    QPainter paint( this );
    paint.drawLine( 0,0,500,500 ); // draw line
        paint.drawPixmap(0,0,*pix);
        }

void MainWindow::loadJPEGFile(){
     
    if(!pix->load("testjpeg")){
    //if(!pix->load("circle")){
        setMsgText("Load failed");
        return;
    }
    setMsgText("Load success!");
    update();
       
}

void MainWindow::setCounter(int no){
    counter = no;
}

void MainWindow::serialOperate(){
  a = new SerialThread(this);
    a->start();
    a->wait();
}

MainWindow::MainWindow(QWidget * parent , const char * name)
    :QMainWindow(parent, name)
{
   
        counter = 0;
       
        QVBox *vbox;
        vbox = new QVBox(this);
        vbox->resize(300,150);
        //msg = new QLabel("SERIAL PROGRAMMING",vbox);
        msg = new QLineEdit("SERIAL PROGRAMMING",vbox);
        msg->resize(300,50);
       
        pix = new    QPixmap();             
       
        btn = new QPushButton(vbox);
        btn->setText("GO!");
        QApplication::connect(btn,SIGNAL(clicked()),this,SLOT(serialOperate()));
        btn2LoadImg = new QPushButton(vbox);
        btn2LoadImg->setText("LOAD");
       
        lab = new QLabel("before load jpeg",vbox);
        QApplication::connect(btn2LoadImg,SIGNAL(clicked()),this,SLOT(loadJPEGFile()));
       
        //btn->resize(100,75);
        //vbox->show();
};

void MainWindow::setMsgText(char* txt){
        QString msgs(txt);
        QString count = QString::number(counter,10);
        msgs.append(count);
        const    char *re = msgs.ascii ();         
        //strcat(msgs,);
        msg->setText(re);   
};\


[my_define.h]
#define BAUDRATE    B115200
#define BLOCK_SIZE    200   
#define DEVICE        "/dev/ttyS0"
#define WAIT_TIME    5
#define CHANGE_LINE    0x0a
#define ACK_NUM    3
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE -1
#endif



[serialthread.h]
#ifndef SERIAL_THREAD_H
#define  SERIAL_THREAD_H
#include <qthread.h>

class MainWindow;

class SerialThread: public QThread {
public:
    SerialThread(MainWindow *parent);
    virtual void run();
private:
    MainWindow *parent;

};
#endif



[serialthread.cpp]

#include <sys/types.h>     
#include <sys/stat.h>     
#include <fcntl.h>     
#include <termios.h>     
#include <stdio.h> 

#include "my_define.h"
#include "serialthread.h"
#include "mainwindow.h"



int set_nc_mode(int fd)
{
    struct termios options;
    if  ( tcgetattr( fd,&options)  !=  0){
          perror("SetupSerial 1");
          return(FALSE);
      } /* get current port settings */

    bzero(&options, sizeof(options)); 
    options.c_cflag |= BAUDRATE | CS8 | CLOCAL | CREAD; 
    options.c_cflag &= ~CRTSCTS;
    options.c_iflag = IGNPAR; 
    options.c_oflag &=~OPOST;           
        //
      options.c_lflag = 0;           
        options.c_cc[VTIME] = WAIT_TIME;
    options.c_cc[VMIN] = BLOCK_SIZE;    /* blocking read until 5 chars received */
   
    tcflush(fd, TCIFLUSH); 
    tcsetattr(fd,TCSANOW,&options);
    return(TRUE);
}

int set_c_mode(int fd)
{
    struct termios options;
    if  ( tcgetattr( fd,&options)  !=  0){
          perror("SetupSerial 1");
          return(FALSE);
      }
    bzero(&options, sizeof(options));
    tcflush(fd, TCIOFLUSH);
    cfsetispeed(&options, BAUDRATE);
        cfsetospeed(&options, BAUDRATE);

    options.c_cflag |=(CLOCAL|CREAD);

    options.c_cflag &= ~CRTSCTS;

    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    options.c_cflag &= ~PARENB;  /* Clear parity enable,clear control mode flag */
    options.c_iflag &= ~INPCK;    /* Disable parity checking ,*/
    options.c_cflag &= ~CSTOPB;

    options.c_iflag |= IGNBRK;

    options.c_lflag |= ICANON;       
    options.c_lflag &= ~(ECHO | ECHOE | ISIG);
    options.c_oflag &= ~(OPOST);

    tcflush(fd, TCIOFLUSH);
      if (tcsetattr(fd,TCSANOW,&options) != 0){
          perror("SetupSerial 3");
        return (FALSE);
    }
    return(TRUE);
}
void send_ack(int fd)
{
    char buf[]={'A','C','K',CHANGE_LINE};
    write(fd,buf,sizeof(buf));
}
void resend(int fd)
{
    char buf[]={'R','S','D',CHANGE_LINE};
    write(fd,buf,sizeof(buf));
}
void delay(int i)
{
    int j;
    for (;i>0;i--)
        for(j=0;j<65535;j++);
}


////////////////////////////////////////////////////////////////////////////////////////////

SerialThread::SerialThread(MainWindow *parent){
    this->parent = parent;
}


void SerialThread::run()
{
    int fd,c, res;   
    int block_num,last_block;
    int i;   
    char buf[BLOCK_SIZE];             
    char file_name[32];
    FILE *fp;
    struct termios oldtio;

    block_num=last_block=0;
    fd = open(DEVICE, O_RDWR | O_NOCTTY ); 
   
    parent->setCounter(fd);
    parent->setMsgText("opend device fd::::::");   
   
   
    if (fd <0){
        perror(DEVICE); 
        parent->setMsgText("open device failed");   
    //    exit(-1); 
    }   
 
    tcgetattr(fd,&oldtio);
    set_nc_mode(fd);
    printf("Changed to nc mode\n");
    /*
    res=read(fd,( char *)file_name,32);
    parent->setCounter(res);
    parent->setMsgText("res is ::::::");   
    */

/*
   

    if(res>0){
        file_name[res-1]='\0';
        printf("Received the file name:%s\n",file_name);
        }
    else
        printf("The received file name is error.\n");

    fp=fopen(file_name,"wb");
    if(fp==NULL){
        printf("Can not creat file %s!\n",file_name);
        return;
    //    exit(-1);
        }
    else
        {
            send_ack(fd);
            printf("The file %s is created.\nWaitting for the block num and last block size\n",file_name);
        }

    //set_nc_mode(fd);
    //printf("Changed to nc mode\n");

    res=read(fd,buf,4);
    printf("res=%d\n",res);
    printf("Received the block num \n");

    for(i=0,block_num=0;i<4;i++){
        block_num=block_num*10+buf;
        printf("buf[%d]=%x\n",i,buf);
        }
    printf("The number of blocks is %d\n",block_num);
    send_ack(fd);

    res=read(fd,buf,3);
    printf("res=%d\n",res);
    printf("Received the last block size \n");
        for(i=0,last_block=0;i<3;i++){
                last_block=last_block*10+buf;
        printf("buf[%d]=%x\n",i,buf);
        }   
    printf("The last block size is %d\n",last_block);
    send_ack(fd);   

    printf("Starting receive blocks\n");

    for(i=0;i<block_num;i++){
        res=read(fd,buf,BLOCK_SIZE);
        if(res!=BLOCK_SIZE){
                        printf("res=%d,\t Request resend the %d block\n",res,i);
            i--;
                tcflush(fd, TCIOFLUSH);
            resend(fd);
            }
        else{           
            fwrite(buf,1,BLOCK_SIZE,fp);
            printf("Received the %d block,    res=%d\n",i,res);
            printf("Send ack signal complete,waiting to read\n");
            send_ack(fd);
            }
    }
    printf("start transporting the last block\n");

    if(last_block>0){
        send_ack(fd);
        res=read(fd,buf,last_block);
        printf("res=%d\n",res);
                if(res!=last_block){
            printf("Request resend the last block\n");
            tcflush(fd, TCIOFLUSH);
                        resend(fd);
                        }
        else
            fwrite(buf,1,last_block,fp);
        }
    send_ack(fd);
    printf("The file transports end\n");

    fclose(fp);
    printf("close the file\n");
    tcsetattr(fd,TCSANOW,&oldtio);
    close(fd);
    printf("close the serial port\n");
    */     
}

离线landuochong

只看该作者 1楼 发表于: 2008-01-10
高人,请问一下,qt哪个版本?3or4,
离线polaris
只看该作者 2楼 发表于: 2008-01-28
标准的posix  的事例代码的封装!
离线jam4466

只看该作者 3楼 发表于: 2008-04-22
请教:
为什么我编译有错呢??
In file included from mainwindow.cpp:13:
serialthread.h:7: parse error before `{' token
serialthread.h:10: virtual outside class declaration
serialthread.h:11: parse error before `private'
In file included from mainwindow.cpp:13:
serialthread.h:15:7: warning: no newline at end of file
mainwindow.cpp: In member function `void MainWindow::serialOperate()':
mainwindow.cpp:39: invalid use of undefined type `class SerialThread'
mainwindow.h:10: forward declaration of `class SerialThread'
mainwindow.cpp:40: invalid use of undefined type `class SerialThread'
mainwindow.h:10: forward declaration of `class SerialThread'
mainwindow.cpp:41: invalid use of undefined type `class SerialThread'
mainwindow.h:10: forward declaration of `class SerialThread'
make: *** [mainwindow.o] Error 1
离线wzc81614
只看该作者 4楼 发表于: 2008-04-28
同问!
离线liaoming
只看该作者 5楼 发表于: 2008-04-28
我也碰到这样的问题,我用的是QT2,不知道是不是版本的问题?
离线bull9god

只看该作者 6楼 发表于: 2008-04-28
哇塞,这么厉害,我以后要在qtopia上跑TCP/IP。没有头绪啊
离线lufengjie

只看该作者 7楼 发表于: 2008-05-15
引用第3楼jam4466于2008-04-22 11:44发表的  :
请教:
为什么我编译有错呢??
In file included from mainwindow.cpp:13:
serialthread.h:7: parse error before `{' token
serialthread.h:10: virtual outside class declaration
.......

我也是这个问题,怎么解决呢,我的是QTE3.3.8
离线lufengjie

只看该作者 8楼 发表于: 2008-05-15
引用第3楼jam4466于2008-04-22 11:44发表的  :
请教:
为什么我编译有错呢??
In file included from mainwindow.cpp:13:
serialthread.h:7: parse error before `{' token
serialthread.h:10: virtual outside class declaration
.......

我的QQ:13363958希望大家交流
离线huzhiwen28

只看该作者 9楼 发表于: 2008-08-22
学习了
http://blog.sina.com.cn/tonyhuzhiwen
https://github.com/huzhiwen28/
专注于工业嵌入设备开发
离线fzusuper
只看该作者 10楼 发表于: 2008-12-10
我也出现了这问题啊 怎么解决啊 给个提示或则给个链接啊
离线fzusuper
只看该作者 11楼 发表于: 2008-12-14
这个问题有谁知道如何解决吗?
离线zcgme

只看该作者 12楼 发表于: 2009-01-02
linux下 编译出来后 有很多警告  而且有点错位的样子

而且 paint.drawLine 画条斜线干嘛阿 
[ 此贴被zcgme在2009-01-02 23:52重新编辑 ]
离线malajisi
只看该作者 13楼 发表于: 2009-03-25
引用楼主tomoowang于2008-01-09 21:23发表的 qt串口编程 :
[serial.cpp]
#include <qapplication.h>
#include <qmainwindow.h>  
#include "mainwindow.h"
.......

ding!

you da 'an le? :)
离线wonderant
只看该作者 14楼 发表于: 2009-06-18
引用第3楼jam4466于2008-04-22 11:44发表的  :
请教:
为什么我编译有错呢??
In file included from mainwindow.cpp:13:
serialthread.h:7: parse error before `{' token
serialthread.h:10: virtual outside class declaration
.......


为什么呢?
请高人指教……
离线wonderant
只看该作者 15楼 发表于: 2009-06-18
请高人指点
离线wandersky
只看该作者 16楼 发表于: 2009-09-07
在  .pro 文件中加上 CONFIG          = qt warn_on release thread
添加thread就通过了。
156955694
离线hanfeng000
只看该作者 17楼 发表于: 2009-10-02
make
android 创意 开发论坛  www.android-zh.com
离线lifuchina
只看该作者 18楼 发表于: 2009-10-03
应该是使用的qt3,在QT4中编译的话加入QT3support就行了,
离线bryans

只看该作者 19楼 发表于: 2009-10-08
好东西,收藏了,
离线pear_2268

只看该作者 20楼 发表于: 2009-12-09
能运行,但是该代码是用linux下open函数进行串口通信的,有没有使用qextserialport的啊?
离线fjutwx
只看该作者 21楼 发表于: 2009-12-18
直接用qextserialport,posix的,
离线帅坤
只看该作者 22楼 发表于: 2010-04-20
引用第3楼jam4466于2008-04-22 11:44发表的  :
请教:
为什么我编译有错呢??
In file included from mainwindow.cpp:13:
serialthread.h:7: parse error before `{' token
serialthread.h:10: virtual outside class declaration
.......

想知道用的是什么版本,我用的是QT2,也出现了上面提到的问题,而且在.pro文件中加了thread也还是会出错,是说write没有声明,还有run函数中定义的变量都没有被使用。不知道怎么弄,是环境变量没有设置对吗?还是QT没安装好啊?希望能帮帮忙。
对了,还有程序中注释掉的那部分代码没有用吗?
我是初学者,对C++也不是很熟,所以恳请大侠帮帮忙,解释一下。
离线帅坤
只看该作者 23楼 发表于: 2010-04-21
引用第12楼zcgme于2009-01-02 23:31发表的  :
[表情] linux下 编译出来后 有很多警告  而且有点错位的样子
而且 paint.drawLine 画条斜线干嘛阿 


刚刚的那个问题解决了,是在serialthead.cpp中,添加#include <unistd.h>,还有虚函数run中有两处的buf好像没有用对,可能需要加上*才可以,还有一个定义的int c,这个变量没用到,应该删掉。
这样就可以编译成功了,不过,运行的结果就是我上面引用的问题。不知道这个应该怎么解决,那位大侠能帮忙解决一下啊?
离线jinxukangyi
只看该作者 24楼 发表于: 2011-03-23
以上这些问题有没有解决了的?
天道酬勤
快速回复
限100 字节
 
上一个 下一个