PDA

View Full Version : Read data from serial port



hoangnguyen
5th September 2017, 06:17
hello everyone, i'm newbie in qt and please excuse me for my English . I'm writing code to receive data from se i have 5 byte data from serial device and i want to save each in a value then print it. example my device sends a string "fet" and it prints "fet" on window but i want print one character 'f' or 'e' ... thank you
12574

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtSerialPort>
#include <QtSerialPort/qserialport.h>
#include <QDebug>

QSerialPort *serialPort;

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{

ui->setupUi(this);
serialPort = new QSerialPort(this);
serialPort->setPortName("com1");
serialPort->setBaudRate(QSerialPort::Baud9600);
serialPort->setDataBits(QSerialPort::Data8);
serialPort->setParity(QSerialPort::NoParity);
serialPort->setStopBits(QSerialPort::OneStop);
serialPort->open(QIODevice::ReadWrite);
connect(serialPort,SIGNAL(readyRead()),this,SLOT(P utData()));
}

MainWindow::~MainWindow()
{
delete ui;
serialPort->close();
}

void MainWindow::on_Send_clicked()
{
serialPort->write(ui->SendEdit->text().toStdString().data());

}

void MainWindow::PutData()
{
//ui->Receive->clear();
QByteArray data;
data=serialPort->readAll();
//sleep(1);
ui->Receive->insertPlainText(data);
}

void MainWindow::on_Clear_clicked()
{
ui->Receive->clear();
}

ado130
5th September 2017, 07:30
Did you check QByteArray doc? http://doc.qt.io/qt-4.8/qbytearray.html#operator-5b-5d