本文整理汇总了C++中QSerialPort::close方法的典型用法代码示例。如果您正苦于以下问题:C++ QSerialPort::close方法的具体用法?C++ QSerialPort::close怎么用?C++ QSerialPort::close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QSerialPort
的用法示例。
在下文中一共展示了QSerialPort::close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: discover
/**
* This functions takes a serial port and tries if it can find a Kettler bike connected
* to it.
*/
bool Kettler::discover(QString portName)
{
bool found = false;
QSerialPort sp;
sp.setPortName(portName);
if (sp.open(QSerialPort::ReadWrite))
{
m_kettlerConnection.configurePort(&sp);
// Discard any existing data
QByteArray data = sp.readAll();
// Read id from bike
sp.write("cd\r\n");
sp.waitForBytesWritten(500);
QByteArray reply = sp.readAll();
reply.append('\0');
QString replyString(reply);
if (replyString.startsWith("ACK") || replyString.startsWith("RUN"))
{
found = true;
}
}
sp.close();
return found;
}
示例2: initPort
void MainWindow::initPort()
{
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()){
QSerialPort serialtmp;
serialtmp.setPort(info);
/* 判断端口是否能打开 */
if(serialtmp.open(QIODevice::ReadWrite))
{
int isHaveItemInList = 0;
/* 判断是不是已经在列表中了 */
for(int i=0; i<ui->portNameCombo->count(); i++)
{
/* 如果,已经在列表中了,那么不添加这一项了就 */
if(ui->portNameCombo->itemData(i) == serialtmp.portName())
{
isHaveItemInList++;
}
}
if(isHaveItemInList == 0)
{
ui->portNameCombo->addItem(serialtmp.portName());
}
serialtmp.close();
}
}
示例3: getPortSettings
PortSettings PositioningMethodSerialPortOptions::getPortSettings(const QString &APortName)
{
PortSettings portSettings;
OptionsNode node;
if (Options::hasNode(OPV_POSITIONING_METHOD_SERIALPORT, APortName))
node = Options::node(OPV_POSITIONING_METHOD_SERIALPORT, APortName);
else
{
QSerialPort *serialPort = new QSerialPort(APortName);
if (serialPort->open(QIODevice::ReadOnly))
{
portSettings.FBaudRate = serialPort->baudRate();
portSettings.FDataBits = serialPort->dataBits();
portSettings.FStopBits = serialPort->stopBits();
portSettings.FParity = serialPort->parity();
portSettings.FFlowControl = serialPort->flowControl();
serialPort->close();
}
else // Failed to open the port
node = Options::node(OPV_POSITIONING_METHOD_SERIALPORT, APortName);
serialPort->deleteLater();
}
if (!node.isNull())
{
portSettings.FBaudRate = node.value("baud-rate").toLongLong();
portSettings.FDataBits = (QSerialPort::DataBits)node.value("data-bits").toInt();
portSettings.FStopBits = (QSerialPort::StopBits)node.value("stop-bits").toInt();
portSettings.FParity = (QSerialPort::Parity)node.value("parity").toInt();
portSettings.FFlowControl = (QSerialPort::FlowControl)node.value("flow-control").toInt();
}
return portSettings;
}
示例4: SerialDisconnect
bool SerialCommunication::SerialDisconnect()
{ // serial disconnect
if (serial.isOpen())
{
serial.close();
return true;
}
return false;
}
示例5: on_connectAction_triggered
void MainWindow::on_connectAction_triggered(bool connect)
{
if(connect)
{
ConnectDialog dlg(this);
if(dlg.exec() == QDialog::Accepted)
{
if(dlg.connectionType() == Serial)
{
QSerialPort* serialPort = new QSerialPort(this);
_ioDevice = serialPort;
serialPort->setPort( dlg.serialPortInfo());
if(serialPort->open(QIODevice::ReadWrite))
{
// TODO hardcoded settings
if(!serialPort->setBaudRate(QSerialPort::Baud115200) ||
!serialPort->setDataBits(QSerialPort::Data8) ||
!serialPort->setParity(QSerialPort::NoParity) ||
!serialPort->setFlowControl(QSerialPort::NoFlowControl) ||
!serialPort->setStopBits(QSerialPort::TwoStop))
{
serialPort->close();
QMessageBox::critical(this, "Logger", "Can't configure serial port, reason: " + serialErrorString());
return;
}
}
else
{
QMessageBox::critical(this, "Logger", "Serial port connection failed, reason: " + serialErrorString(), QMessageBox::Ok);
return;
}
}
else if(dlg.connectionType() == File)
{
QFile* file = new QFile(dlg.fileName(), this);
_ioDevice = file;
}
_logParser = new LogParser(_ioDevice, this);
QObject::connect(_logParser, SIGNAL(logMessageReceived(QString)), SLOT(onLogMessageReceived(QString)));
QObject::connect(_logParser, SIGNAL(packetParsed(Packet)), SLOT(onPacketParsed(Packet)));
_logParser->setParent(0);
_logParser->moveToThread(_parserThread);
_parserThread->start();
_logParser->openDevice();
}
}
else
{
_ioDevice->close();
}
updateStatus();
}
示例6: GetSerialport
void SerialSetup::GetSerialport()
{
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
qDebug() << "Name : " << info.portName();
QSerialPort serial;
serial.setPort(info);
if (serial.open(QIODevice::ReadWrite))
{
serial.close();
ui->SerialPort->addItem(info.portName());
}
}
示例7: discover
/**
* This functions takes a serial port and tries if it can find a Monark bike connected
* to it.
*/
bool MonarkConnection::discover(QString portName)
{
bool found = false;
QSerialPort sp;
sp.setPortName(portName);
if (sp.open(QSerialPort::ReadWrite))
{
configurePort(&sp);
// Discard any existing data
QByteArray data = sp.readAll();
// Read id from bike
sp.write("id\r");
sp.waitForBytesWritten(-1);
QByteArray id;
do
{
bool readyToRead = sp.waitForReadyRead(1000);
if (readyToRead)
{
id.append(sp.readAll());
} else {
id.append('\r');
}
} while ((id.indexOf('\r') == -1));
id.replace("\r", "\0");
// Should check for all bike ids known to use this protocol
if (QString(id).toLower().contains("lt") ||
QString(id).toLower().contains("lc") ||
QString(id).toLower().contains("novo")) {
found = true;
}
}
sp.close();
return found;
}
示例8: main
int main(int argc, char **argv)
{
ros::init(argc, argv, "nav");
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise<mini::naviLoc>("navmsg", 1);
QSerialPort sp;
sp.setPortName("/dev/ttyS4");
sp.setBaudRate(QSerialPort::Baud115200);
sp.setDataBits(QSerialPort::Data8);
sp.setParity(QSerialPort::NoParity);
sp.setStopBits(QSerialPort::OneStop);
sp.open(QIODevice::ReadWrite);
int data_len = 10;
char rcv_buf[100];
FILE* fp = fopen("/home/haha/catkin_ws/odom.txt","w");
int ret;
while (ros::ok())
{
mini::naviLoc msg;
struct timeval tv;
int ret;
while(1)
{
//ROS_INFO(" ");
ret = sp.read(rcv_buf,1);
//ROS_INFO("[%d]",ret);
//usleep(10000);
if(ret==1)
{
//ROS_INFO("[%02X]",rcv_buf[0]);
}
if(ret==1 && rcv_buf[0]==char(0xA2))
{
break;
}
}
int counter = 1;
while(counter<data_len)
{
//ROS_INFO(" ");
ret = sp.read(&rcv_buf[counter],1);
//ROS_INFO("[%d]",ret);
if(ret!=1)
{
continue;
}
counter++;
}
gettimeofday(&tv,0);
if(rcv_buf[data_len-1]!=char(0x2A))
{
continue;
}
unsigned int timeStamp = tv.tv_sec%100000*1000+tv.tv_usec/1000;
SerialData2Msg(timeStamp, rcv_buf, data_len, msg);
chatter_pub.publish(msg);
//ROS_INFO("[%d],[%f],[%f],[%f]",msg.timestamp,msg.x,msg.y,msg.theta);
//fprintf(fp,"%d %f %f %f\n",msg.timestamp,msg.x,msg.y,msg.theta);
//fflush(fp);
ros::spinOnce();
//usleep(20000);
}
sp.close();
fclose(fp);
return 0;
}
示例9: run
//! [4]
void MasterThread::run()
{
bool currentPortNameChanged = false;
mutex.lock();
//! [4] //! [5]
QString currentPortName;
quint32 currentBaudRate;
QSerialPort::DataBits currentDataBits;
QSerialPort::Parity currentParity;
QSerialPort::StopBits currentStopBits;
QSerialPort::FlowControl currentFlowControl;
if ((currentPortName != portName) ||
(currentBaudRate != baudRate) ||
(currentDataBits != dataBits) ||
(currentParity != parity) ||
(currentStopBits != stopBits) ||
(currentFlowControl != flowControl))
{
currentPortName = portName;
currentBaudRate = baudRate;
currentDataBits = dataBits;
currentParity = parity;
currentStopBits = stopBits;
currentFlowControl = flowControl;
currentPortNameChanged = true;
}
QString currentRequest = request;
mutex.unlock();
//! [5] //! [6]
QSerialPort serial;
while (!quit) {
//![6] //! [7]
if (currentPortNameChanged) {
serial.close();
serial.setPortName(currentPortName);
if (!serial.open(QIODevice::ReadWrite)) {
emit error(tr("Не удалось подключиться к порту %1, код ошибки %2")
.arg(portName).arg(serial.error()));
return;
}
// if (!serial.setBaudRate(QSerialPort::Baud9600)) {
if (!serial.setBaudRate(currentBaudRate)) {
emit error(tr("Не удалось установить скорость для порта %1, код ошибки %2")
.arg(portName).arg(serial.error()));
return;
}
// if (!serial.setDataBits(QSerialPort::Data8)) {
if (!serial.setDataBits(currentDataBits)) {
emit error(tr("Не удалось установить количество бит для порта %1, код ошибки %2")
.arg(portName).arg(serial.error()));
return;
}
// if (!serial.setParity(QSerialPort::NoParity)) {
if (!serial.setParity(currentParity)) {
emit error(tr("Не удалось установить четность для порта %1, код ошибки %2")
.arg(portName).arg(serial.error()));
return;
}
// if (!serial.setStopBits(QSerialPort::OneStop)) {
if (!serial.setStopBits(currentStopBits)) {
emit error(tr("Не удалось установить стоповый бит для порта %1, код ошибки %2")
.arg(portName).arg(serial.error()));
return;
}
// if (!serial.setFlowControl(QSerialPort::NoFlowControl)) {
if (!serial.setFlowControl(currentFlowControl)) {
emit error(tr("Не удалось установить контроль четности для порта %1, код ошибки %2")
.arg(portName).arg(serial.error()));
return;
}
}
QByteArray requestData = 0;
StringToByteArray(currentRequest, requestData);
serial.write(requestData);
if (serial.waitForBytesWritten(WAIT_TIMEOUT)) {
// read response
if (serial.waitForReadyRead(WAIT_TIMEOUT)) {
QByteArray responseData = serial.readAll();
while (serial.waitForReadyRead(10))
responseData += serial.readAll();
QString response(responseData);
emit this->response(response);
} else {
emit timeout(tr("Время ожидания ответа истекло: %1")
.arg(QTime::currentTime().toString()));
}
} else {
//.........这里部分代码省略.........
示例10: run
void SerialThread::run()
{
QSerialPort serial;
int cr;
serial.setPortName(m_portName);
if (!serial.setBaudRate(115200)) {
qDebug() << "Serial set baud rate failed!";
emit this->serialError(tr("Can't set baud rate for %1, error code %2. %3.")
.arg(m_portName).arg(serial.error()).arg(serial.errorString()));
return;
}
if (!serial.setDataBits(QSerialPort::Data8)) {
qDebug() << "Serial set data bits failed!";
emit this->serialError(tr("Can't set data bits for %1, error code %2. %3.")
.arg(m_portName).arg(serial.error()).arg(serial.errorString()));
return;
}
if (!serial.setParity(QSerialPort::NoParity)) {
qDebug() << "Serial set parity failed!";
emit this->serialError(tr("Can't set parity for %1, error code %2. %3.")
.arg(m_portName).arg(serial.error()).arg(serial.errorString()));
return;
}
if (!serial.setStopBits(QSerialPort::OneStop)) {
qDebug() << "Serial set stop bits failed!";
emit this->serialError(tr("Can't set stop bits for %1, error code %2. %3.")
.arg(m_portName).arg(serial.error()).arg(serial.errorString()));
return;
}
if (!serial.setFlowControl(QSerialPort::NoFlowControl)) {
qDebug() << "Serial set flow control failed!";
emit this->serialError(tr("Can't set flow control for %1, error code %2. %3.")
.arg(m_portName).arg(serial.error()).arg(serial.errorString()));
return;
}
for (cr = 0; cr < m_connectAttempts; cr++) {
if (serial.open(QIODevice::ReadWrite)) {
break;
}
sleep(1);
qDebug() << "Serial connect retry...";
}
if (cr == m_connectAttempts) {
qDebug() << "Connection failed!";
emit this->serialError(tr("Can't open %1, error code %2. %3.")
.arg(m_portName).arg(serial.error()).arg(serial.errorString()));
return;
}
emit this->serialConnected();
qDebug() << "Serial Thread is ready...";
m_mutex.lock();
/* Unlock resources and wait for the first job. */
m_cond.wait(&m_mutex);
m_mutex.unlock();
while (!m_quit) {
/* Protect shared resources while thread is working. */
m_mutex.lock();
if (m_txBuf.size() > 0) {
qint64 bytesWritten = serial.write(m_txBuf);
if (serial.waitForBytesWritten(SERIAL_WRITE_TIMEOUT_MS)) {
m_txBuf.remove(0, bytesWritten);
} else {
qDebug() << "Write request timeout!";
/* Unlock resources and exit. */
m_mutex.unlock();
emit serialTimeout(tr("Write request timeout!"));
break;
}
}
if (serial.waitForReadyRead(SERIAL_READ_TIMEOUT_MS)) {
m_rxBuf += serial.readAll();
while (serial.waitForReadyRead(SERIAL_READ_TIMEOUT_EXTRA_MS)) {
m_rxBuf += serial.readAll();
}
if (m_rxBuf.size() >= TELEMETRY_MSG_SIZE_BYTES) {
processInputData();
}
} else {
qDebug() << "Read response timeout!";
/* Unlock resources and exit. */
m_mutex.unlock();
emit serialTimeout(tr("Read response timeout!"));
break;
}
//qDebug() << "Serial Thread is sleeping...";
/* Unlock resources and wait for the next job. */
m_cond.wait(&m_mutex);
m_mutex.unlock();
}
qDebug() << "Serial Thread is terminating...";
serial.close();
}
示例11: run
void ReceiveDataThread::run()
{
bool currentPortNameChanged = false;
quit = false;//这一句是必须的
mutex.lock();
QString currentPortName;
if (currentPortName != portName)
{
currentPortName = portName;
currentPortNameChanged = true;
}
mutex.unlock();
QSerialPort serial;
while (!quit)
{
if (currentPortNameChanged)
{
serial.close();
serial.setPortName(currentPortName);
serial.setBaudRate(baudRate);
serial.setStopBits(stopBits);
serial.setParity(parity);
serial.setDataBits(dataBits);
if (!serial.open(QIODevice::ReadWrite))
{
emit error(tr("无法打开串口%1, 错误码为%2")
.arg(portName).arg(serial.error()));
return;
}
//成功打开串口
emit success();
}
if (serial.waitForReadyRead(100))
{
//读取数据
// QByteArray requestData = serial.readAll();
data += serial.readAll();
// while (serial.waitForReadyRead(1000))
// requestData += serial.readAll();
// qDebug() << "requestData.size() = " << requestData.size();
//如果接收到的数据加起来超过了800个字节,则发送给主界面
// if(requestData.size() > 800)
if(data.size() > 400)
{
// QString request(requestData);
qDebug() << "data.size() = " << data.size();
QString request(data);
emit this->request(request);//发送数据
data.clear();
}
}
mutex.lock();
if (currentPortName != portName)
{
currentPortName = portName;
currentPortNameChanged = true;
}
else
{
currentPortNameChanged = false;
}
mutex.unlock();
}
serial.close();
qDebug() << "串口被关闭" << endl;
}
示例12: run
void SerialPortThread::run()
{
bool __isStopped = true;
m_serialPortMutex.lock();
__isStopped = m_isStopped;
m_serialPortMutex.unlock();
qDebug("thread running");
SerialPortSettings::Settings __mSettings;
bool __isSettingsChanged = false;
QByteArray __dataReceived;
QByteArray __dataToSend;
// unsigned char rx_buffer[256];
QSerialPort serial;
while(!__isStopped)
{
m_serialPortMutex.lock();
if(m_isSettingsChanged){
m_isSettingsChanged =false;
__isSettingsChanged = true;
}
m_serialPortMutex.unlock();
if(__isSettingsChanged){
__isSettingsChanged =false;
if(serial.isOpen()){
serial.close();
}
m_serialPortMutex.lock();
__mSettings = m_currentSettings;
m_serialPortMutex.unlock();
serial.setPortName(__mSettings.name);
serial.setBaudRate(__mSettings.baudRate);
serial.setDataBits(__mSettings.dataBits);
serial.setParity(__mSettings.parity);
serial.setStopBits(__mSettings.stopBits);
serial.setFlowControl(__mSettings.flowControl);
emit message(QString("settings changed !"));
}//settings changed
if(!serial.isOpen()){
if(serial.open(QIODevice::ReadWrite)){
emit message(QString("open successfully !"));
}
else{
m_serialPortMutex.lock();
m_isStopped = true;
m_serialPortMutex.unlock();
emit message(QString("open failed !"));
break;
}
}//if not open , while loop break
/*=== opened , processing data here ===*/
m_serialPortMutex.lock();
if(!m_dataToSend.isEmpty()){
__dataToSend.append(m_dataToSend);
m_dataToSend.clear();
}
m_serialPortMutex.unlock();
if(! __dataToSend.isEmpty()){
if(serial.write(__dataToSend) > 0){
if (serial.waitForBytesWritten(100) == true) {
qDebug() <<"write successfully !";
__dataToSend.clear();
}
else
qDebug() <<"write time out !";
}
}
if (serial.waitForReadyRead(100)) {
__dataReceived = serial.readAll();
while (serial.waitForReadyRead(10))
__dataReceived += serial.readAll();
}
//unpack the data received
if(__dataReceived.size() > 0){
emit message(__dataReceived);
// for(int i = 0; i < __dataReceived.size(); i ++){
// if(FrameUnpack(__dataReceived.at(i),rx_buffer)){
// tHeader* pHeader = (tHeader*)rx_buffer;
// if( pHeader->cmd == CMD_ID_SENSOR_INFO){
// // Cmd_Data *pData = (Cmd_Data *)&rx_buffer[sizeof(tHeader)];//
// }
// else{
// }
// }
// }
}//unpack code end
//.........这里部分代码省略.........
示例13: run
void SerialPortThread::run()
{
bool currentPortNameChanged = false;
mutex.lock();
QString currentPortName;
if(currentPortName != portName)
{
currentPortName = portName;
currentPortNameChanged = true;
}
int currentWaitTimeout = waitTimeout;
QString currentRequest = request;
mutex.unlock();
QSerialPort serial;
while(!quit)
{
if(currentPortNameChanged)
{
serial.close();
serial.setPortName(currentPortName);
if(!serial.open(QIODevice::ReadWrite))
{
emit this->S_PortNotOpen(); //串口未成功打开,信号返回到主程序
return;
}
serial.setBaudRate(QSerialPort::Baud19200); //波特率
serial.setDataBits(QSerialPort::Data8); //数据位
serial.setParity(QSerialPort::NoParity); //校验位
serial.setStopBits(QSerialPort::OneStop); //停止位
serial.setFlowControl(QSerialPort::NoFlowControl); //流控制
}
QByteArray requestData = currentRequest.toLocal8Bit();
serial.write(requestData);
if(serial.waitForBytesWritten(waitTimeout))
{
if(serial.waitForReadyRead(currentWaitTimeout))
{
QByteArray responseData = serial.readAll();
while(serial.waitForReadyRead(80))
responseData += serial.readAll();
QString response(responseData);
emit this->response(response);
}
else
{
emit this->timeout();
return;
}
}
else
{
emit this->timeout();
return;
}
mutex.lock();
cond.wait(&mutex);
if(currentPortName != portName)
{
currentPortName = portName;
currentPortNameChanged = true;
}
else
currentPortNameChanged = false;
currentWaitTimeout = waitTimeout;
currentRequest = request;
mutex.unlock();
}
}
示例14: GetLeonardoSerialPort
QString Builder::GetLeonardoSerialPort(QString defaultPort)
{
QStringList before, after;
QSerialPortInfo serialList;
QSerialPort port;
SetPercentage(100);
for (int i=0; i < serialList.availablePorts().count(); i++) {
before.append(serialList.availablePorts().at(i).portName());
}
/*#ifdef Q_OS_WIN
PrepareSerialPort(project->serialPort, "1200");
#endif*/
port.setPortName(project->serialPort);
port.setFlowControl(QSerialPort::NoFlowControl);
port.setBaudRate(QSerialPort::Baud1200);
port.setParity(QSerialPort::NoParity);
port.setStopBits(QSerialPort::OneStop);
port.setDataBits(QSerialPort::Data8);
bool open = port.open (QIODevice::ReadWrite);
//#endif
if (open == false) {
progress->SetPhase(BuildWindowTypes::detectingLeonardo2);
msg.Add("Could not reset board automatically via serial port " + project->serialPort + "! Press RESET button at your board NOW!", mtWarning);
}
/*char buffer[20] = "Hello!\r\n";
port.write ((const char *)buffer);*/
//QThread::msleep(10);
port.close();
QThread::msleep(100);
int counter = 50;
after.clear();
bool warningMessage = true;
while (counter > 0) {
QSerialPortInfo newSerialList;
for (int i=0; i < newSerialList.availablePorts().count(); i++) {
after.append(newSerialList.availablePorts().at(i).portName());
}
for (int i=0; i < after.count(); i++) {
if (before.indexOf(after.at(i)) < 0) {
return after.at(i);
}
}
QThread::msleep(120);
counter--;
if ( (progress->value() > 40) && warningMessage) {
warningMessage = false;
progress->SetPhase(BuildWindowTypes::detectingLeonardo2);
msg.Add("Could not reset board automatically via serial port " + project->serialPort + "! Press RESET button at your board NOW!", mtWarning);
}
SetPercentage(100 - counter * 2);
if (GetCancel()) {
counter = 0;
break;
}
}
msg.Add("Could not detect Leonardo serial port for programming. Please try pressing the RESET button at your board when you see the dialog message 'Detecting Leonardo port...'!", mtError);
return "";
}
示例15: run
void SlaveThread::run()
{
bool currentPortNameChanged = false;
mutex.lock();
QString currentPortName;
if (currentPortName != portName) {
currentPortName = portName;
currentPortNameChanged = true;
}
int currentWaitTimeout = waitTimeout;
QString currentRespone = response;
mutex.unlock();
QSerialPort serial;
while (!quit) {
if (currentPortNameChanged) {
serial.close();
serial.setPortName(currentPortName);
if (!serial.open(QIODevice::ReadWrite)) {
emit error(tr("Can't open %1, error code %2")
.arg(portName).arg(serial.error()));
return;
}
}
if (serial.waitForReadyRead(currentWaitTimeout)) {
// read all request
QByteArray requestData = serial.readAll();
while (serial.waitForReadyRead(10))
requestData += serial.readAll();
// write all response
QByteArray responseData = currentRespone.toLocal8Bit();
serial.write(responseData);
if (serial.waitForBytesWritten(waitTimeout)) {
QString request(requestData);
emit this->request(request);
} else {
emit timeout(tr("Wait write response timeout %1")
.arg(QTime::currentTime().toString()));
}
} else {
emit timeout(tr("Wait read request timeout %1")
.arg(QTime::currentTime().toString()));
}
mutex.lock();
if (currentPortName != portName) {
currentPortName = portName;
currentPortNameChanged = true;
} else {
currentPortNameChanged = false;
}
currentWaitTimeout = waitTimeout;
currentRespone = response;
mutex.unlock();
}
}