Skip to content

Instantly share code, notes, and snippets.

@silbo
Last active August 17, 2018 10:11
Show Gist options
  • Save silbo/b4baa296322daacfe2fde1816a5eb28e to your computer and use it in GitHub Desktop.
Save silbo/b4baa296322daacfe2fde1816a5eb28e to your computer and use it in GitHub Desktop.
Piezzo buzzer and ultrasonic sensor
// Add ultrasonic distance sensor library
#include <NewPing.h>
// Disntance sensor
static const int echo_pin = 2;
static const int trigger_pin = 3;
static const int max_distance = 200;
// Piezzo buzzer
static const int piezo_pin = 11;
static const int beep_duration = 10;
static const int beep_frequency = 1000;
// Initialize the ultrasonic sensor
NewPing sonar(trigger_pin, echo_pin, max_distance);
// This functions only runs once
void setup() {
Serial.begin(9600);
}
// This functions runs in a loop
void loop() {
// Make a 1000 Hz and 10 millisecond beep
tone(piezo_pin, beep_frequency, beep_duration);
// Get the ultrasonic sensor distance
int distance = sonar.ping_cm();
// Send the distance reading to the computer
Serial.print("distance: ");
Serial.println(distance);
// When the sonar gives 0, it means it
// didn't receive a response back, so
// we set the distance to 1000
if (distance == 0) {
distance = 1000;
}
// Wait "distance" milliseconds
delay(distance);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment