I'm trying to get two arduino uno to communicate. The slave reads a temp sensor as an analog value, then converts it to degrees C, then sends that value to the master, the master then prints the value to the serial monitor. This is the code I have thus far.
for the slave
const int tempPin = A0;
void setup(){
Serial.begin(9600);
delay(2000);
}
void loop() {
//read sensor data to a variable
float volt = analogRead(tempPin) * 0.004882814;
float degC = (volt - 0.5) * 100.0;
Serial.println(degC);
delay(2000); //Not to flood serial port
}
this is the code for the master
float tempC;
void setup(){
Serial.begin(9600);
delay(2000);
}
void loop() {
/** check if data has been sent from the computer: */
while (Serial.available()) {
/* read the most recent byte */
tempC = Serial.read(); //now byteRead will have latest sensor
// data sent from Arduino1
Serial.println(tempC);
}
}
My issue is that I am reading on the serial monitor 4 different 2 integer values
-
What exactly are you seeing in the serial monitor? What does "4 different 2 integer values" mean?gre_gor– gre_gor10/11/2017 23:37:49Commented Oct 11, 2017 at 23:37
-
The code comes from this: arduino.stackexchange.com/questions/16227/… That example for sending and receiving a single byte. You want to send a text (a text that shows a floating point number), so you will have to read that complete text.Jot– Jot10/12/2017 14:39:50Commented Oct 12, 2017 at 14:39
1 Answer 1
Your slave is sending an array of characters and your master is reading the ASCII values of those characters.
If you send 25.43, Serial.println
will send 7 characters 2
, 5
, .
, 4
, 3
, carriage return and a newline.
The master will read them as 50, 53, 46, 52, 51, 13 and 10. Your code then prints:
50.00
53.00
46.00
52.00
51.00
13.00
10.00
On your master, the loop()
should look like:
void loop() {
if (Serial.available()) {
char c = Serial.peek(); // just look at the next character on the serial buffer
if (c == '\r' || c == '\n') // ignore the carriage return and newline characters
Serial.read(); // remove the character from serial buffer by reading it
else {
tempC = Serial.parseFloat(); // read and parse the string representing the float value
Serial.println(tempC);
}
}
}
-
1The value is floating point, not integer. Reading the integer part would be a start, though that will truncate rather than round. Possible solutions are parsing the float, rounding to an integer on the sender, or something like multiplying by 100, rounding, sending that, and then on the receiver copying the multiplied value to a float and dividing it back.Chris Stratton– Chris Stratton10/11/2017 19:30:16Commented Oct 11, 2017 at 19:30
-
1I fixed it, so it properly reads the floating point value.gre_gor– gre_gor10/12/2017 02:44:38Commented Oct 12, 2017 at 2:44