I2C troubles transferring data between slave to master

Hey Everyone,

So I've got a pulse output from a pump that I need to count and display.

I have 2 Arduinos (ATMEGA 328's).

The one arduino reads the pulses and add's the to variable x.

The other arduino requests the pulse count (via I2C) and then does further calculations(Haven't got that far yet).

Here is the I2C slave sketch:

#include <Wire.h>

long x;
byte ch;
const int PUMP = 13;
const int TRIG = 2;
int StaTe = 0;

void setup()  {
 pinMode(PUMP, OUTPUT);
 pinMode(TRIG, INPUT); 
 Wire.begin(9);
}

void loop()  {
  StaTe = digitalRead(TRIG);
  
  if(StaTe == HIGH)  {
    x++;
    digitalWrite(PUMP, HIGH);
    delay(100);
    digitalWrite(PUMP, LOW);
  }
  
  Wire.beginTransmission(10);
  ch = Wire.read();
  
  if(ch == 1)  {
    Wire.write(x);
  }
  else  {
  }
  Wire.endTransmission();
}

And here is the I2C Master Sketch:

#include <Wire.h>

byte cH = 1; //set to 1 so the slave device will send x
long val;

void setup()  {
 Wire.begin(10); 
 Serial.begin(9600);
}

void loop()  {
 Wire.beginTransmission(9);
 Wire.write(cH);
 val = Wire.read();
 Serial.println(val);
 Wire.endTransmission();
}

It needs to be over 2 arduino's because the master device will delay for 3 hours and the update the figures.

I'm not great at this but I think I've made a mistake by giving the master a number(10). Maybe you can't send data from a slave I2C device? It's reading -1 on the serial monitor even if I add a pulse on the slave.

Any help would much appreciated :grin: :grin:

Both your I2C sketches look almost 100% wrong. Not entirely your fault. The "instructions" for using Wire are very weak, and many of the published examples won't actually work. Nevertheless, some do work, and your code does not resemble any of those.

Maybe you can't send data from a slave I2C device?

You can "send" data from a slave I2C device, but not unilaterally. You have to get the master device to "ask" for it. Then you can send.

It needs to be over 2 arduino's because the master device will delay for 3 hours and the update the figures.

Why can't one Arduino read the pulse, do the calculations and display the results ? What has the 3 hour delay got to do with it, unless, of course, you were thinking of using delay() somewhere in the program (horror) ?

Banish the thought of using delay() and use millis() for timing as in the BlinkWithoutDelay example in the IDE. It illustrates a non blocking method of doing timing.