|
音调跟随器(Pitch follower using the tone() function)
本示例展示了如何使用tone()命令产生一个随着模拟输入值变化的音调。使用光敏电阻,Arduino或者Genuino变成一个简化的光感泰勒明(theremin)。
所需硬件
- Arduino或者Genuino开发板
- 8欧扬声器
- 光敏电阻 - 4.7K电阻 - 100欧电阻 - 导线
- 面包板
电路连接方式
将扬声器的一端通过一个100欧的电阻连接到Arduino的数字9脚,另一端连接到地。使用5V给光敏电阻供电,然后连接到模拟输入A0,同时添加一个4.7K的电阻连接到地。
原理图
代码 本示例的代码比较简单。只需要采集一个模拟信号输入,然后将该值映射成一系列可听音调。人能够听见20-20,000HZ的声音,但本示例比较适合使用120-1,500HZ的声音。 您需要获取映射的模拟输入的实际范围。 在所示的电路中,模拟输入值范围从约400欧到约1,000欧。 更改map()命令中的参数来匹配传感器的范围。
以下是主要的程序: - /*
- Pitch follower
- Plays a pitch that changes based on a changing analog input
- circuit:
- * 8-ohm speaker on digital pin 9
- * photoresistor on analog 0 to 5V
- * 4.7K resistor on analog 0 to ground
- created 21 Jan 2010
- modified 31 May 2012
- by Tom Igoe, with suggestion from Michael Flynn
- This example code is in the public domain.
- http://www.arduino.cc/en/Tutorial/Tone2
- */
- void setup() {
- // initialize serial communications (for debugging only):
- Serial.begin(9600);
- }
- void loop() {
- // read the sensor:
- int sensorReading = analogRead(A0);
- // print the sensor reading so you know its range
- Serial.println(sensorReading);
- // map the analog input range (in this case, 400 - 1000 from the photoresistor)
- // to the output pitch range (120 - 1500Hz)
- // change the minimum and maximum input numbers below
- // depending on the range your sensor's giving:
- int thisPitch = map(sensorReading, 400, 1000, 120, 1500);
- // play the pitch:
- tone(9, thisPitch, 10);
- delay(1); // delay in between reads for stability
- }
复制代码
|