How do you make an arduino communicate with another arduino?

I already succeeded in making the sender send hello to the receiver arduino. But now I want to make a code where I press a button on the sender arduino and it then sends a signal to the receiver arduino to light up an LED lamp.

For this project I'm using arduino UNO for both.

With these codes.

Code of sender arduino:

char mystr[5] = "Hello"; //String data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600);
}

void loop() {
  Serial.write(mystr,5); //Write the serial data
  delay(1000);
}

Code of receiver arduino:

char mystr[10]; //Initialized variable to store recieved data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600);
}

void loop() {
  Serial.readBytes(mystr,5); //Read the serial data and store in var
  Serial.println(mystr); //Print data on Serial Monitor
  delay(1000);
}

So first try changing the sender code so that it only sends hello when you push a buton.

1. You add the following codes at the appropriate place of the Sender Sketch:

pinMode(2, INPUT_PULLUP);   //connect a Switch across DPin-2 and GND
while(digitalRead(2) != LOW)
{
   ;//wait until Swicth is pressed
}
Serial.write(mystr, 5);

2. You add the following codes at the appropriate place of the Receiver Sketch:

#define LED 2
pinMode(LED, OUTPUT);

byte n = Serial.available();
if(n != 0)
{
   Serial.readBytes(mystr, 5);
   mystr[5] ='\0';
   if(strcmp(mystr, "Hello") == 0)
   {
       digitalWrite(LED, HIGH);   //LED is turned On
   }
}

Fix this problem first

char mystr[5] = "Hello"; //String data

The string actually has 6 characters in it including the trailing '\0' that the compiler will add to mark the end of the string. By declaring teh array as having 5 elements it means that the '\0' is written to memory that does not belong to the array

char mystr[] = "Hello"; //String data

would be better as it allows the compiler to work out teh size of the array

1 Like

should only read when there's something to receive

look this over

const byte PinLed = LED_BUILTIN;
enum { LedOff = LOW, LedOn = HIGH };

void loop ()
{
    if (Serial.available ())  {
        char buf [80];
        int n = Serial.readBytesUntil ('\n', buf, sizeof(buf)-1);
        buf [n] = '\0';

        // toggle led on/off
        digitalWrite (PinLed, ! digitalRead (PinLed));
    }
}

void setup ()
{
    Serial.begin (9600);

    pinMode      (PinLed, OUTPUT);
    digitalWrite (PinLed, LedOn);
}
  • not sure what you will see on serial monitor if serial pins are connected between Arduinos
  • need to recognize command to turn LED on or off

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.