用Arduino来演奏Despacito教程

用Arduino来演奏Despacito教程

演示视频:

Arduino 演奏西班牙神曲 Despacito

接线图:

用Arduino来演奏Despacito教程_第1张图片
程式/代码:

/*
 * Project: Despacito
 * 
 * Author: Mun Kim   [email protected]
 * Last Edited: Dec.31st.2020
 */

#define Speaker 3      // speaker signal on D3
#define Drum 5         // relay signal on D5
#define Interval 160
#define NoteSpacing 16

const uint16_t Notes[]={
     0,31,33,35,37,39,41,44,46,49,52,55,58,62,65,69,73,78,82,87,93,98,104,110,117,123,131,139,147,156,165,175,185,196,208,220,233,247,262,277,294,311,330,349,370,392,415,440,466,494,523,554,587,622,659,698,740,784,831,880,932,988,1047,1109,1175,1245,1319,1397,1480,1568,1661,1760,1865,1976,2093,2217,2349,2489,2637,2794,2960,3136,3322,3520,3729,3951,4186,4435,4699,4978};
const uint16_t SongLength=64;
//notes to play
const uint8_t SpeakerTick[]={
     52,0,0,0,51,0,0,0,49,0,44,0,44,44,44,44,44,49,49,49,49,0,47,49,0,0,45,0,45,45,45,45,45,49,49,49,49,0,51,52,0,0,47,0,47,47,47,47,52,51,52,51,52,0,54,54,0,51,0,0,0,0,0,0};
//duration of each notes
const uint8_t NoteLength[]={
     4,0,0,0,4,0,0,0,2,0,1,0,1,1,1,1,1,1,1,1,2,0,1,1,0,0,1,0,1,1,1,1,1,1,1,1,2,0,1,1,0,0,1,0,1,1,1,1,1,1,1,1,2,0,1,2,0,3,0,0,0,0,0};
//duration of each relay tick
const uint8_t DrumTick[]={
     0,0,0,0,0,0,0,0,30,0,0,5,5,0,5,0,30,0,0,5,5,0,5,0,30,0,0,5,5,0,5,0,30,0,0,5,5,0,5,0,30,0,0,5,5,0,5,0,30,0,0,5,5,0,5,0,30,0,0,5,5,0,5,0};

void setup() {
     
  pinMode(Speaker,OUTPUT);
  pinMode(Drum,OUTPUT);
}

uint16_t ctr=0,t=0;

void loop() {
     
  t=millis();
  if(NoteLength[ctr]!=0){
     
    noTone(Speaker);
    if(SpeakerTick[ctr]!=0) tone(Speaker,Notes[SpeakerTick[ctr]],NoteLength[ctr]*Interval-NoteSpacing);
  }
  if(DrumTick[ctr]!=0){
     
    digitalWrite(Drum,HIGH);
    delay(DrumTick[ctr]);
    digitalWrite(Drum,LOW);
  }
  ctr=(ctr+1) ;
  delay(Interval-(millis()-t));
}

你可能感兴趣的:(arduino)