Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int speakerPin = 10, length = 26, tempo = 300, duration, distance;
- int beats[] = { 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2};
- char notes[] = "eeeeeeegcde";
- const int trigPin = 5;
- const int echoPin = 4;
- const int trigDistance = 100;
- void playTone(int tone, int duration);
- void playNote(char note, int duration);
- void setup() {
- pinMode(speakerPin, OUTPUT);
- pinMode(trigPin, OUTPUT);
- pinMode(echoPin, INPUT);
- }
- void loop() {
- digitalWrite(trigPin, LOW);
- digitalWrite(trigPin, HIGH);
- delay(1);
- digitalWrite(trigPin, LOW);
- duration = pulseIn(echoPin, HIGH);
- distance = duration * 0.034 / 2;
- if (distance <= trigDistance) {
- for (int i = 0; i < length; i++) {
- if (notes[i] == ' ') {
- delay(beats[i] * tempo);
- } else {
- playNote(notes[i], beats[i] * tempo);
- }
- delay(tempo / 2);
- }
- }
- delay(10000);
- }
- void playTone(int tone, int duration) {
- for (long i = 0; i < duration * 1000L; i += tone * 2) {
- digitalWrite(speakerPin, HIGH);
- delayMicroseconds(tone);
- digitalWrite(speakerPin, LOW);
- delayMicroseconds(tone);
- }
- }
- void playNote(char note, int duration) {
- char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
- int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
- for (int i = 0; i < 8; i++) {
- if (names[i] == note) {
- playTone(tones[i], duration);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement