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

Arduino send integer as two bytes and display it in Qt

本文关键字:字节 Qt 两个 显示 整数 Arduino      更新时间:2023-10-16

我试图通过串行端口每秒发送一个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:中的插槽代码

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

您是否尝试只打印数据?我想没有,否则你会注意到的。。您不是一个接一个地发送整数。

原因是什么?每次迭代都要向数据中添加一个,但每秒钟都要发送一个。

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

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

然而,我认为从长远来看,你会遇到一些问题,尤其是如果你用1周期调用插槽。

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

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