风筝
发表于: 2016-7-21 23:37:01 | 显示全部楼层

音调键盘(Simple keyboard using the tone() function)

本示例展示了如何使用tone()命令根据按下的传感器来产生不同的音调。


所需硬件

-    Arduino或者Genuino开发板

-    8欧的扬声器

-    3个压力感应电阻

-    3个10k电阻

-    100欧电阻

-    导线

-    面包板


电路连接方式

将扬声器的一端通过一个100欧的电阻连接到数字8脚,扬声器的另一端连接到地。

将3个压力感应电阻FSR并联,连接到到5V电源。每个传感器连接到模拟输入0-2脚,在每个输入回路使用一个10K(作为参考)的电阻连接到地。

arduino_fsrs_speaker_bb.png


原理图

arduino_fsrs_speaker_schem.png

代码

下面的程序读取三个模拟传感器。每个传感器对应一个音符数组里的音符值。如果任何一个传感器的值超过给定的阈值,那么就会播放相应的音符。

以下是主要的程序:

  1. /*
  2.   keyboard

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

  4. circuit:
  5. * 3 force-sensing resistors from +5V to analog in 0 through 5
  6. * 3 10K resistors from analog in 0 through 5 to ground
  7. * 8-ohm speaker on digital pin 8

  8. created 21 Jan 2010
  9. modified 9 Apr 2012
  10. by Tom Igoe

  11. This example code is in the public domain.

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

  13. */

  14. #include "pitches.h"

  15. const int threshold = 10;    // minimum reading of the sensors that generates a note

  16. // notes to play, corresponding to the 3 sensors:
  17. int notes[] = {
  18.   NOTE_A4, NOTE_B4, NOTE_C3
  19. };

  20. void setup() {

  21. }

  22. void loop() {
  23.   for (int thisSensor = 0; thisSensor < 3; thisSensor++) {
  24.     // get a sensor reading:
  25.     int sensorReading = analogRead(thisSensor);

  26.     // if the sensor is pressed hard enough:
  27.     if (sensorReading > threshold) {
  28.       // play the note corresponding to this sensor:
  29.       tone(8, notes[thisSensor], 20);
  30.     }
  31.   }
  32. }
复制代码


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

本版积分规则

主题 700 | 回复: 1482



手机版|

GMT+8, 2024-4-30 22:37 , Processed in 0.058568 second(s), 8 queries , Gzip On, MemCache On. Powered by Discuz! X3.5

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

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