/*
Grove Buzzer
The example uses a buzzer to play notes.
The circuit:
* Buzzer attached to Pin 39 (J14 plug on Grove Base BoosterPack)
* Ultrasonic Ranger attached to Pin 24 (J6 plug on Grove Base BoosterPack)
*/
#include "TM1637.h"
#include "Ultrasonic.h"
/* Macro Define */
#define BUZZER_PIN 39 /* sig pin of the Grove Buzzer */
#define ULTRASONIC_PIN 24 /* pin of the Ultrasonic Ranger */
int tempo = 300;
/* Global Variables */
Ultrasonic ultrasonic(ULTRASONIC_PIN); /* Ultrasonic Ranger object */
int distance = 0; /* variable to store the distance to obstacles in front */
/* the setup() method runs once, when the sketch starts */
void setup()
{
/* set buzzer pin as output */
pinMode(BUZZER_PIN, OUTPUT);
}
void loop()
{
distance = ultrasonic.MeasureInCentimeters(); /* read the value from the sensor */
loopThruNotes(distance);
delay(300);
}
void loopThruNotes(int distance) {
if (distance < 10) {
playTone(110, tempo);
}
else if (distance < 20) {
playTone(123, tempo);
}
else if (distance < 30) {
playTone(131, tempo);
}
else if (distance < 40) {
playTone(147, tempo);
}
else if (distance < 50) {
playTone(165, tempo);
}
else if (distance < 60) {
playTone(175, tempo);
}
else if (distance < 70) {
playTone(195, tempo);
}
else if (distance < 80) {
playTone(220, tempo);
}
}
/* play tone */
void playTone(int tone, int duration)
{
for (long i = 0; i < duration * 1000L; i += tone * 2)
{
digitalWrite(BUZZER_PIN, HIGH);
delayMicroseconds(tone);
digitalWrite(BUZZER_PIN, LOW);
delayMicroseconds(tone);
}
}
Comments
Please log in or sign up to comment.