-
1Setting Up Code
Copy this Code into Arduino:
// constants won't change
const int TRIG_PIN = 14; // Arduino pin connected to Ultrasonic Sensor's TRIG pin
const int ECHO_PIN = 13; // Arduino pin connected to Ultrasonic Sensor's ECHO pin
const int LED_PIN = 16; // Arduino pin connected to LED's pin
const int BUZZER_PIN = 2; const int MIN_DISTANCE = 10; // Minimum distance for LED on (cm)
const int MAX_DISTANCE = 50; // Maximum distance for LED on (cm)long duration;
float duration_us, distance_cm;void setup() {
Serial.begin(9600); // Initialize serial port
pinMode(TRIG_PIN, OUTPUT); // Set TRIG_PIN as output
pinMode(ECHO_PIN, INPUT); // Set ECHO_PIN as input
pinMode(LED_PIN, OUTPUT); // Set LED_PIN as output
pinMode(BUZZER_PIN, OUTPUT); // Set BUZZER_PIN as output
}void loop() {
// Send a 10-microsecond pulse to TRIG pin to start the measurement
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);// Measure the duration of the pulse received by ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH);// Calculate the distance in cm (speed of sound is 0.034 cm/us)
distance_cm = (duration_us * 0.034) / 2; // Divide by 2 because pulse travels to object and back// Check if the distance is within the defined range
if (distance_cm >= MIN_DISTANCE && distance_cm <= MAX_DISTANCE) {
digitalWrite(LED_PIN, HIGH); // Turn on LED
tone(BUZZER_PIN, 1000); // Generate tone (1 kHz frequency for active buzzer)
} else {
digitalWrite(LED_PIN, LOW); // Turn off LED
noTone(BUZZER_PIN); // Stop buzzer sound
}// Print the distance to Serial Monitor
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.println(" cm");delay(500); // Wait for 500 ms before taking another measurement
} -
2Create box to put machine in
-
3Follow this tutorial to put all the parts together
-
4Final Step
Put the machine you just build from the tutorial into the box you 3d printed and plug it into a computer capable of running arduino then download the code you pasted into ardiuno onto the machine.
James
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.