如何解决在一个函数中运行不同长度的数组
我想在我的 Arduino 上制作一个蜂鸣器,一个接一个地播放不同的歌曲。我已经把音符放在数组中来组成歌曲和一个函数来调用不同的数组。我的问题是数组的长度不同,这会导致我播放它们时歌曲被剪切。我已经在“int arrSize”中定义了长度,并将其设置为名为 MikkelRev_melody 的数组的长度,但是较长的歌曲会被剪切掉。有没有人知道解决这个问题的好方法?
这是我的代码:
int buzzer = 13;
int tempo = 120; //melodiens tempo i bpm
//Defining the needed notes
#define T_C 262
#define T_D 294
#define T_E 330
#define T_F 349
#define T_G 392
#define T_A 440
#define T_Ab 466
#define T_B 493
#define T_C2 523
#define T_D2 587
//arrays with notes
int AlleFugler_melody[] = {T_C,T_E,T_G,T_C2,T_A,T_F,T_C,T_D,T_C};
int MikkelRev_melody[] = {T_E,T_G};
int LisaGikkTilSkolen_melody[] = {T_C,T_C};
int LilleMaltrost_melody[] = {T_E,T_D};
int BjornenSover_melody[] = {T_C,T_C};
int BamsesFodselsdag_melody[] = {T_C2,T_D2,T_Ab,T_F};
//duration of each note
int AlleFugler_durations[] = {2,4,6,2,2};
int MikkelRev_durations[] = {4,2};
int LisaGikkTilSkolen_durations[] = {4,2};
int LilleMaltrost_durations[] = {6,2};
int BjornenSover_durations[] = {4,2};
int BamsesFodselsdag_durations[] = {4,2};
void setup()
{
pinMode(13,OUTPUT);
PlaySong(LisaGikkTilSkolen_melody,LisaGikkTilSkolen_durations,tempo);
PlaySong(MikkelRev_melody,MikkelRev_durations,tempo);
PlaySong(AlleFugler_melody,AlleFugler_durations,tempo);
PlaySong(LilleMaltrost_melody,LilleMaltrost_durations,tempo);
PlaySong(BjornenSover_melody,BjornenSover_durations,tempo);
PlaySong(BamsesFodselsdag_melody,BamsesFodselsdag_durations,tempo);
}
void loop()
{
}
void PlaySong(int notes[],int durations[],int BPM)
{
int arrSize = sizeof(MikkelRev_melody)/sizeof(int); //leanght of array playing
for (int thisNote = 0; thisNote < arrSize; thisNote++)
{
int noteDuration = (int)((750 * (120 * 2 / BPM)) / durations[thisNote] + 0.); //defining duration of tone
tone(buzzer,notes[thisNote],noteDuration);
int pauseBetweenNotes = noteDuration * 1.20; //defining pause between tones
delay(pauseBetweenNotes); //leanght of tone
noTone(buzzer); //add pause between tones
}
delay(1000); //one second pause before next song
}
解决方法
有多种方式。我会像 C 字符串那样做。再定义一个值为 0 或 -1 的音符并将其放在每个数组的末尾。然后迭代数组,直到达到该值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。