p07_Keyboard

はじめに

キーボード(タイプする方ではなく、音を出すほう)です。

プログラム

定義等

 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
/*
  Arduino Starter Kit example
  Project 7 - Keyboard

  This sketch is written to accompany Project 7 in the Arduino Starter Kit

  Parts required:
  - two 10 kilohm resistors
  - 1 megohm resistor
  - 220 ohm resistor
  - four pushbuttons
  - piezo

  created 13 Sep 2012
  by Scott Fitzgerald

  https://store.arduino.cc/genuino-starter-kit

  This example code is part of the public domain.
*/

// create an array of notes
// the numbers below correspond to the frequencies of middle C, D, E, and F
int notes[] = {262, 294, 330, 349};
 

音階を表す変数notesを定義しています。262、294、330、349は、それぞれ、ド、レ、ミ、ファの周波数です。

setup()

26
27
28
29
30
void setup() {
  //start serial communication
  Serial.begin(9600);
}
 

Serial.begin()でシリアル通信の初期化を行います。通信速度は9600bpsです。

loop()

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
void loop() {
  // create a local variable to hold the input on pin A0
  int keyVal = analogRead(A0);
  // send the value from A0 to the Serial Monitor
  Serial.println(keyVal);

  // play the note corresponding to each value on A0
  if (keyVal == 1023) {
    // play the first frequency in the array on pin 8
    tone(8, notes[0]);
  } else if (keyVal >= 990 && keyVal <= 1010) {
    // play the second frequency in the array on pin 8
    tone(8, notes[1]);
  } else if (keyVal >= 505 && keyVal <= 515) {
    // play the third frequency in the array on pin 8
    tone(8, notes[2]);
  } else if (keyVal >= 5 && keyVal <= 10) {
    // play the fourth frequency in the array on pin 8
    tone(8, notes[3]);
  } else {
    // if the value is out of range, play no tone
    noTone(8);
  }
}

analogRead()を使って可変抵抗器の電圧を読み取り、keyValに設定します。

Serial.print()で、読み取った値をシリアルコンソールに表示します。

keyValの値に応じて、tone()を使って特定の周波数の音を出力します。keyValが4以下の場合はnoTone()で音の出力を停止します。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system