-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserialport.cpp
70 lines (61 loc) · 1.74 KB
/
serialport.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "serialport.h"
#include <QSerialPortInfo>
//Q_GLOBAL_STATIC(SerialPort, p_serialPort)
//SerialPort *SerialPort::getInstance()
//{
// return p_serialPort;
//}
SerialPort::SerialPort(QObject *parent) : QObject(parent)
{
}
SerialPort::~SerialPort()
{
close();
}
bool SerialPort::open(QString portName, int baudRate)
{
close();
serialPort = new QSerialPort();
serialPort->setPortName(portName);
if(!serialPort->open(QIODevice::ReadWrite)) {
emit openFailed();
close();
return false;
}
serialPort->setBaudRate(baudRate, QSerialPort::AllDirections); //设置波特率和读写方向
serialPort->setDataBits(QSerialPort::Data8); //数据位为8位
serialPort->setFlowControl(QSerialPort::NoFlowControl); //无流控制
serialPort->setParity(QSerialPort::NoParity); //无校验位
serialPort->setStopBits(QSerialPort::OneStop); //一位停止位
return true;
}
void SerialPort::close()
{
if(serialPort != Q_NULLPTR) {
if (serialPort->isOpen()) {
serialPort->clear();
serialPort->close();
}
serialPort->deleteLater();
serialPort = Q_NULLPTR;
}
}
QStringList SerialPort::getAllPortNames(QString defaultSearch, QString &defaultName)
{
defaultName = "";
QStringList portNames;
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
portNames << info.portName();
if (defaultName.isEmpty() && info.portName().contains(defaultSearch)) {
defaultName = info.portName();
}
}
return portNames;
}
void SerialPort::sendData(QString data)
{
if(serialPort != Q_NULLPTR && serialPort->isOpen()) {
data += "\r\n";
serialPort->write(data.toUtf8());
}
}