Hardware Serial between two Arduino Nanos

Hi. I am trying to transfer a simple integer value from one arduino Nano to another Nano and it should display the value which it received from other Arduino on its serial monitor.
For this purpose, i have made two simple programs for transmitter and receiver arduinos. The transmitter arduino displays the correct value i.e 2 on its serial monitor. But when i open the serial monitor of the receiver arduino, the value that i print keeps changing in random i.e 0,72,254 etc. Please guide me where i am possibly going wrong. Both codes are as below:

//Transmitter code
int x=2;

void setup() {

Serial.begin(9600);
}

void loop() {
Serial.println(x);
delay(2000);
}

//Receiver code
int y;

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

void loop()
{
if (Serial.available()>0){
y = Serial.read();
}
Serial.println(y);
delay(2000);
}

If you are using HardwareSerial between the two Nanos then you are piggy-backing on top of the connection between the Nano and the PC so stuff will get confused - a bit like talking to yourself.

It would be simpler to use SoftwareSerial on each Nano to communicate with the other one and leave HardwareSerial for communication with the PC.

...R
Serial Input Basics

I tried Software serial as well, it had the same problem as i mentioned with hardware serial.

(deleted)

(deleted)

@Spycatcher Yes i have connected the grounds.

Remove the delay() statement and put the Serial.println() inside the if() statement in the receiver loop() function.

void loop()
{
    if( Serial.available() > 0 )
    {
        y = Serial.read();
        Serial.println( y );
    }
}

asharNK:
I tried Software serial as well, it had the same problem as i mentioned with hardware serial.

Post that code - you probably have some small mistake. It should work fine.

...R

@Robin 2, here you go sir, software serial:

//Transmitter

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

int x=2;

void setup()

{ Serial.begin(9600);
mySerial.begin(9600); }

void loop() {
mySerial.println(x);
Serial.println(x);
}

//Receiver
#include <SoftwareSerial.h>

SoftwareSerial mySerial(11, 10); // RX, TX
int y;

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

void loop() {
if (mySerial.available()) {
y=mySerial.read();
}
Serial.println(y);
}

How have you the two Arduinos connected?

Do you have GND connection between them?

You are not taking account of how fast loop() repeats. Try adding delay(1000); into loop() in your Tx program.

It would probably also help if you print some text so you know what you are looking at in the Serial Monitor - for example Serial.print("sent to Arduino "); and Serial.print("received from Arduino ");

...R

I have both arduinos powered from the same PC but i also have grounds of both connected just to be sure. Okay I will try it with delay and text as soon as possible. Thanks for the help :slight_smile: