⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serial.cpp~

📁 PXA270的串口调试程序
💻 CPP~
字号:
#include "serialform.h"#include "serial.h"#include <qcombobox.h>#include <qframe.h>#include <qlabel.h>#include <qlineedit.h>#include <qmultilineedit.h>#include <qpushbutton.h>#include <qlayout.h>#include <qvariant.h>#include <qtooltip.h>#include <qwhatsthis.h>#include <qimage.h>#include <qpixmap.h>#include <qpushbutton.h>#include <qimage.h>#include <qpixmap.h>#include <qmessagebox.h>#include <qdir.h>#include <qfile.h>#include <qfiledialog.h>#include <qtimer.h>#include <qtextstream.h>#include <qcursor.h>#include <qtooltip.h>// some .h files used for serial port programming#include  <stdio.h>#include  <stdlib.h>#include  <unistd.h>#include  <sys/types.h>#include <sys/signal.h>#include  <sys/stat.h>#include  <fcntl.h>#include  <termios.h>#include  <errno.h>#include <limits.h>static struct termios termios_old, termios_new;static fd_set   fs_write;static struct timeval tv_timeout;Serial::Serial( QWidget* parent,  const char* name, bool modal, WFlags fl )    : Serial_Form( parent, name, modal, fl ){    serialfd=-1;    ReadComTimer = new QTimer(this);                                    //Read Com Port Timer    Baudrate_Combobox->setCurrentItem(1);    Serialport_Combobox->setCurrentItem(0);    E_obits_Combobox->setCurrentItem(2);    Stopbits_Combobox->setCurrentItem(0);    Databits_Combobox->setCurrentItem(0);        Portsel=Serialport_Combobox->currentItem();    Ratesel=Baudrate_Combobox->currentItem();    EvenOddsel=E_obits_Combobox->currentItem();    StopBitsel=Stopbits_Combobox->currentItem();    DataBitsel=Databits_Combobox->currentItem();        // connection of the bottons    connect( Exit_Botton, SIGNAL( clicked() ), SLOT( close() ) );    connect( About_Botton, SIGNAL( clicked() ), SLOT( AboutShow() ) );    connect( Openfile_Botton, SIGNAL( clicked() ),  SLOT( OpenFile() ) );    connect( Sendfile_Botton, SIGNAL( clicked() ),  SLOT( SendFile() ) );    connect( Modify_Botton, SIGNAL( clicked() ), SLOT( ModifyPath() ) );    connect( Savedisplay_Botton, SIGNAL( clicked() ), SLOT( SaveDiplayData() ) );    connect( Openport_Botton, SIGNAL( clicked() ), SLOT( OpenPort() ) );    connect( Manul_Botton, SIGNAL( clicked() ), SLOT( ManulSend() ) );    connect( Cleardisplay_Botton, SIGNAL( clicked() ), SLOT( ClearDisplay() ) );        // connection of the comboboxes    connect( Databits_Combobox, SIGNAL( activated(int) ), SLOT( DatabitsChange(int) ) );    connect( E_obits_Combobox, SIGNAL( activated(int) ), SLOT( EvenoddChange(int) ) );    connect( Serialport_Combobox, SIGNAL( activated(int) ),  SLOT( SerialportChange(int) ) );    connect( Stopbits_Combobox, SIGNAL( activated(int) ), SLOT( StopbitsChange(int) ) );    connect( Baudrate_Combobox, SIGNAL( activated(int) ), SLOT( BaudrateChange(int) ) );    // connection of timeout    connect( ReadComTimer,SIGNAL(timeout()), SLOT(ReadComPort()));}Serial::~Serial(){}void Serial::OpenFile(){/*    QString filename= QFileDialog::getOpenFileName("/root",QString::null,this,"Open File Dialog","Choose a File to Open");    if( !filename.isEmpty() )        {	        QFile f(filename);	        if(!f.open(IO_ReadOnly))	            return;	        Transmit_Mulitlineedit->clear( );	        QTextStream t( &f );	        while(!t.eof())	            {	                QString s=t.readLine();	                Transmit_Mulitlineedit->append(s);                }            f.close();            Filepath_Textlabel->setText(filename);        }*/}int Serial::WriteComPort (const char *data, int datalength)                     //  ?{    int buflen, baud ,retval, len = 0, total_len = 0;    FD_ZERO (&fs_write);    FD_SET (serialfd, &fs_write);    baud = GetBaudRate();    buflen= datalength ;    tv_timeout.tv_sec =  ( (buflen*20)/baud ) + 2  ;    tv_timeout.tv_usec = 0 ;    //tv_timeout.tv_sec = TIMEOUT_SEC( buflen, baud );                 //modify    //tv_timeout.tv_usec = TIMEOUT_USEC;    for (total_len = 0, len = 0; total_len < datalength;)    {        retval = select (serialfd + 1, NULL, &fs_write, NULL, &tv_timeout);        if (retval)	{	    len = ::write(serialfd, &data[total_len], datalength - total_len);            if (len > 0)                total_len += len;        }        else	{            tcflush (serialfd, TCOFLUSH);     /* flush all output data */            break;        }    }    return (total_len);}void Serial::SendFile(){    QString str=Filepath_Textlabel->text() ;    const char *path;    int total_len=0;    Sendfile_Botton->setCursor( QCursor( WaitCursor ) );    if(serialfd<0)	    QMessageBox::information(this,"Information","Port isn't opened");    else        {            path=str.latin1();            total_len=SendComFile( path );            if (total_len<0)		        QMessageBox::information(this,"Information","Send Error");		     else		        {			        Sendfile_Botton->setCursor( QCursor( 13 ) );			        QString str;			        str=str.setNum(total_len);			        str="Send Over , Send bytes is "+ str;			        QMessageBox::information(this,"Information",str);		        }	    }}int Serial::SendComFile( const char *path ){    int fd, buflen;    int total_len , len_tmp;    total_len=0; len_tmp=0;    QString pathname(path);    char buf[BUFFER_LEN+1];    QFile f(pathname);    fd=f.open(IO_ReadOnly);    if( fd<0)        {	        QMessageBox::information(this,"Information","File open error");	        return (-1);        }        while(!f.atEnd())        {	        bzero(buf, sizeof(buf));	        buflen = f.readLine(buf,sizeof(buf));	        if (buflen == 0)	            {	                f.close();	                break;	            }	        buf[buflen]=0;	        len_tmp=WriteComPort( buf , buflen );	        if( len_tmp !=buflen )	            {	                QMessageBox::information(this,"Information","Write error");	                f.close();	                return (-1);	            }	        else	            total_len+=len_tmp;        }    f.close();    return (total_len);          }void Serial::AboutShow(){    QMessageBox::about(this,"About...","a simple serial wiget");}void Serial::ModifyPath(){    Recieve_Multilineedit->clear();}void Serial::OpenPort(){    QString caption;    int retval;    caption=Openport_Botton->text();    ReadComTimer->stop();    if(caption.find("Open",0,FALSE)>=0)        {	        Openport_Botton->setText("Close Port");	        serialfd=OpenSerialPort(Portsel);	                                    // Open com port	        QPixmap bg = QPixmap(QDir::currentDirPath()+"/greed.png");	        Portstauts_Pixmap->setPixmap( bg );	        if(serialfd<0)	            QMessageBox::information(this,"Information","Cannt Open Serial Port");	        else	            {	                retval=SetSerialPara(DataBitsel , StopBitsel , EvenOddsel , Ratesel);	                ReadComTimer->start(10);	            }        }    else        {	        Openport_Botton->setText("Open Port");	        QPixmap bg = QPixmap(QDir::currentDirPath()+"/red.png");	        Portstauts_Pixmap->setPixmap(bg);	        if(serialfd>0)	            CloseComPort();        }}void Serial::CloseComPort(){    tcsetattr (serialfd, TCSADRAIN, &termios_old);    ::close (serialfd);    serialfd=-1;}void Serial::ManulSend(){    int len;    const char *strchar;    if(serialfd>0)        {	        QString str=Transmit_Mulitlineedit->text();	        len=str.length();	        if(!str.isEmpty())	            {	                strchar=str.latin1();	                if(WriteComPort(strchar,len)!=len)	                    QMessageBox::information(this,"information","write Error");	            }	        else	            QMessageBox::information(this,"Information","Send context is Empty");         }    else	    QMessageBox::information(this,"Information","Serial Port is not Opened");}void Serial::SerialportChange(int){    Portsel=Serialport_Combobox->currentItem();}void Serial::BaudrateChange(int){    Ratesel=Baudrate_Combobox->currentItem();}void Serial::DatabitsChange(int){    DataBitsel=Databits_Combobox->currentItem();}void Serial::StopbitsChange(int){    StopBitsel=Stopbits_Combobox->currentItem();}void Serial::EvenoddChange(int){    EvenOddsel=E_obits_Combobox->currentItem();}void Serial::SaveDiplayData(){    qWarning( "frmserial::SaveDiplayData(): Not implemented yet" );}void Serial::ClearDisplay(){    Transmit_Mulitlineedit->clear();    Filepath_Textlabel->clear();}int  Serial::OpenSerialPort(int index){    char *device;    switch(index)        {        case 0:	        device="/dev/ttyS0";	        break;        case 1:	        device="/dev/ttyS1";	        break;        case 2:	        device="/dev/ttyS2";	        break;        case 3:	        device="/dev/ttyS3";	        break;         default:	        device="/dev/ttyS0";        }    int fd=open( device, O_RDWR | O_NOCTTY | O_NONBLOCK);    if ( fd<0 )        {	        QMessageBox::information(this,"Information","Can't Open the Serial Port");	        return -1;        }    tcgetattr(fd , &termios_old);    return fd;}int Serial::SetSerialPara(int databits , int stopbits ,int parity, int speed){    bzero( &termios_new, sizeof(termios_new));    cfmakeraw(&termios_new);    termios_new.c_cflag=BaudRate(speed);    termios_new.c_cflag |= CLOCAL | CREAD;    termios_new.c_cflag &= ~CSIZE;    switch (databits) //    {    case 0:	termios_new.c_cflag |= CS8;	break;    case 1:	termios_new.c_cflag |= CS7;	break;    case 2:	termios_new.c_cflag |= CS6;	break;    case 3:	termios_new.c_cflag |= CS5;	break;    default:	termios_new.c_cflag |= CS8;	break;    }    switch (parity) //    {    case 0:	termios_new.c_cflag |= PARENB;     // Enable parity	termios_new.c_cflag &= ~PARODD;	break;    case 1:	termios_new.c_cflag |= PARENB;	termios_new.c_cflag |= ~PARODD;	break;    case 2:  				//as no parity	termios_new.c_cflag &= ~PARENB;    //Clear parity enable	break;    default:	termios_new.c_cflag &= ~PARENB;   // Clear parity enable	break;    }    switch (stopbits)// set Stop Bit    {    case 0:	termios_new.c_cflag &= ~CSTOPB;	break;    case 1:	termios_new.c_cflag |= CSTOPB;	break;    default:	termios_new.c_cflag &= ~CSTOPB;	break;    }    tcflush(serialfd,TCIFLUSH); // Update the termios_new and do it NOW    termios_new.c_cc[VTIME] = 1; /* unit: 1/10 second. */    termios_new.c_cc[VMIN] = 1; /* minimal characters for reading */    tcflush (serialfd, TCIFLUSH);    return tcsetattr(serialfd,TCSANOW,&termios_new);}int Serial::BaudRate( int baudrate){    switch(baudrate)        {        case 0:	        return (B4800);        case 1:	        return (B9600);        case 2:	        return (B19200);        case 3:	        return (B38400);        case 4:	        return (B57600);        case 5:	        return (B115200);        default:	        return (B9600);        }}int Serial::_BaudRate(int baudrate){    switch(baudrate)        {        case B4800:	        return (4800);        case B9600:	        return (9600);        case B19200:	        return (19200);        case B38400:	        return (38400);        case B57600:	        return (57600);        case B115200:	        return (115200);        default:	        return (9600);        }}int Serial::GetBaudRate(){    return ( _BaudRate( cfgetospeed( &termios_new ) ) );}void Serial::ReadComPort(){   char recvbuf [ BUFFER_LEN+1 ] ;   int buflen= -1;    if(serialfd>0)    {       buflen=::read (serialfd, recvbuf, BUFFER_LEN);       if (buflen>0)            {	            recvbuf[buflen]=0;	            QString str(recvbuf);	            Recieve_Multilineedit->insert(str);            }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -