How to stop two arduino from communicating?

Hi everyone, I have the following code for the sender:
(I connected two boards with pins TX, RX)

void setup() {
  // put your setup code here, to run once:
   Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
 Serial.write(13);
}

And for the receiver:

int receive = 0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
   if(Serial.available())
   {
    receive = Serial.read();
    if(receive == 13)
    {
      Serial.print("I love arduino");
    }
   }
}

When I go to the serial port monitor, I can see the words "I love arduino" appear every second. And that's what I want to achieve, except I don't want subtitles to last forever. What do I do to stop broadcasting after sending a message?

If your intent is for it to happen once, when the Arduinos wake up, then put it in setup, not in loop().

Put the print message in the setup() portion of code. The loop can be loop(){}. It will print once then stop. I would add this to the code Serial.print("\n\n\tI love..."); That will give you two blank lines at the start and tab the message in to make it easier to read.

But clearly, you need a power up sequence so that A starts sending 13, B wakes up, sees that and acknowledges, then A stops sending 13.
At least, that's what I make of your somewhat tenuous description of what needs to happen.
C

???

You could set a flag to indicate that the message has already been set:

   {
    static boolean messageHasBeenSent = false;
    receive = Serial.read();
    if(receive == 13 && messageHasBeenSent == false)
    {
      Serial.print("I love arduino");
      messageHasBeenSent = true;
    }
   }

The 'static' means "This variable is initialized once, and (if changed) keeps its (changed) value even after the function ends." Without it, the variable would be re-created and re-initilized every time that line was executed.

Thank you, it helped me! :grinning:

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