runman69:
thanks for the reply Australia
I am Nick Gammon:
I live in Australia:
You want to do something more like this:
#include <Wire.h>
const int pingPin = 7;
long duration, cm;
void setup()
{
Wire.begin(2); // join i2c bus with address #2
Wire.onRequest(requestEvent); // register event
}
void loop()
{
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
noInterrupts ();
cm = microsecondsToCentimeters(duration);
interrupts ();
delay(50);
}
long microsecondsToCentimeters(long microseconds)
{
return (microseconds / 29 / 2);
}
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent()
{
Wire.write(cm);
}
I've made "cm" a global variable, so you can access it in requestEvent. There is still the issue that Wire.write will only write a single byte. That will be OK if the number of cm is an integer (no decimal places) and is in the range 0 to 255.