0

I'm trying to connect two Arduinos according to the example in Example

I added a bit of debug prints so the code looks like:

#include <Wire.h>

// Include the required Wire library for I2C<br>#include <Wire.h>
int LED = 13;
int x = 0;
void setup() {
  // Define the LED pin as Output
  pinMode (LED, OUTPUT);
  // Start the I2C Bus as Slave on address 9
  Wire.begin(9); 
  // Attach a function to trigger when something is received.
  Wire.onReceive(receiveEvent);
  Serial.begin(9600);
}
void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
  Serial.println(x);
}

void loop() {
  //If value received is 0 blink LED for 200 ms
  Serial.print("x = '");
  Serial.print(x);
  Serial.println("'");
  if (x == '0') {
    Serial.println("Do 0");
    digitalWrite(LED, HIGH);
    delay(200);
    digitalWrite(LED, LOW);
    delay(200);
  }
  //If value received is 3 blink LED for 400 ms
  if (x == '3') {
    Serial.println("Do 3");
    digitalWrite(LED, HIGH);
    delay(400);
    digitalWrite(LED, LOW);
    delay(400);
  }
}

The strange thing is, the terminal gives the following information:

...
x = '2'
x = '2'
x = '2'
x = '2'
x = '2'
x3= '3'
x = '3'
x = '3'
x = '3'
x = '3'
...

However, I never see the expected "Do 3" lines. Why is that? I assume if (x == '3) would return true when x = '3'?

Also I see the x3 = '3'instead of x = '3'... now I print x also while an event is received, but are those in two different threads since the expected text would be "3x = '3'") or "x = '3'3"

  • 2
    Have you tried if (x == 3)? – KIIV Mar 29 '17 at 21:20
  • @KIIV No ... however it works (that was the main problem)... Ah now I see, it's an integer ... strange the website itself contains an error. I would expect initially strings/characters to be sent but it seems everything can be sent. Thanks! – Michel Keijzers Mar 29 '17 at 21:23
  • 2
    Maybe the author of that instructable never tested it. – KIIV Mar 29 '17 at 21:44
2

Following code is printing value of integer as string.

int x = 0;
...
Serial.print("x = '");
Serial.print(x);
Serial.println("'");

It prints x = '3' for numeric value 3. But ASCII value for character '3' is actually 51.

And about the second issue - reveiveEvent is called from receive ISR asynchronously, so it's completely random when the main code gets interrupted. Btw printing anything inside of ISR is quite tricky. If the output buffer is full or will be filled up inside of ISR, everything gets deadlocked as it needs ISRs enabled.

  • I really missed the 'int' indeed. And thanks about the comment about the ISR ... it was just for testing purposes. I know it's not good to process much things in an ISR (from my regular job). – Michel Keijzers Mar 29 '17 at 21:50

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.