サーボモーターは色々な使い方が出来そうだが、とりあえずすぐ頭に浮かぶのは踏切遮断機だろう。というわけで、次の練習課題では光センサーと組み合わせ、列車の通過を検知して遮断機を操作する。
[ スケッチ:Sweep1]
#include <Servo.h>
const int analogPin = A0; // pin that the sensor is attached to
const int threshold = 150; // an arbitrary threshold level
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
int analogValue = analogRead(analogPin);
if (analogValue < threshold) {
for (pos = 0; pos <= 90; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position 'pos'
delay(15); // waits 15ms for the servo to reach pos
}
delay(3000);
for (pos = 90; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in 'pos'
delay(15); // waits 15ms for the servo to reach pos
}
}
}