Created
September 19, 2014 10:32
-
-
Save cowdinosaur/880242d43651ed9aa93d to your computer and use it in GitHub Desktop.
Tinkerbot 3.6.2: Controlling a buzzer with proximity sensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <NewPing.h> | |
#include <NewTone.h> | |
const int ULTRASONIC_TRIGGER = 6; | |
const int ULTRASONIC_ECHO = 7; | |
const int BUZZER_PIN = 9; | |
#define MAX_DISTANCE 100 | |
NewPing sonar(ULTRASONIC_TRIGGER, ULTRASONIC_ECHO, MAX_DISTANCE); | |
void setup() { | |
pinMode(ULTRASONIC_TRIGGER, OUTPUT); | |
pinMode(ULTRASONIC_ECHO, INPUT); | |
pinMode(BUZZER_PIN, OUTPUT); | |
} | |
void loop() { | |
int distance = sonar.ping_cm(); | |
// If distance value is 0, it means that the object is very far away | |
if (distance == 0) { | |
distance = MAX_DISTANCE; | |
} | |
// We are only interested in the 10cm to 20cm range, so we constrain | |
// it to that range, and then map it to the brightness value (inverse map) | |
distance = constrain(distance, 10, 20); | |
// map the sensor values to a wide range of pitches | |
int pitch = map(distance, 10, 20, 50, 5000); | |
NewTone(9, pitch, 20); | |
// wait for a moment | |
delay(10); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment