Arduino将整数发送为两个字节,并将其显示在Qt中
Arduino send integer as two bytes and display it in Qt
我试图通过串行端口每秒发送一个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,则将其他部分连接到保存的部分,并将其输出到控制台。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- Qt VTK交互风格的信号到小部件
- C++/Qt Valgrind 未初始化的字节
- Qt:从固定数量的字节到整数
- 如何从 Oracle 数据库中获取 qt 中 SQL 查询的传输字节大小?
- Qt TCP 套接字 - 写入超过 15 个字节
- 为什么当我使用双精度时,Qt<->Matlab 正确写入和读取我的字节,但存储 uint32 的字节不正确?
- 在 QByteArray 中插入字节 来自 QString - Qt C++
- 删除字节数组 : Qt 缓冲区之间的空字符 (\x00)
- QT QT QBuffer字节编写的字节无法读取
- VoIP:如何从QT多媒体中的相机中捕获实时音频/视频流字节
- 从字节数组快速转换为图像,QT可以以形式显示
- Qt套接字未等待写入字节
- Qt串行端口有时会丢失最后一个字节
- 控制QT中准备从声卡读取的字节数
- Qt是否有一种将字节转换为int的方法,反之亦然
- Qt:显示来自 QByteArray 的字节
- QT 串行发送一个字节
- Arduino将整数发送为两个字节,并将其显示在Qt中
- 在Qt中打印8字节整数时出错