简体   繁体   中英

QtSerialPort communication issue

QSerialPort *serial;
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    serial = new QSerialPort(this);
    serial->setPortName("/dev/ttyUSB0");
    serial->setBaudRate(QSerialPort::Baud9600);
    serial->setStopBits(QSerialPort::OneStop);
    serial->setParity(QSerialPort::NoParity);
    serial->setDataBits(QSerialPort::Data8);
    serial->setFlowControl(QSerialPort::NoFlowControl);
    serial->open(QIODevice::ReadWrite);
    connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(serialReceived())); 
    connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(serialSent()));
}

MainWindow::~MainWindow()
{
    delete ui;
    serial->close();
}
void MainWindow::serialReceived()
{
    ui->label->setText(serial->readAll());
}
void MainWindow::serialSent()
{
    QByteArray bytes;
    serial->write(bytes);
}

From this code I 've run in qt on Ubuntu. It show QIOdevice::write device not open. But I already plug my usb to serial on this port how can I solve this problem.

1) In ubuntu for access to serial port you must have the right permission. Try to run your code with sudo command.

2) The various settings for serial port must be done after that the port was opened, change your code like this:

serial->setPortName("/dev/ttyUSB0");
if(serial->open(QIODevice::ReadWrite){
   serial->setBaudRate(QSerialPort::Baud9600);
   serial->setStopBits(QSerialPort::OneStop);
   serial->setParity(QSerialPort::NoParity);
   serial->setDataBits(QSerialPort::Data8);
   serial->setFlowControl(QSerialPort::NoFlowControl);
}

Every settings can return true or false. Correct way is check everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM