Greetings people.
This is not a question but rather a way that I found works properly for sending multiple float values (through many different sensors) from one Arduino board to another. Or in my case, an Arduino Mega to Arduino Uno.
This involves the use of Serial.parseFloat() function to read the values.
Sender code-
// here data from analog pins A0 and A1 are sent serially to arudino UNO
// to add more sensors, just increase the use of alphabets and update the receiver code accordingly
const int analogPin1 = A0;
const int analogPin2 = A1;
void setup()
{
Serial.begin(9600);
}
void loop()
{
int sensor1 = analogRead(analogPin1) ;
int sensor2 = analogRead(analogPin2) ;
Serial.write('a');
Serial.println(sensor1);
Serial.write('b');
Serial.println(sensor2);
Serial.write('c');
}
Receiver code-
#include <SPI.h>
// initializing the variables
float sensor1 = 0;
float sensor2 = 0;
float windMPS = 0;
float tempC = 0;
char inChar;
unsigned long previousMillis = 0;
const long interval = 3000;
void setup()
{
Serial.begin(9600);
}
void loop()
{
while (Serial.available() > 0)
{
// wait until the serial reading encounters character 'a'
// this marks the beginning of data
inChar = Serial.read();
while (inChar != 'a')
{
inChar = Serial.read();
}
// when character 'a' is encountered, read the floating data till the next character
sensor1 = Serial.parseFloat();
inChar = Serial.read();
// run if the next character is 'b' (it will always be 'b', unless someone messes with the sender code)
if (inChar == 'b')
{
// read floating value till next character
sensor2 = Serial.parseFloat();
}
inChar = Serial.read();
// break out of the loop once character 'c' is encountered
if (inChar == 'c')
{
break;
}
// for more sensor values, add more IF cases and keep the 'break' in the last one
// number them alphabetically for simplicity
}
// this code runs every 2 seconds and display data on the Serial Monitor
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
windMPS = (pow(((sensor1 - 264.0) / 85.6814), 3.36814)) * 0.44704;
Serial.print("Value from sensor 1 is ");
Serial.println(windMPS);
tempC = (((sensor2 * 5.0) / 1024.0) - 0.400) / .0195;
Serial.print("Value from sensor 2 is ");
Serial.println(tempC);
}
}
I am displaying the data every three seconds. Let me know if you have any doubts or any feedback as to improve the code.
Thanks.