Goodmorning everyone,
I have two Arduino MEGA and I would like them to communicate via serial. The first MEGA is connected to USB in order to have the serial monitor, but in the future it will not be. The second MEGA takes power from the first through Vin and is connected to it via Serial1.
Data exchange between the two MEGA, as I said, will be through Serial1 and the first relaunch everything that comes on the USB monitor.
Good theory. In practice not funziona.Dal first MEGA send an int on the second reading correctly and when the response is sent (another int or a string or a char or a byte or qulunque thing) the first MEGA does not see it. Buffer Serial1 it’ll be int he had previously sent to the second MEGA.
A little piece of code? I’ve found this on some website in internet. Here it is:
int val = 0;
int incoming = 0;
int incoming1 = 0;
void setup()
{
Serial.begin(115200); //Begin Serial to talk to the Serial Monitor
Serial1.begin(115200); //Begin Serial to talk to the Rx Arduino
Serial.println("Serial Monitor Connected");
Serial.parseInt(); //clear any garbage in the buffer.
}
void loop()
{
// From the USB
incoming = Serial.available();
while (incoming != 0) //while there is something to be read
{
val = Serial.parseInt();
if (val != 0)
{
Serial.print("Received input... Transmitting: ");
Serial.println(val); //Print value to the Serial Monitor
Serial1.print(val); //Send value to the Rx Arduino
}
incoming = Serial.available();
}
// From the Rx Arduino
incoming1 = Serial1.available();
while(incoming1 != 0) //While there is something to be read
{
val = Serial1.parseInt(); //Get new value
Serial.print("Receiving... ");
Serial.println(val); //Print new value to the Serial Monitor
incoming1 = Serial1.available();
}
}
Receiver:
int val = 0;
int incoming = 0;
void setup()
{
Serial1.begin(115200);
}
void loop()
{
incoming = Serial1.available();
while (incoming != 0) //While there is something to be read
{
val = Serial1.parseInt(); //Reads integers as integer rather than ASCI. Anything else returns 0
val = val + 5;
Serial1.print(val); //Send the new val back to the Tx
incoming = Serial1.available();
}
}
Thanx to everyone
D: