p06_LightTheremin

はじめに

光テルミンです。

アナログの0番ピンに可変抵抗器、デジタルの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
/*
  Arduino Starter Kit example
  Project 6 - Light Theremin

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

  Parts required:
  - photoresistor
  - 10 kilohm resistor
  - piezo

  created 13 Sep 2012
  by Scott Fitzgerald

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

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

// variable to hold sensor value
int sensorValue;
// variable to calibrate low value
int sensorLow = 1023;
// variable to calibrate high value
int sensorHigh = 0;
// LED pin
const int ledPin = 13;
 

各種変数を定義しています。ピン番号に利用する変数はプログラム中で変更しないので、const宣言しています。

setup()

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
void setup() {
  // Make the LED pin an output and turn it on
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);

  // calibrate for the first five seconds after program runs
  while (millis() < 5000) {
    // record the maximum sensor value
    sensorValue = analogRead(A0);
    if (sensorValue > sensorHigh) {
      sensorHigh = sensorValue;
    }
    // record the minimum sensor value
    if (sensorValue < sensorLow) {
      sensorLow = sensorValue;
    }
  }
  // turn the LED off, signaling the end of the calibration period
  digitalWrite(ledPin, LOW);
}
 

pinMode()を使いledPinを出力モードに設定し、digitalWrite()でledPinにHIGHを出力し、LEDを点灯させます。

millis()はArduinoが動き始めてからの時間をミリ秒単位で返す関数です。このスケッチでは、Arduinoが動き始めてから5000ミリ秒間アナログピンの0番に接続したフォトレジスタの値を校正します。この間analogRead()で読み取った値の最大値と最小値をそれぞれ、sensorHighとsensorLowに代入します。

校正終了後、LEDを消灯します。

loop()

50
51
52
53
54
55
56
57
58
59
60
61
62
void loop() {
  //read the input from A0 and store it in a variable
  sensorValue = analogRead(A0);

  // map the sensor values to a wide range of pitches
  int pitch = map(sensorValue, sensorLow, sensorHigh, 50, 4000);

  // play the tone for 20 ms on pin 8
  tone(8, pitch, 20);

  // wait for a moment
  delay(10);
}

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

map()を使ってsensorValueの値を変換します。

変換した値をtone()を使ってスピーカに出力します。

delay()を使って、しばらく待ちます。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system