⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.cpp

📁 Visual C++串口通信开发入门与编程实践
💻 CPP
字号:
#include <QtCore>
#include <QCoreApplication>
#include <iostream>
using namespace std;

#include "qextserialport.h"
#include "uithread.h"



void UIThread::receive()
{
	cout << "data received: ";
	int bytesRead = port->read(data, BUFFER_SIZE);
	data[bytesRead] = '\0';
	cout << data << " (" << bytesRead << " bytes)" << endl;
}

void UIThread::reportWritten(qint64 bytes)
{
	cout << bytes << " bytes written" << endl;
}

void UIThread::reportClose()
{
	cout << "closing port" << endl;
}

void UIThread::reportDsr(bool status)
{
	if (status)
		cout << "device was turned on" << endl;
	else
		cout << "device was turned off" << endl;
}

UIThread::UIThread( QextSerialPort * port, QObject * parent /*= 0*/ ) :
QThread(parent)
{
	this->port = port;
}

void UIThread::run()
{
	QTextStream in(stdin);
	QString inStr;
	cout << "Special commands: open close bye" << endl << endl;
	while(inStr.compare("bye") != 0) {
		in >> inStr;
		if (inStr.compare("close") == 0) {
			cout << "requesting close... " << endl; 
			port->close();
		}
		else if (inStr.compare("open") == 0) {
			cout << "opening port... ";
			cout << port->open(QIODevice::ReadWrite);
			cout << endl;
		} else if (inStr.compare("bye") != 0)
			port->write(qPrintable(inStr), inStr.length());
	}
	port->close();
}
int main(int argc, char *argv[])
{

	QCoreApplication app(argc, argv);

	QextSerialPort * port = new QextSerialPort("COM1", QextSerialPort::EventDriven);
	port->setBaudRate(BAUD9600);
	port->setFlowControl(FLOW_OFF);
	port->setParity(PAR_NONE);
	port->setDataBits(DATA_8);
	port->setStopBits(STOP_1);
	port->open(QIODevice::ReadWrite);
	if (!(port->lineStatus() & LS_DSR)) {
		cout << "warning: device may not turned on" << endl;
	}

	UIThread * thread = new UIThread(port);
	app.connect(port, SIGNAL(readyRead()), thread, SLOT(receive()));
	app.connect(port, SIGNAL(bytesWritten(qint64)), thread, SLOT(reportWritten(qint64)));
	app.connect(port, SIGNAL(aboutToClose()), thread, SLOT(reportClose()));
	app.connect(port, SIGNAL(dsrChanged(bool)), thread, SLOT(reportDsr(bool)));


	app.connect(thread, SIGNAL(finished()), & app, SLOT(quit()));
	thread->start();

	return app.exec();
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -