hi , I have writing code on arduino ide platform for a scenario.
const int inputPin = 4; // Input pin PB4
unsigned long pulseStartTime = 0;
unsigned long pulseEndTime = 0;
#define I2C_SLAVE_ADDRESS 0x48 // Address of the slave
#include <TinyWireM.h>
void setup() {
pinMode(inputPin, INPUT);
TinyWireM.begin();
TinyWireM.beginTransmission(I2C_SLAVE_ADDRESS); // Initialize I2C communication
}
void loop() {
// Wait for the rising edge
while (digitalRead(inputPin) == LOW) {
// Do nothing
}
// Record the start time of the pulse
pulseStartTime = micros();
// Wait for the falling edge
while (digitalRead(inputPin) == HIGH) {
// Do nothing
}
// Record the end time of the pulse
pulseEndTime = micros();
// Calculate pulse width
unsigned long pulseWidth = pulseEndTime - pulseStartTime;
float frequency = 1000000.0 / pulseWidth; // Calculate frequency in Hz
// Convert frequency to bytes for I2C transmission
uint8_t frequencyBytes[4]; // Assuming frequency will fit within 4 bytes
memcpy(frequencyBytes, &frequency, sizeof(frequency));
// Send frequency bytes over I2C
TinyWireM.write(frequencyBytes, sizeof(frequencyBytes));
// End transmission
TinyWireM.endTransmission();
// Delay before next measurement
delay(100);
}
slave code ( arduino uno )
#include <Wire.h>
const int slaveAddress = 0x48;
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 bps.
Wire.begin(slaveAddress); // Join i2c bus with the address specified as slaveAddress
Wire.onReceive(receiveEvent); // Register the receive event function
Serial.println("Ready to receive frequency data...");
}
void loop() {
// Nothing to do here, all processing occurs in the receiveEvent function.
delay(100); // Optional: slight delay to ease the CPU workload if needed.
}
// Function called by the Wire library when data is received.
void receiveEvent(int howMany) {
if (howMany >= 4) { // Ensure we have at least 4 bytes for a float value
byte frequencyBytes[4];
for (int i = 0; i < 4; ++i) {
if (Wire.available()) {
frequencyBytes[i] = Wire.read(); // Read a byte from the I2C buffer
}
}
float frequency;
memcpy(&frequency, frequencyBytes, sizeof(frequency)); // Recompile the bytes back into the single float
// Print the frequency to Serial Monitor
Serial.print("Received Frequency: ");
Serial.print(frequency);
Serial.println(" Hz");
}
else {
Serial.println("Error: Not enough bytes received");
}
}