0

I'm a total noob when it comes to Arduino. I'm slowly learning stuff. I was trying this code which basically gets input in Arduino1(master) and displays the character in serial monitor of Arduino2(slave). The code words just find but I just need the slave to wait until the master sends the next character. Right now, the slave is continuously printing the character.

Master code:

    #include "Wire.h"
    char ch;

    void setup() {

      Serial.begin(9600);
      Wire.begin();

    }

     void loop() {
      while(Serial.available()==0)
      {}
      ch=Serial.read();
      delay(1000);
      Serial.print("The character that you entered is ");
      Serial.println(ch);

      Wire.beginTransmission(9);
      Wire.write(ch);
      Wire.endTransmission();

        }

Slave code:

#include "Wire.h"
char x;

void setup() {

  Serial.begin(9600);
  Wire.begin(9);
  Wire.onReceive(Event);

}
void Event(char bytes){
  x = Wire.read();
}

void loop() {

  Serial.print("The character that you entered in the other Arduino is ");
  Serial.println(x);
}

I know that this will be simple but I just can't quite figure out what to do. Please help me out

  • Changed the code. Please check now – Kishore Oct 28 '18 at 13:08
  • send more bytes, read more bytes. collect bytes into a buffer, send the whole buffer and receive a buffer – Juraj Oct 28 '18 at 13:29
  • @Juraj Please translate this into noob language. Sorry. Is there any modification to the code that I can do so I can get the slave to do this? – Kishore Oct 28 '18 at 13:39
  • see master_writer and slave_reader examples in IDE File menu – Juraj Oct 28 '18 at 14:04
2
#include "Wire.h"
volatile char x;
volatile bool received;

void setup() {
  Serial.begin(9600);
  Wire.begin(9);
  Wire.onReceive(Event);
}

void Event(char bytes){
  x = Wire.read();
  received = true;
}

void loop() {

  if (received) {
    received = false;
    Serial.print("The character that you entered in the other Arduino is ");
    Serial.println(x);
  }
}
  • Make both volatile? – Jot Oct 30 '18 at 3:32
  • yes, it is called from interrupt of course. – Juraj Oct 30 '18 at 6:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.