PDA

View Full Version : read data from serial port and display it



vanduongbk
30th June 2013, 03:34
hi everyone
i have write a simple code to read and display data that received from serial port with qextserialport ,i have compiler without any error but nothing was execute,plz solve it hep me
this's my code


#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qextserialport.h>
#include "stdlib.h"
#include "stdio.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QextSerialPort * port = new QextSerialPort("COM2");
port->setBaudRate(BAUD115200);
port->setDataBits(DATA_8);
port->setParity(PAR_NONE);
port->setStopBits(STOP_1);
port->setFlowControl(FLOW_OFF);
port->open(QextSerialPort::ReadWrite);
//while(1)
//{
char buff[1024];
int bytesToRead = port->bytesAvailable();
int result = (int)port->read(buff,bytesToRead);
buff[result];
char byte1[3];
char byte2[3];
byte1[0] = buff[0];
byte1[1] = buff[1];
byte1[2] = buff[2];
byte2[0] = buff[3];
byte2[1] = buff[4];
byte2[2] = buff[5];
long int B1=byte1[0]<<16|byte1[1]<<8|byte1[2];
long int B2=byte2[0]<<16|byte2[1]<<8|byte2[2];
long int C1;
long int C2;
char * next;
C1 = strtol(byte1,&next,16);
C2 = strtol(byte2,&next,16);
ui->lcdNumber->display(B1);
ui->lcdNumber_2->display(B2);
ui->lcdNumber_3->display(C1);
ui->lcdNumber_4->display(C2);
//}
}

MainWindow::~MainWindow()
{
delete ui;

}


when i run it without send any data ,lcdnumber display is -6378 and lcdnumber2 dispaly is 4864 and lcdnumber 3,4 is 0,
but when i send data 0x10 0x20 0x30 0x40 0x50 0x60 ,it do have any changed in lcdnumber ...
please help me

ChrisW67
30th June 2013, 03:46
The various Qt serial port libraries all operate asynchronously and require the Qt event loop to be running to receive data. Inside the constructor the event loop is not processing, so you receive nothing, and consequently nothing useful comes out of your remaining code. If you uncommented the while() loop your program will hang. The receive code should be in a slot connected to one of the QextSerialPort signals not in the constructor.

Your remaining code is curious and asking to crash too, but one problem at a time.