Arduino Mega 2560 LESSON:6 アクティブブザー
概要
アクティブブザーの実験をするLESSONです。
アクティブブザーは音源を内蔵していて、それを鳴らすという構造のため、高価ですが、制御できるものがすくなく鳴らすか鳴らさないかという2択しかないです。次のレッスンのパッシブは逆に音源はないので、スピーカーに音の元である周波数のある信号をながせばその周波数で圧電素子が振動するため、音がなります。
結線図はアクティブスピーカーと自体は存在せず、Tinkercadで示せませんでした。でも結線図はアクティブスピーカーでもパッシブスピーカーでも同じようなものなので、代わりにパッシブブザーで示します。
完成図は以下のようなモノです。
//www.elegoo.com
//2023.05.06
int buzzer = 12;//the pin of the active buzzer
void setup()
{
pinMode(buzzer, OUTPUT); //initialize the buzzer pin as an output
}
void loop()
{
int sound_duration = 500;
for (int i = 0; i < 20; i++)
{
//use the if function to gradually shorten the interval of the sound
if (i < 5)
{
sound_duration = 500;
} else if (i < 10)
{
sound_duration = 300;
} else if (i < 20)
{
sound_duration = 100;
}
//activate the active buzzer
digitalWrite(buzzer, HIGH);
delay(sound_duration);//wait for sound_duration ms
//deactivate the active buzzer
digitalWrite(buzzer, LOW);
delay(sound_duration);//wait for sound_duration ms
}
//activate the active buzzer
digitalWrite(buzzer, HIGH);
delay(5000);//keep playing sound for 5 seconds.
}