// Pin Definitions
const int TRIG_PIN = 7; // Trigger pin for HC-SR04
const int ECHO_PIN = 6; // Echo pin for HC-SR04
const unsigned int MAX_DIST = 23200; // Maximum pulse duration for 400 cm
// Variables for Ultrasonic Sensor and Potentiometer
unsigned long t1, t2, pulse_width;
float measuredRange, actualRange = 150.0; // User-defined actual range (e.g., 50 cm)
float error, percentageError;
float frequency;
// Time for Frequency Measurement
unsigned long currentTime, previousTime = 0;
unsigned long period;
// Setup Function
void setup() {
pinMode(TRIG_PIN, OUTPUT); // Trigger pin as OUTPUT
pinMode(ECHO_PIN, INPUT); // Echo pin as INPUT
Serial.begin(9600); // Start serial communication
}
// Main Loop
void loop() {
// Part 1: Ultrasonic Sensor Measurement
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH); // Send trigger pulse
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the echo pulse width
while (digitalRead(ECHO_PIN) == 0); // Wait for the start of the echo pulse
t1 = micros(); // Get start time
while (digitalRead(ECHO_PIN) == 1); // Wait for the end of the echo pulse
t2 = micros(); // Get end time
pulse_width = t2 - t1; // Calculate pulse width
// Calculate the measured range in centimeters
measuredRange = pulse_width / 58.0;
// Ensure measured range doesn't exceed the sensor's limit
if (pulse_width > MAX_DIST) {
Serial.println("Out of range");
} else {
// Part 2: Calculate Error and Percentage Error
error = abs(actualRange - measuredRange); // Always positive error using abs()
percentageError = (error / actualRange) * 100; // Percentage error
// Part 4: Frequency Measurement
currentTime = millis(); // Get current time
if (previousTime > 0) {
period = currentTime - previousTime; // Calculate the period (in milliseconds)
frequency = 1000.0 / period; // Calculate frequency in Hz
// Print all results
Serial.print("Actual Range: ");
Serial.print(actualRange);
Serial.print(" cm, Measured Range: ");
Serial.print(measuredRange);
Serial.print(" cm, Error: ");
Serial.print(error);
Serial.print(" cm, Percentage Error: ");
Serial.print(" V, Frequency: ");
Serial.print(frequency);
Serial.println(" Hz");
}
previousTime = currentTime; // Update the previous time
}
delay(2500); // Delay for half a second before the next loop
}