Ich arbeite an einer einfachen Funktion, die in der Lage ist, ein Int in Qt unter Verwendung von Informationen zu einem Comport zurückgeben.Qt - Bytearray mit leeren Einträgen?
Ich verwende die QSerialPort-Klasse, die eine QBytearray zurückgibt.
Das Problem ist, ich (gelegentlich) leere Einträge im Array, das QSerialPort.readAll zurückgibt. Dadurch kann ich das Bytearray nicht in ein int konvertieren.
Die grundlegende Funktionalität ist: Fragen Sie nach Arduino, um entweder Temperatur oder Feuchtigkeit zu senden.
Qt Code:
#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();
}
Der Code Arduino ist super einfach.
#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();
}
}
Terminal-Monitor zeigt:
Bitte bearbeiten Sie Ihren Code, um ihn auf ein [mcve] Ihres Problems zu reduzieren. Ihr aktueller Code enthält eine Vielzahl von Problemen, die für Ihr Problem typisch sind. Ein minimales Beispiel ähnelt normalerweise einem guten Komponententest: Es wird nur eine Aufgabe ausgeführt, wobei die Eingabewerte für die Reproduzierbarkeit angegeben werden. –
Sie könnten 'QByteArray :: toHex()' Methode hilfreich, BTW. – hyde