2017-04-04 47 views
2
#include <QSerialPort> 
#include <QSerialPortInfo> 
int main(int argc, char *argv[]) 
{ 
    QCoreApplication a(argc, argv); 

    // Example use QSerialPortInfo 
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { 

     // Example use QSerialPort 
     QSerialPort serial; 
     serial.setPort(info); 
     if (serial.open(QIODevice::ReadWrite)) 
      //I try to send a string of hexadecimal numbers,seems not right 
      //serial.write(QByteArray("0xFF010100FFFFFF")); 
      serial.close(); 
    } 

    return a.exec(); 
} 

上面的示例顯示瞭如何打開所有可用的串行端口,然後關閉它們。但是我想打開給定的串口,例如COM6,設置其BaudRate,DataBits,Parity,StopBits,FlowControl,然後發送一串十六進制數字。如何用qt將數據寫入給定的串口?

回答

3

這部影片一定會幫助你:https://www.youtube.com/watch?v=UD78xyKbrfk

你也可以在這裏找到類似的代碼:https://cboard.cprogramming.com/cplusplus-programming/169624-read-write-serial-port.html

示例代碼:

#include <QSerialPort> 

MySerialPort::MySerialPort() 
{ 
    serial = new QSerialPort(this); 
    openSerialPort(); 
}  

void MySerialPort::openSerialPort() 
{ 
    serial->setPortName("COM3"); 
    serial->setBaudRate(QSerialPort::Baud9600); 
    serial->setDataBits(QSerialPort::Data8); 
    serial->setParity(QSerialPort::NoParity); 
    serial->setStopBits(QSerialPort::OneStop); 
    serial->setFlowControl(QSerialPort::NoFlowControl); 

    if (serial->open(QIODevice::ReadWrite)) 
    {  
     //Connected  
    } 
    else 
    {  
     //Open error 
    } 
}  

void MySerialPort::writeData(const QByteArray &data) 
{ 
    serial->write(data); 
} 
+1

請不要張貼鏈接,只有答案。提供一些包含在這些鏈接中的信息。看[如何寫出一個好答案](http://stackoverflow.com/help/how-to-answer)。 – thuga

+0

@thuga感謝您的建議 – ni1ight