Unsolved Serial Port : Unique Read Error
-
My application is simple i need to wire and read data to serial port.
When ever i write "1" on the serial port, the microcontroller receives the "1" and send the 8 bytes of data.
Also i have four buttons, when the buttons clicked one byte of data is sent to microcontoller based on the button pressed.
My problem is when ever i reading the data from serial port the buttons are not working and ........ if buttons are working then i cant read data from the port.
Kindly suggest the solutions,this is my code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include "QThread"
#include <QReadWriteLock>
QSerialPort *serial;QReadWriteLock inv;
int numRead = 0,bytesToRead;
char buffer[8];
QString str;MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
serial = new QSerialPort(this);
serial->setPortName("COM6");
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
serial->open(QIODevice::ReadWrite);
serial->write("1",1);
connect(serial,SIGNAL(readyRead()),this,SLOT(serialReceived()));
MainWindow::updatelcd(str);}
MainWindow::~MainWindow()
{
delete ui;
serial->close();
}
void MainWindow::serialReceived()
{
serial->write("1",1);
if((serial->bytesAvailable()==8))
{
QByteArray data = serial->readAll();
str=data;
//MainWindow::updatelcd(str);
}//MainWindow::updatelcd(str); /*if((serial->canReadLine())) { numRead = serial->readLine(buffer, 8); str=buffer; MainWindow::updatelcd(str); //QThread::msleep(10);
}*/
}
void MainWindow::updatelcd(const QString sdata)
{
ui->lcdNumber->display(sdata);
}void MainWindow::on_pushButton_clicked()
{
serial->write("2",1);
}void MainWindow::on_pushButton_2_clicked()
{
serial->write("3",1);
}void MainWindow::on_pushButton_3_clicked()
{
serial->write("4",1);
}void MainWindow::on_pushButton_4_clicked()
{
serial->write("5",1);
} -
@Dhinesh said:
HI and welcome
The signal readyRead (serialReceived) is sent when QSerialPort reads some data.
Try to not call serial->write("1",1); in your serialReceived
as it might make controller send more data and it might never get out of there.
(end less loop) as its called pretty fast.Else they code seems fine.
Maybe say
QByteArray data.append( serial->readAll());
(and move QByteArray data to MainWindow.h)
and then when data.size() == 8 then
DOSTUFF
data.clear();