-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserialport.cpp
85 lines (71 loc) · 1.94 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "serialport.h"
#if defined(LINUX) || defined(UNIX)
#include <unisted>
#elif defined(WINDOWS)
#include <Windows.h>
#endif
SerialPort::SerialPort()
{
serialport = new QSerialPort;
hasbeenclosed = 1;
}
SerialPort::~SerialPort()
{
if(hasbeenclosed == 0)
close();
delete[] serialport;
}
int SerialPort::run(QString comnum, qint32 btl)
{
serialport->setPortName(comnum);
serialport->setBaudRate(btl);
serialport->setDataBits(QSerialPort::Data8); //数据位
serialport->setParity(QSerialPort::NoParity);//无奇偶校验
serialport->setStopBits(QSerialPort::OneStop);//停止位1
serialport->setFlowControl(QSerialPort::NoFlowControl);//无控制
hasbeenclosed = 0;
if(!serialport->open(QIODevice::ReadWrite))
return -1;
else
{
connect(serialport, &QSerialPort::readyRead,
this, &SerialPort::begin_to_receive);
//connect(serialport, SIGNAL(readyRead()), this, SLOT(begin_to_receive()));
return 1;
}
}
void SerialPort::begin_to_receive()
{
rcvdata = serialport->readAll();
emit signals_serial_receive(rcvdata);
#if defined(LINUX) || defined(UNIX)
usleep(5000);
#elif defined(WINDOWS)
Sleep(5);
#endif
#ifdef DEBUG_SERIAL_PORT_RECEIVE
QString hexstr = ByteArrayToHexString(rcvdata);
printf("SerialPort receive: %s\n", hexstr.toStdString().c_str());
#endif
}
void SerialPort::send(QByteArray portdata)
{
if(serialport != nullptr)
{
qint64 res = serialport->write(portdata);
//serialport->flush();
//printf("Send length: %d\n", res);
#ifdef DEBUG_SERIAL_PORT_SEND
//printf("Serial send: %s\n", ByteArrayToHexString(portdata).toStdString().c_str());
#endif
}
}
void SerialPort::close()
{
if(serialport != nullptr)
{
hasbeenclosed = 1;
serialport->clear();
serialport->close();
}
}