Al Ma
Al Ma

Reputation: 71

How to send and receive correctly more than one sensor's data via serial communication

I'm trying to send data of 2 sensors from arduino uno to NodeMCU V3 via serial communication,

when I try to send data from one sensor at the time everything works fine but when I use both it gives me random values

This is the arduino sender code :

int water_sensor_pin = 8;
void setup()
{ pinMode(water_sensor_pin, INPUT);
Serial.begin(115200);
}

void loop()
{  
// First sensor
int soil_moisture=analogRead(A0);  
int output_value = map(soil_moisture,430,70,0,100); 
Serial.write(output_value);

 // Second sensor
 int value = digitalRead(water_sensor_pin); 
 if(value==HIGH){
 Serial.write('1');}

 if(value==LOW){
 Serial.write('0');} 
  }

and this is the receiver's part of code

char msg[10];
.
.
.
if(Serial.available()>0){

// First sensor
int output_value = Serial.read(); 
Serial.println(output_value );

// Second sensor
char value = Serial.read(); 
Serial.println(value); 

 }

I expect the output to be correct values for both sensors

Upvotes: 0

Views: 1017

Answers (1)

Tom
Tom

Reputation: 303

When using Serial in Arduino, you have to take care of sending a known amount of bytes and then read this amount of bytes.

On the transmitting side try something like Serial.write(output_value,4); in order to send four bytes and, on the receiving side, Serial.readBytes(output_value,4); in order to read the four bytes you sent, and only them.

Of course you can apply the same technic for the second value you want to send except that you may need only one byte as you seem to send a boolean.

Hope it helps!

EDIT

The technic above would work if you had a buffer of bytes to send. Unfortunately you have an integer value… So you can either try to:

  • convert your value as an array of char of a known size,
  • use the fact that the value you are trying to send can fit in a single byte and thus declaring it as a byte instead of an int and then reading this single byte on the receiver side.

Upvotes: 1

Related Questions