加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

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

(2015-09-29 15:41:56)
标签:

arduino

蜂鸣器

音频震荡信号

先来一段常见的Arduino代码

void buzzerVoice(){
  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);
  }
}
能够发声, 但太不好听

要生产音频脉冲,只要算出某一音频的周期(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);

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有