接続 センサーはA0に接続します。 サーボモーターの白の線をPin9に接続する。 サーボモーターの黒の線をGNDに接続する。 サーボモーターの赤の線を5Vに接続する。センサーの値を表示するために、右上のシリアルモニタを動作させます。

| IrServo |
|---|
#include <Servo.h>
Servo myservo;
int pos = 0;
void setup() {
Serial.begin(9600); // パソコンとシリアル通信の準備を行う
myservo.attach( 9 ); // Port 9 にサーボモーター制御線をつなぐ
}
int rSensor; // センサーの値
int rPosition; // サーボの制御値
int rAmp=10; // 動作感度
int IrMin = 50; // センサの最低値
int IrMax = 1000; // センサの最大値
int center = 90; // サーボモーターの中心位置
// 比例制御を行う
void loop() {
rSensor = analogRead(0) ; // アナログ0番ピンから反射型光センサーの値を読み込む
rPosition = rAmp*((double)rSensor-IrMin)/(rSensor-IrMax)+90.0;
myservo.write( rPosition );
delay( 15 );
}
|