Kryptomatrix Kryptomatrix - 2 months ago 30
C++ Question

I2C communication Raspberry Pi 3 and Arduino

(sorry for bad English, I'm German)

Hello programmers,

I'm trying (without success) to send data from an Raspberry Pi 3(master) to an Arduino(slave):

Here's my Arduino Code:

#include <Wire.h>
void wireHandler(int numBytes)
{
while(true)
{
digitalWrite(13, HIGH);
delay(400);
digitalWrite(13, LOW);
delay(400);
}
}
void setup()
{
pinMode(13, OUTPUT);
Wire.begin(0x23);
Wire.onReceive(wireHandler);
}
void loop()
{
}


My Raspy code (C++, g++ main.cpp -lwiringPi):

#include <iostream>
#include <wiringPi.h>
#include <wiringPiI2C.h>
int main(void)
{
if(wiringPiSetup() == -1)
{
std::cerr << "wiringPiSetup() == -1\n";
return 1;
}
if(wiringPiI2CSetup(0x39) == -1)
{
std::cerr << "wiringPiI2CSetup(int) == -1\n";
return 1;
}
while(true)
{
wiringPiI2CWrite(0x23, 0x23);
delay(100);
}
}


In theory this should make the Arduino Led (pin 13) blink.
However the led stays dark.

I would be thankful if anyone could explain me why this program does not work and how to fix it.

And yes I2C is activated in Raspi-Config.

Answer

The Wire.onReceive() handler is called from ISR handler and therefore all other ISRs are blocked. Including the one counting millis and without it, delay() can't work as it's relying on millis.

For example some volatile variable should be updated by this event and handled in loop(), as ISR handlers must be as short as possible.

Comments