p09_MotorizedPinwheel

はじめに

スイッチのON/OFFでモーターのON/OFFを行います。

デジタルピンの2番にスイッチが、9番にモーターが接続されています。

プログラム

定義等

 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 9 - Motorized Pinwheel

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

  Parts required:
  - 10 kilohm resistor
  - pushbutton
  - motor
  - 9V battery
  - IRF520 MOSFET
  - 1N4007 diode

  created 13 Sep 2012
  by Scott Fitzgerald

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

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

// named constants for the switch and motor pins
const int switchPin = 2; // the number of the switch pin
const int motorPin =  9; // the number of the motor pin

int switchState = 0;  // variable for reading the switch's status
 

変数を定義しています。

setup()

29
30
31
32
33
34
35
void setup() {
  // initialize the motor pin as an output:
  pinMode(motorPin, OUTPUT);
  // initialize the switch pin as an input:
  pinMode(switchPin, INPUT);
}
 

pinMode()を使い、motorPinを出力モードに、switchPinを入力モードにします。

loop()

36
37
38
39
40
41
42
43
44
45
46
47
48
void loop() {
  // read the state of the switch value:
  switchState = digitalRead(switchPin);

  // check if the switch is pressed.
  if (switchState == HIGH) {
    // turn motor on:
    digitalWrite(motorPin, HIGH);
  } else {
    // turn motor off:
    digitalWrite(motorPin, LOW);
  }
}

digitalRead()を使ってswitchPinの値を読み取りswitchStateに代入します。

switchStateがHIGHならばdigitalWrite()を使って、motorPinをHIGHにしモーターを回します。switchStateがHIGHでなければ、motorPinをLOWにしモーターを止めます。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system