2017-04-27 8 views
0

나는 compt에 보내진 정보를 사용하여 Qt에서 int를 반환 할 수있는 간단한 함수를 만들고있다.Qt - 빈 항목이 포함 된 Bytearray?

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(); 
} 

아두 이노 코드는 매우 간단합니다.

#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(); 
    } 
} 

터미널 모니터 디스플레이 : 배열의 4 바이트가 있음을 의미하므로 rawDataArry.size(), 4 반환처럼

enter image description here

+0

코드를 편집하여 문제의 [mcve]로 줄이십시오. 현재 코드에는 문제의 주변부가 많이 포함되어 있습니다. 최소한의 샘플은 일반적으로 좋은 단위 테스트와 유사합니다. 재현성을 위해 지정된 입력 값을 사용하여 하나의 작업 만 수행합니다. –

+0

'QByteArray :: toHex()'메소드가 도움이 될 것입니다. btw. – hyde

답변

0

보인다. 그러나 rawDataArry[i]을 호출하면 char가 반환됩니다. 모든 char 값이 ascii 문자로 표현 될 수있는 것은 아닙니다. 그래서 마지막 2 바이트가 비어있는 것입니다.

대신 각 문자를 ASCII 표현 대신에 바이트의 십진수/16 진수 표현을 나타내는 값으로 변환해야합니다.

양자 택일로, 당신은 바로 int로하는 4 바이트를 변환 할 수 그것으로 할 수 :

//Big Endian 
quint32 myValue(0); 
for(int i=0; i<4; i++) 
    myValue = myValue + (quint8(rawDataArry.at(i)) << (3-i)*8); 
//myValue should now have your integer value 
+0

입력 해 주셔서 감사합니다! QByteArray에 모든 빈 항목과 넓은 영역을 제거 할 수있는 멤버가 있다는 사실을 알게되었습니다. 그것은 일하는 것을 끝내었다! –

0

내가 배열의 widespaces을 정리 QByteArray의 멤버를 사용하여 종료!

다음과 같이 보입니다.

bool ok; 
int returnVal; 

do 
{ 
    Arduino.write(&imputChar, 1); // Arduino input Char 

    Arduino.waitForReadyRead(); 

    QByteArray rawDataArry(Arduino.readAll()); // Empties buffer into rawDataArry 
    QByteArray dataArray(rawDataArry.simplified()); // Removes all widespaces! 

    returnVal = dataArray.toInt(&ok, 10); // Retuns ByteConvertion - &OK is true if convertion has completed - Widespaces will ruin the conversion 

    qDebug() << "Converted data:"; 
    qDebug() << returnVal; 
    qDebug() << "Convertion Status:" << ok; 
    }while(ok != 1); 

    return(returnVal);