我正在研究一个简单的函数,它能够使用发送到 comport 的信息在 Qt 中返回一个 int。
我正在使用返回 QBytearray 的 QSerialPort类。
问题是我似乎(有时)在 QSerialPort.readAll 返回的数组中获取空条目。这使我无法将 bytearray 转换为 int。
基本功能是:要求 Arduino 发送温度或湿度。
Qt代码:
#include <QCoreApplication>
#include <QSerialPortInfo>
#include <QSerialPort>
#include <iostream>
#include <string>
#include <windows.h>
#include <math.h>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString comPort = "COM6";
QSerialPortInfo ArduinoInfo(comPort);
cout << "Manufacturer: " << ArduinoInfo.manufacturer().toStdString() << endl;
cout << "Product Identifier: " << ArduinoInfo.productIdentifier() << endl;
cout << "Vendor Identifier: " << ArduinoInfo.vendorIdentifier() << endl;
QSerialPort Arduino(ArduinoInfo);
Arduino.setBaudRate(QSerialPort::Baud9600);
Arduino.open(QSerialPort::ReadWrite);
Sleep(1000);
if(Arduino.isDataTerminalReady())
cout << "Great Sucess" << endl;
char sending = 'H';
cout << sending << endl;
Arduino.write(&sending, 1);
//int maxSize = Arduino.bytesAvailable();
while(!Arduino.waitForReadyRead()){}
Sleep(100);
QByteArray rawDataArry = Arduino.readAll();
cout << "Shit has been read." << endl;
// Form here on its just write functions, used for debug
cout << "rawData:" << endl;
for(int i=0; i < rawDataArry.size(); i++)
cout << "[" << i << "] "<< rawDataArry[i] << endl;
cout << "All data:" << endl;
for(char s:rawDataArry){
cout << s;
}
cout << endl;
cout << "Converted data:" << endl;
bool ok;
int returnVar = rawDataArry.toInt(&ok, 10);
cout << returnVar << endl;
cout << "Convertion Status:" << ok;
Arduino.close();
return a.exec();
}
Arduino 代码非常简单。
#include <dht.h>
dht DHT;
#define PIN_7 7
void setup() {
Serial.begin(9600);
}
void loop()
{
String impString;
while(Serial.available() != 1);
impString = Serial.readString();
DHT.read11(PIN_7);
if(impString == "T")
{
int temp = DHT.temperature;
Serial.println(temp);
}
else if(impString == "H")
{
int humid = DHT.humidity;
Serial.println(humid);
}
emptyReceiveBuf();
delay(100);
}
void emptyReceiveBuf()
{
int x;
delay(200); // vent lige 200 ms paa at alt er kommet over
while (0 < Serial.available())
{
x = Serial.read();
}
}
终端监视器显示: