p05_ServoMoodIndicator

はじめに

フォトレジスタから読み取ったRGBの値を使って、RGB LEDを点灯させます。

デジタルの9番、10番、11番に、それぞれ、緑、赤、青のLEDが、アナログの0番、1番、2番に、それぞれ、赤、緑、青のフォトレジスタが接続されている想定です。

プログラム

定義等

 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 5 - Servo Mood Indicator

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

  Parts required:
  - servo motor
  - 10 kilohm potentiometer
  - two 100 uF electrolytic capacitors

  created 13 Sep 2012
  by Scott Fitzgerald

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

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

// include the Servo library
#include <Servo.h>

Servo myServo;  // create a servo object

int const potPin = A0; // analog pin used to connect the potentiometer
int potVal;  // variable to read the value from the analog pin
int angle;   // variable to hold the angle for the servo motor
 

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

setup()

29
30
31
32
33
void setup() {
  myServo.attach(9); // attaches the servo on pin 9 to the servo object
  Serial.begin(9600); // open a serial connection to your computer
}
 

myServo.attach()で、9番ピンに接続したサーボを利用可能状態にします。

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

loop()

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
void loop() {
  potVal = analogRead(potPin); // read the value of the potentiometer
  // print out the value to the Serial Monitor
  Serial.print("potVal: ");
  Serial.print(potVal);

  // scale the numbers from the pot
  angle = map(potVal, 0, 1023, 0, 179);

  // print out the angle for the servo motor
  Serial.print(", angle: ");
  Serial.println(angle);

  // set the servo position
  myServo.write(angle);

  // wait for the servo to get there
  delay(15);
}

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

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

map()を使ってpotValの値(0から1023)を0から179に変換します。

Serial.print()で、変換後の値をシリアルコンソールに表示します。

myServo.write()を使って、サーボを回転させます。

delay()を使って、サーボが動き終わるのを待ちます。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system