Arduino将整数作为两个字节发送并在Qt中显示

时间:2015-12-23 08:22:58

标签: c++ qt arduino serial-port

我试图通过串口发送每秒0到400之间的整数,并在Qt中显示。问题是我正在阅读不一致的数字:

  

174,229,397,51,220,18,1,42

这是我的Arduino代码:

int data = 0; // variable to send via serial
unsigned long deltaTime;
unsigned long oldTime = 0;

void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
}

void loop() {
   // decompose the integer into low and high bytes 
   byte b0 = lowByte(data);
   byte b1 = highByte(data);
   // Create a buffer and store the two bytes in it
   byte buff[2];
   buff [0] = b0;
   buff [1] = b1;
   deltaTime = millis() - oldTime;
   // When one second is passed send Data
   if (deltaTime > 1000) {
       // Send the packet
       Serial.write(buff,2) ;
       oldTime = millis();
   }
   // incremment the integer:
   data++; 
   if(data >= 400 ) data = 0;
}

这是Qt中的Slot代码:

void MainWindow::readData(){
    // read two bytes at once
    QByteArray data  = serial->read(2);
    // convert them back to int and display
    unsigned char b0 = (unsigned char)data[0];
    unsigned char b1 = (unsigned char)data[1];
    int val = (int)b1 * 256 + (int)b0 ;
    qDebug()<< val << endl;
}

1 个答案:

答案 0 :(得分:2)

您是否尝试仅打印数据?我想不,因为否则你会注意到......你不是一个接一个地发送整数。

原因?您每次迭代都会向数据添加一个,但是您每秒都会将其发送出去。

修复它的方法非常简单:这个

if (deltaTime > 1000)
{  
    // Send the packet
    Serial.write(buff,2) ;
    oldTime = millis();
}

// increment the integer:
data++; 

if(data >= 400 ) data = 0;

应该成为这个

if (deltaTime > 1000)
{  
    // Send the packet
    Serial.write(buff,2) ;
    oldTime = millis();

    // increment the integer:
    data++; 

    if(data >= 400 ) data = 0;
}

但是我认为从长远来看你会遇到一些问题,特别是如果你用一段时间来调用这个插槽。

我建议你使用未使用的位(你发送0到400之间的整数,所以9位,但你发送其中的16位),以提供一种方法来理解字节是高字节还是低字节。

最简单的方法是在第一个字节中发送高7位并将最高位设置为1,然后发送最低7位并将最高位设置为0。在qt中,然后,连续阅读。如果第一位是1,则将另一部分保存为最高位,如果为零则将另一部分连接到已保存的部分并将其输出到控制台。