DEV Community

Cover image for How to make two Arduinos communicate over serial.

How to make two Arduinos communicate over serial.

As we all know, an Arduino can't handle too many sensors and calculate all of them without freaking out, so sometimes we need to out source a sensor to other Arduino and let it calculate a value and send it to us in the master.

Wiring

Image description

RX ===> TX
TX ===> RX
GND ===> GND

I needed to send data to the other Arduino, and make it calculate it and send it over to me in the master.

Master code

char number  = ' ';
String message = "";
bool send_data = true;
void setup()
{
  Serial.begin(9600);

}

void loop()
{

  while(send_data){

  Serial.println("Little bord Hi!! ");

   readData();
  delay(2000);
  if(message != ""){
      if(message == "2222"){
      send_data = false;

      Serial.println("Message received");
      Serial.println("******************");
      Serial.println(message);
      Serial.println("******************");
      }
  }
      message = "";

  }


}

void readData(){
  while(Serial.available()){

   if(Serial.available())
   {
      char number = Serial.read();
      message += number ;
   }
  }
}
Enter fullscreen mode Exit fullscreen mode

Slave code

char number  = ' ';
String message = "";
bool is_not_sent = true; 
void setup() 
{
  pinMode(LED_BUILTIN, OUTPUT);
   Serial.begin(9600);
   Serial.println("START");
}


void loop()
{


 readData();
  delay(2000);
 if(is_not_sent)
  {
    if(message != ""){
      message = "Big bro said : " + message;
      // Serial.println(message);
      digitalWrite(LED_BUILTIN, HIGH); 
      delay(500);
      Serial.print(2222);
      delay(500);

      // Todo check wach correct data
      is_not_sent = false;
      message = "";
  }
  }
}



void readData(){
  while(Serial.available()){

   if(Serial.available())
   {
      char number = Serial.read();
      message += number ;
   }
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)