本文整理汇总了C++中QSerialPort类的典型用法代码示例。如果您正苦于以下问题:C++ QSerialPort类的具体用法?C++ QSerialPort怎么用?C++ QSerialPort使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QSerialPort类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: switch
QString MainWindow::serialErrorString() const
{
QSerialPort* serial = qobject_cast<QSerialPort*>(_ioDevice);
switch(serial->error())
{
case QSerialPort::NoError:
return "no error";
case QSerialPort::DeviceNotFoundError:
return "device not found";
case QSerialPort::PermissionError:
return "permission error";
case QSerialPort::OpenError:
return "device is already opened";
case QSerialPort::FramingError:
return "framing error";
case QSerialPort::ParityError:
return "parity error";
case QSerialPort::BreakConditionError:
return "break condition error";
case QSerialPort::ReadError:
return "read error";
case QSerialPort::WriteError:
return "write error";
case QSerialPort::UnsupportedOperationError:
return "unsupported operation error";
case QSerialPort::UnknownError:
default:
return "unknown error";
}
}
示例2: main
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QCoreApplication coreApplication(argc, argv);
int argumentCount = QCoreApplication::arguments().size();
QStringList argumentList = QCoreApplication::arguments();
QTextStream standardOutput(stdout);
if (argumentCount == 1) {
standardOutput << QObject::tr("Usage: %1 <serialportname> [baudrate]").arg(argumentList.first()) << endl;
return 1;
}
QSerialPort serialPort;
QString serialPortName = argumentList.at(1);
serialPort.setPortName(serialPortName);
int serialPortBaudRate = (argumentCount > 2) ? argumentList.at(2).toInt() : QSerialPort::Baud9600;
serialPort.setBaudRate(serialPortBaudRate);
if (!serialPort.open(QIODevice::ReadOnly)) {
standardOutput << QObject::tr("Failed to open port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
}
SerialPortReader serialPortReader(&serialPort);
return coreApplication.exec();
}
示例3: tcgetattr
bool Ficgta01MultiplexerPlugin::detect( QSerialIODevice *device )
{
// The FIC needs a special line discipline set on the device.
QSerialPort *port = qobject_cast<QSerialPort *>( device );
if (port) {
int discipline = N_TIHTC;
::ioctl(port->fd(), TIOCSETD, &discipline);
}
device->discard();
int rc;
struct termios t;
rc = tcgetattr(port->fd(), &t);
t.c_cflag |= CRTSCTS;
rc = tcsetattr(port->fd(), TCSANOW, &t);
// Issue an innocuous command to wake up the device.
// It will respond with either "OK" or "AT-Command Interpreter ready".
// We will do this up to 10 times as the modem is losing the first at
// commands (due waking up)
int attempts = 10;
while (--attempts >= 0 && !QSerialIODeviceMultiplexer::chat( device, "ATZ"));
// Issue the AT+CMUX command to determine if this device
// uses GSM 07.10-style multiplexing.
#ifndef FICGTA01_NO_MUX
return QGsm0710Multiplexer::cmuxChat( device, FICGTA01_FRAME_SIZE, true );
#else
return true;
#endif
}
示例4: newSession
bool AtSessionManager::addSerialPort
( const QString& deviceName, const QString& options )
{
// Bail out if the device is already bound.
if ( d->serialPorts.contains( deviceName ) )
return true;
// Attempt to open the device.
QSerialPort *port = QSerialPort::create( deviceName, 115200, true );
if ( !port )
return false;
connect( port, SIGNAL(destroyed()), this, SLOT(serialPortDestroyed()) );
// Zero reads on RFCOMM sockets should cause a close to occur.
port->setKeepOpen( false );
// Add the device to our list.
d->serialPorts.insert( deviceName, port );
registerTaskIfNecessary();
// Wrap the device in a new session handler. We hang it off the
// serial port object so it will get cleaned up automatically
// when removeSerialPort is called.
AtFrontEnd *session = new AtFrontEnd( options, port );
session->setDevice( port );
emit newSession( session );
return true;
}
示例5: run
void ConnectionThread::run()
{
if(stepByStep)
sendNextCommand = false;
else
sendNextCommand = true;
QSerialPort serial;
serial.setPortName(portName);
if (!serial.open(QIODevice::ReadWrite))
{
emit error(tr("Can't open %1, error code %2").arg(portName).arg(serial.error()));
return;
}
while (!quit) {
if(stepByStep)
{
while(!sendNextCommand);
mutex.lock();
sendNextCommand = false;
mutex.unlock();
}
// Envoi microcommande
serial.write(test->recupProchaineMicrocommande().c_str());
if(!serial.waitForBytesWritten(waitTimeout))
{
emit timeout(tr("Wait write microcommande timeout %1").arg(QTime::currentTime().toString()));
}
//Accusé de reception
if(serial.waitForReadyRead(waitTimeout))
{
QByteArray received = serial.readAll();
if(received.toStdString().compare(COMMANDE_RECEIVED) != 0)
{
emit error("Not wanted response");
}
}
else
{
emit timeout(tr("Wait read response timeout %1").arg(QTime::currentTime().toString()));
}
//Pret a recevoir prochaine commande
if(serial.waitForReadyRead(waitTimeout))
{
QByteArray received = serial.readAll();
if(received.toStdString().compare(READY_FOR_NEXT_COMMAND) != 0)
{
emit error("Not wanted response");
}
}
else
{
emit timeout(tr("Wait read response timeout %1").arg(QTime::currentTime().toString()));
}
}
}
示例6: onRxData
void onRxData() {
if (m_port.bytesAvailable() < 9) return;
if (m_port.error() != QSerialPort::NoError)
return;
if (! check(m_port.peek(9)))
return setIoStatus(ChecksumError);
uint8_t dummy;
m_str >> m_address >> dummy >> m_status >> dummy >> m_value;
setIoStatus(Ok);
}
示例7: QSerialPort
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;
}
示例8: foreach
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());
}
}
示例9: dlg
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();
}
示例10: main
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QStringList argumentList = QCoreApplication::arguments();
QSerialPort serialPort;
QString serialPortName = "/dev/ttyUSB0"; // default
int boudRate = QSerialPort::Baud115200;
if (argumentList.size() == 2 ) {
serialPortName = argumentList.at(0);
boudRate = argumentList.at(1).toInt();
}
serialPort.setPortName(serialPortName);
serialPort.open(QIODevice::ReadWrite);
serialPort.setBaudRate(boudRate);
serialPort.setDataBits(QSerialPort::Data8);
serialPort.setParity(QSerialPort::NoParity);
serialPort.setStopBits(QSerialPort::OneStop);
serialPort.setFlowControl(QSerialPort::NoFlowControl);
SerialPortReader serialPortReader(&serialPort, 8080);
serialPortReader.showSerialInfo();
return a.exec();
}
示例11: sendAbortCmd
void ScanUART::sendAbortCmd(QSerialPort &port)
{
QByteArray abortCmd;
abortCmd += 'a';
port.setBaudRate(QSerialPort::Baud115200);
port.write(abortCmd);
port.waitForBytesWritten(100);
int maxCnt = 20;
int cnt=0;
while(port.waitForReadyRead(100)) {
port.readAll();
cnt++;if(cnt>=maxCnt) break;
}
}
示例12: 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;
}
示例13: QWidget
JLWidget::JLWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::JLWidget)
{
ui->setupUi(this);
exusb = new ExUSB();
exusb->start();
exusbthread = new ExUSBThread(exusb);
jl = new JLOpenCV();
//img = new QImage(640,480,QImage::Format_RGB32);
//connect(exusbthread,SIGNAL(exusbthread->GetFrameOK()),this,SLOT(flush_image));
connect(exusbthread,SIGNAL(GetFrameOK(int)),this,SLOT(flush_image()),Qt::QueuedConnection);
//connect(exusbthread,SIGNAL(exusbthread->GetFrameOK(int)),exusbthread,SLOT(test_recv()));
//,Qt::QueuedConnection);
//connect(this,SIGNAL(flush_image()),exusbthread,SLOT(GetFrameOK()),Qt::DirectConnection);
//mVideoWidget.setParent(this);
/*
mVideoWidget = new QVideoWidget();
mMediaPlayer = new QMediaPlayer;
QMediaContent mp = QUrl::fromLocalFile("E:\\zlj_bd.mp4");
mMediaPlayer->setMedia(mp);
mMediaPlayer->setVideoOutput(mVideoWidget);
//mVideoWidget->setBaseSize(1024,576);
mVideoWidget->setGeometry(0,0,1024,576);
mVideoWidget->show();
mMediaPlayer->play();
*/
// image
img = new QImage(640,480,QImage::Format_RGB32);
scence = new QGraphicsScene;
QPainter mPainter(ui->histwidget);
mPainter.setPen(Qt::blue);
mPainter.drawText(rect(),Qt::AlignCenter,"Hello WOrld");
// serialport
QSerialPort *mPort = new QSerialPort();
mPort->setPortName("COM4");
mPort->setBaudRate(mPort->Baud115200);
if (mPort->open(QIODevice::ReadWrite))
{
mPort->write("hello");
}
}
示例14: testBootMode
bool ScanUART::testBootMode(QSerialPort &port)
{
bool foundFlag = false;
SearchController contr;
Request req;
req.setNetAddress(0);
port.setBaudRate(QSerialPort::Baud115200);
CommandInterface* cmd = new GetCoreVersion();
if(cmd->execute(req,port)){
contr.setBaudrate(115200);
if(QString(req.getRdData()).contains("boot")) contr.setBootMode(true);
else contr.setBootMode(false);
contr.setAsciiMode(false);
contr.setNetAddress(0);
contr.setUartName(pName);
if(contr.getBootMode()) {
emit plcHasBeenFound(contr);
foundFlag = true;
}
}
delete cmd;
if(foundFlag) return true;
return false;
}
示例15: scan
bool ScanUART::scan(QSerialPort &port)
{
bool foundFlag = false;
SearchController contr;
float stepWidth = 100.0/(baudTable.count()*2);
float currentPercent=0;
for(int i=0;i<baudTable.count();i++) {
Request req;
req.setNetAddress(progAddr);
port.setBaudRate(baudTable.at(i));
CommandInterface* cmdBin = new GetCoreVersion();
CommandInterface* cmdAscii = new AsciiDecorator(cmdBin);
QVector<CommandInterface*> cmdList {cmdBin, cmdAscii};
foundFlag = false;
foreach(CommandInterface* cmd, cmdList) {
if(cmd->execute(req,port)){
contr.setBaudrate(baudTable.at(i));
if(QString(req.getRdData()).contains("Relkon")) contr.setBootMode(false);
else contr.setBootMode(true);
if(dynamic_cast<AsciiDecorator*>(cmd)) contr.setAsciiMode(true);
else contr.setAsciiMode(false);
GetCoreVersion* coreCmd = dynamic_cast<GetCoreVersion*>(cmdBin);
if(coreCmd) contr.setNetAddress(coreCmd->getNetAddress());
else contr.setNetAddress(0);
contr.setUartName(pName);
// get canal name
if(contr.getBootMode()==false) {
CommandInterface* cmdGetName = new GetCanName();
if(contr.getAsciiMode()) cmdGetName = new AsciiDecorator(cmdGetName);
if(cmdGetName->execute(req,port)) {
contr.setCanName(QString(req.getRdData()).remove("Canal:"));
}
delete cmdGetName;
}
emit percentUpdate(100);
emit plcHasBeenFound(contr);
foundFlag = true;
break;
}
currentPercent+=stepWidth;
emit percentUpdate(currentPercent);
}
delete cmdAscii; // cmdBin удаляется декоратором
mutex.lock();
if(stopCmd) {mutex.unlock();break;}
mutex.unlock();
if(foundFlag) break;
}
if(foundFlag) return true;
return false;
}