toneKeyboard

はじめに

アナログピンからの入力値に従って音を出します。

アナログの0から2番ピンに感圧抵抗、デジタルの8番ピンにスピーカが接続されている想定です。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
  Keyboard

  Plays a pitch that changes based on a changing analog input

  circuit:
  - three force-sensing resistors from +5V to analog in 0 through 5
  - three 10 kilohm resistors from analog in 0 through 5 to ground
  - 8 ohm speaker on digital pin 8

  created 21 Jan 2010
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneKeyboard
*/

#include "pitches.h"

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

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

pitches.hというファイルを#includeを使って取り込みます。これにより、pitches.hでの定義や宣言を利用できるようになります。pitches.hは、本体のファイル(toneKeyboard.ino)と同じフォルダにあります。

このプログラムで利用する大域変数を定義します。大域変数は、int型のthresholdとint型の配列のnotesです。

notes[0]、notes[1]、notes[2]には、それぞれ、NOTE_A4、NOTE_B4、NOTE_C3が代入されます。配列の添え字は0から始まります。

NOTE_A4、NOTE_B4、NOTE_C3は、pitches.hで定義されていて、それぞれ、440、494、131です

setup()

29
30
31
32
void setup() {

}
 

何もしません。何もしない場合でもsetup()を定義しておく必要があります。

loop()

33
34
35
36
37
38
39
40
41
42
43
44
void loop() {
  for (int thisSensor = 0; thisSensor < 3; thisSensor++) {
    // get a sensor reading:
    int sensorReading = analogRead(thisSensor);

    // if the sensor is pressed hard enough:
    if (sensorReading > threshold) {
      // play the note corresponding to this sensor:
      tone(8, notes[thisSensor], 20);
    }
  }
}

analogRead()を使って、thisSensorの状態を読み取り、結果をsensorReadingに代入します。thisSensorの値は、for文によって、0から2まで変化します。つまり、アナログピンの0番、1番、2番から順番に値を読み取ります。

sensorReadingがthresholdより大きいときに、tone()を使って、音を出します。tone()の第2引数は周波数です。これは、notes[thisSensor]となっています。thisSensorは、0から2まで変化する値なので、notes[0]、notes[1]、notes[2]のどれかになり、実際には、440、494、131のどれかが渡されることになります。

結果として、アナログピンに接続した感圧抵抗を押すと、押した感圧抵抗が接続されているアナログピンによって異なる音が出力されます。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system