风筝
发表于: 2016-10-21 09:54:58 | 显示全部楼层

音调跟随器(Pitch follower using the tone() function)

本示例展示了如何使用tone()命令产生一个随着模拟输入值变化的音调。使用光敏电阻,Arduino或者Genuino变成一个简化的光感泰勒明(theremin)。


所需硬件

-    Arduino或者Genuino开发板

-    8欧扬声器

-   光敏电阻

-   4.7K电阻

-   100欧电阻

-    导线

-   面包板


电路连接方式

arduino_speaker_photocell_bb.png

将扬声器的一端通过一个100欧的电阻连接到Arduino的数字9脚,另一端连接到地。使用5V给光敏电阻供电,然后连接到模拟输入A0,同时添加一个4.7K的电阻连接到地。


原理图

arduino_speaker_photocell_schem.png


代码

本示例的代码比较简单。只需要采集一个模拟信号输入,然后将该值映射成一系列可听音调。人能够听见20-20,000HZ的声音,但本示例比较适合使用120-1,500HZ的声音。

您需要获取映射的模拟输入的实际范围。 在所示的电路中,模拟输入值范围从约400欧到约1,000欧。 更改map()命令中的参数来匹配传感器的范围。

以下是主要的程序:

  1. /*
  2.   Pitch follower

  3. Plays a pitch that changes based on a changing analog input

  4. circuit:
  5. * 8-ohm speaker on digital pin 9
  6. * photoresistor on analog 0 to 5V
  7. * 4.7K resistor on analog 0 to ground

  8. created 21 Jan 2010
  9. modified 31 May 2012
  10. by Tom Igoe, with suggestion from Michael Flynn

  11. This example code is in the public domain.

  12. http://www.arduino.cc/en/Tutorial/Tone2

  13. */


  14. void setup() {
  15.   // initialize serial communications (for debugging only):
  16.   Serial.begin(9600);
  17. }

  18. void loop() {
  19.   // read the sensor:
  20.   int sensorReading = analogRead(A0);
  21.   // print the sensor reading so you know its range
  22.   Serial.println(sensorReading);
  23.   // map the analog input range (in this case, 400 - 1000 from the photoresistor)
  24.   // to the output pitch range (120 - 1500Hz)
  25.   // change the minimum and maximum input numbers below
  26.   // depending on the range your sensor's giving:
  27.   int thisPitch = map(sensorReading, 400, 1000, 120, 1500);

  28.   // play the pitch:
  29.   tone(9, thisPitch, 10);
  30.   delay(1);        // delay in between reads for stability
  31. }
复制代码

跳转到指定楼层
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题 700 | 回复: 1483



手机版|

GMT+8, 2024-5-9 03:17 , Processed in 0.039385 second(s), 7 queries , Gzip On, MemCache On. Powered by Discuz! X3.5

YiBoard一板网 © 2015-2022 地址:河北省石家庄市长安区高营大街 ( 冀ICP备18020117号 )

快速回复 返回顶部 返回列表