issue using HC-SR04 with i2c

so set up is as follows. I have HC-SR04 attached to a slave arduino and another master arduino is requesting the distance from the slave.

but when checking the serial out of the master i just get, 0s and 1s going back and forth. but when i fix the output value on the slave side. i,e i dont actually use the measured value and just force the output to say 11, the master prints 11. also when i check the serial out on the slave side directly even inside the the call back the values make sence. no idea whats going on heres the code.


#include <NewPing.h>
#include <Wire.h> 
#define TRIGGER_PIN  4
#define ECHO_PIN     3
#define MAX_DISTANCE 200
unsigned int dist;

void setup() {
void loop() {
  dist = sonar.ping_cm();

void requestEvent() {

 Wire.write((byte *)&dist, sizeof(unsigned int));


#include <Wire.h>
unsigned int dist=3;
byte buff[2];
void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output

void loop() {  
  Wire.requestFrom(8, 2);    // request 6 bytes from slave device #8
     Wire.readBytes( buff, 2);
     dist = ((buff[1] << 8) | buff[0]);

test_ultrasonic.ino (424 Bytes)

test_dummy_ultra.ino (393 Bytes)

I'm no expert on this, but since your max distance is 200, your distance can fit in a byte. So I think you could simplify your slave code by declaring dist as a byte, casting sonar.ping_cm() (which is an unsigned long) to a byte, and just using Wire.write(dist). And your master code could be simplified by deleting the buffer, declaring dist a byte, deleting the bit shifting, requesting one byte, and just doing a Maybe that would help with your problem...maybe not.