I am developing a multi-master scenario sketch with the https://github.com/rambo/I2C library, because this library will handle multi-master data collisions.
I created a setup with two Arduino nano's which act both as master and slave.
My sketch works as long as I use only one master. Sending data from one Arduino to the other works fine. The other receives the data.
But when I sequentially try to send data from the second Arduino to the first, I get an error (32). After that even sending data from the initial Arduino results in error 32.
This is the used sketch for both the Arduino's. The only difference is that I switch the values of rel_address and own_address when programming the seconds Arduino.
Sending data is done by pressing a button on pin 2 (switchPin)
/**
atme328 = ATmega328
SDA --> Pin A4
SCL --> Pin A5
*/
#include <I2C.h>
#include <Wire.h>
int switchPin = 2;
int relayOnPin = 3;
int relayOffPin = 4;
uint8_t broadcast_address = 0;
uint8_t own_address = 11; // CHANGE FOR EVERY MODULE!!
// rel_address = address of relay to switch; SET to own_address if relay is connected to this chip!
uint8_t rel_address = 10; // CHANGE FOR EVERY MODULE!! SET to own_address if relay is connected to this chip!
uint8_t rpi_address = 1;
unsigned long counter = 0;
void setup() {
Serial.begin(9600);
pinMode(switchPin, INPUT_PULLUP);
pinMode(relayOnPin, OUTPUT);
pinMode(relayOffPin, OUTPUT);
// start condition
digitalWrite(relayOnPin, HIGH);
digitalWrite(relayOffPin, LOW);
I2c.begin();
I2c.timeOut(50);
// I2c.pullup(true); // done by external 4.7kOhm resistors
// config Wire library for I2C slave functionality
Wire.begin( own_address );
TWAR = (own_address << 1) | 1; // enable broadcasts to be received!
// set slave receive callback
Wire.onReceive( onI2CReceive );
}
void loop() {
counter = counter + 1;
if (counter == 20000) {
digitalWrite(relayOnPin, LOW);
digitalWrite(relayOffPin, LOW);
}
if ( digitalRead(switchPin) == LOW ) {
sendCmd('d', rel_address); // send command to remote relay
}
}
void sendCmd(uint8_t cmd, uint8_t address) {
uint8_t status = I2c.write(address, cmd); //configure device for continuous mode
if (status > 0) {
// error codes at https://github.com/rambo/I2C/blob/master/I2C.cpp
Serial.print(status, DEC);
Serial.print('!');
digitalWrite(relayOffPin, HIGH);
delay(50);
} else {
digitalWrite(relayOnPin, HIGH);
Serial.print('.');
}
counter = 0;
}
void onI2CReceive(int howMany) {
// loops, until all received bytes are read
while (Wire.available() > 0) {
digitalWrite(relayOffPin, HIGH);
Serial.write(Wire.read());
}
counter = 0;
}
What do I need to do to be able to send from two units using this library? Thanks!