Arduino.通过tone()控制无源蜂鸣器输出音频震荡信号实现发声

标签:
arduino蜂鸣器音频震荡信号 |
先来一段常见的Arduino代码
unsigned char i,j;
for(i=0;i<200;i++){
digitalWrite(PIN_BUZZER,HIGH);
delay(1);
digitalWrite(PIN_BUZZER,LOW);
delay(1);
}
for(i=0;i<100;i++){
digitalWrite(PIN_BUZZER,HIGH);
delay(2);
digitalWrite(PIN_BUZZER,LOW);
delay(2);
}
void buzzerVoice(){
}
能够发声, 但太不好听
要生产音频脉冲,只要算出某一音频的周期(1/频率),可以利用定时器计时的方式得到此频率的脉冲
Arduino官方封装了一个方法tone(), 详细说明如下
tone()
Description
Generates a square wave of the specified frequency (and 50%
duty cycle) on a pin. A duration can be specified, otherwise the
wave continues until a call to noTone(). The pin can be connected
to a piezo buzzer or other speaker to play tones.
Only one tone can be generated at a time. If a tone is already
playing on a different pin, the call to tone() will have no effect.
If the tone is playing on the same pin, the call will set its
frequency.
Use of the tone() function will interfere with PWM output on
pins 3 and 11 (on boards other than the Mega).
It is not possible to generate tones lower than 31Hz. For
technical details, see Brett Hagman's notes.
NOTE: if you want to play different pitches on multiple pins,
you need to call noTone() on one pin before calling tone() on the
next pin.
Syntax
tone(pin, frequency)
tone(pin, frequency, duration)
Parameters
pin: the pin on which to generate the tone
frequency: the frequency of the tone in hertz - unsigned
int
duration: the duration of the tone in milliseconds (optional)
- unsigned long
Returns
nothing
tone(pin,
frequency),Arduino会向指定pin发送制定频率的方波,执行noTone()函数来停止。
tone(pin, frequency,
duration方法多了一个参数,代表发送方波持续的时间,到时自动停止发送信号,就不需要noTone()函数。
利用tone()函数播放音乐,只需要查表了解各个音符对应的频率
实际例子:
tone(PIN_BUZZER,330,500);
前一篇:TTL232和RS232的区别
后一篇:ssh安全的免密码自动登录