## **制作你的特雷門琴**
> 本例向你展示如何使用tone()函數根據模擬信號的變化播放不同的音符。?
> 用一個光敏電阻將Arduino或Genuino板變成一個簡易版**特雷門琴**。
### **所需硬件**
* Arduino板Genuino板
* 8Ω揚聲器
* 光敏電阻
* 100Ω電阻
* 面包板連接線/杜邦線、
* 面包板
### **電路**

將揚聲器一端通過100Ω的電阻連接到9號引腳,另一端連接到GND。5V連接到光敏電阻一端,另一端連接到A0口,并加一個4.7KΩ下拉電阻。
### **原理圖**

### **代碼**
本例的代碼超級簡單。你只需要讀取模擬信號輸入值然后將它與一些音符對應即可。人類能夠聽見20-20,000HZ的聲音,但120-1,500HZ的聲音比較適合在這個例子中使用。
為了達到音符與模擬輸入值的對應,你需要知道模擬信號值的范圍。在這個電路中,這個值在400-1000左右。你可改變傳入map函數的參數來根據你用的傳感器進行調整。
代碼如下:
~~~
/*
制作你的特雷門琴
根據模擬輸入值的改變播放不同的音符。
電路搭建:
* 9號引腳連接8Ω揚聲器
* 光敏電阻連0-5V
* 4.7KΩ電阻連A0-GND
代碼是公開的。
*/
void setup() {
// 初始化串口連接(調試用):
Serial.begin(9600);
}
void loop() {
// 讀取傳感器值:
int sensorReading = analogRead(A0);
//打印一下傳感器的值來找到范圍:
Serial.println(sensorReading);
// 將模擬輸入值的對應到120-1500HZ的聲音
//注:可能要根據實際情況調整下列數值:
int thisPitch = map(sensorReading, 400, 1000, 120, 1500);
// 播放音符:
tone(9, thisPitch, 10);
delay(1); // delay以保證穩定
}
~~~
### **相關資料**
[Array()](http://www.arduino.cc/en/Reference/Array)?
[for()](http://www.arduino.cc/en/Reference/For)?
[tone()](http://www.arduino.cc/en/Reference/Tone)?
[map()](http://www.arduino.cc/en/Reference/Map)?
- 說明
- 系統示例文件目錄結構及說明
- 01.Basics
- AnalogReadSerial
- BareMinimum
- Blink
- DigitalReadSerial
- Fade
- ReadAnalogVoltage
- 02.Digital
- BlinkWithoutDelay
- Button
- Debounce
- DigitalInputPullup
- StateChangeDetection
- toneKeyboard
- toneMelody
- toneMultiple
- tonePitchFollower
- 03.Analog
- AnalogInOutSerial
- AnalogInput
- AnalogWriteMega
- Calibration
- Fading
- Smoothing
- 04.Communication
- ASCIITable
- Dimmer
- Graph
- Midi
- MultiSerial
- PhysicalPixel
- ReadASCIIString
- SerialCallResponse
- SerialCallResponseASCII
- SerialEvent
- SerialPassthrough
- VirtualColorMixer
- 05.Control
- Arrays
- ForLoopIteration
- IfStatementConditional
- switchCase
- switchCase2
- WhileStatementConditional
- 06.Sensors
- ADXL3xx
- Knock
- Memsic2125
- Ping
- 07.Display
- barGraph
- RowColumnScanning
- 08.Strings
- CharacterAnalysis
- StringAdditionOperator
- StringAppendOperator
- StringCaseChanges
- StringCharacters
- StringComparisonOperators
- StringConstructors
- StringIndexOf
- StringLength
- StringLengthTrim
- StringReplace
- StringStartsWithEndsWith
- StringSubstring
- StringToInt
- 09.USB
- Keyboard
- KeyboardLogout
- KeyboardMessage
- KeyboardReprogram
- KeyboardSerial
- KeyboardAndMouseControl
- Mouse
- ButtonMouseControl
- JoystickMouseControl
- 10.StarterKit_BasicKit (與特定硬件相關,暫無)
- p02_SpaceshipInterface
- p03_LoveOMeter
- p04_ColorMixingLamp
- p05_ServoMoodIndicator
- p06_LightTheremin
- p07_Keyboard
- p08_DigitalHourglass
- p09_MotorizedPinwheel
- p10_Zoetrope
- p11_CrystalBall
- p12_KnockLock
- p13_TouchSensorLamp
- p14_TweakTheArduinoLogo
- p15_HackingButtons
- 11.ArduinoISP(暫無)
- ArduinoISP