我在我的项目中使用Arduino Uno:一个是Master,另一个是Slave。我使用I2C将数据从主设备发送到从设备。我需要发送float,但因为I2C只能发送char,所以我有义务将float转换为String,然后逐字符发送,并在Slave中汇编它们。
我遇到的问题是,我正在声明变量(在Slave中)包含Float接收并从Master那里像一个全局变量一样,我需要在我的代码中使用它,但我的问题是它始终打印为0,并且它没有给出正确的值。
我使用的代码是:
#include <LCD16x2.h>
#include <Wire.h>
LCD16x2 lcd;
int buttons;
int sensorPin = A0; // select the input pin for the potentiometer
int sensorValue = 0; // variable to store the value coming from the sensor
float numOut=0; // The Global Variable
int comp=1 ;
String wordd = "";
void setup()
{
Wire.begin(8); // join i2c bus with address #8
Wire.onReceive(receiveEvent); // register event
Serial.begin(9600); // start serial for output
lcd.lcdGoToXY(1,1);
lcd.lcdClear();
lcd.lcdWrite("EG ");
lcd.lcdGoToXY(7,1);
lcd.lcdWrite(numOut,3);
}
void loop()
{
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
wordd = "";
int x = Wire.read();
for (int i=0; i<=x; i++)
{
char c = Wire.read();
wordd += c;
}
numOut = wordd.toFloat();
Serial.println(numOut,3); // print the integer
}
我需要知道如何获得全局变量的结果&#34; numOut&#34;在我的代码中使用它。
提前谢谢。!!
答案 0 :(得分:-1)
您是否确实检查过收到的数据是否正确?我不知道Arduino的字符串,但如果你的toFloat()
失败,它可能会返回0。
如果你的wordd变量是正确的,请检查你的串口,并且如前所述,全局变量应该声明为volatile
。
编辑:
此处需要volatile
以确保您的数据在不同的函数调用之间同步(否则您的程序可能会将值保留在寄存器中,尽管&#34; real&#34;值已通过中断更新)。
然而,有人说volatile
不对每个全局变量都是必需的,但是你不会在Arduino上使用信号量/互斥量...所以坚持为你解决这个问题帐。
编辑: https://www.arduino.cc/en/Reference/StringToFloat &#34;如果由于字符串不以数字开头而无法执行有效转换,则返回零。&#34;