在 Arduino 上使用串行软件发送 3 个浮点变量 [英] Sending 3 float variables with serial software on Arduino
问题描述
我正在尝试使用软件串行库通过 Arduino 的无线模块发送我的机器人的位置.我发现它一次只能发送 1 个字节.我不能发送超过 255 的数字,我需要发送直到 40000 的浮点数.我该怎么做?
I'm trying to send position of my robot through wireless module with Arduino using Software Serial library. I found that it can only send 1 byte at time. I can't send more than number 255 and I need to send floats till 40000. How I can do that?
这是我的发射器的一个例子:
Here is an example of my transmitter:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
mySerial.begin(9600);
}
void loop() // run over and over
{
float i=40000;
mySerial.write(i);
//Serial.println(i);}
}
我的收货人
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX
int i=0;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
mySerial.begin(9600);
}
void loop() {
if(mySerial.available()){
i=mySerial.read();
Serial.println(i);
}
}
推荐答案
您必须使用 Serial.println(floatVal);
以带有任何空格分隔符的纯文本形式发送它并通过Serial.parseFloat()
方法.
You have to use Serial.println(floatVal);
to send it in plain text with any white space separator and receive it by Serial.parseFloat()
method.
write
方法适合发送原始数据(单个字符、c 字符串或一些缓冲区)
The write
method is good for sending raw data (single character, c-string or some buffer)
如果您真的想以二进制形式发送浮点数,则必须将其作为缓冲区传递:Serial.write((uint8_t*)&floatVal, sizeof(intVal));
.在接收方,您也必须读取整个浮点数.read()
方法只读取一个字符.
If you really want sending floats in its binary form, you have to pass it as an buffer: Serial.write((uint8_t*)&floatVal, sizeof(intVal));
. And on the receiver side you have to read whole float too. The read()
method reads only one character.
这篇关于在 Arduino 上使用串行软件发送 3 个浮点变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!