伺服馬達 SG90

[材料]

Arduino主板 x 1

伺服馬達 SG90

[伺服馬達SG90腳位]

棕色線  --> arduino GND

紅色線  --> arduino 5V

黃色線 --> arduino pin9

#include <Servo.h>

Servo myServo;


void setup() {

myServo.attach(9); // 伺服馬達物件連接到pin9 

}


void loop() {

myServo.write(0);//面對伺服器從0度以逆時針轉動

delay(1000);

myServo.write(90);

delay(1000);

myServo.write(180);

delay(1000);

}

步驟二:加入可變電阻

利用改變電阻來改變馬達選轉角度


[可變電阻的接腳]

左和右 --> 分別接到arduino的VIN和GND

中 --> arduino pinA0

#include <Servo.h>

Servo myServo;


int potPin = A0;

int potValue, motorValue;


void setup() {

  Serial.begin(9600);

  myServo.attach(9); // 伺服馬達物件連接到pin9 

}


void loop() {

  potValue = analogRead(potPin);      //讀取可變電阻的數值,數值介於0~1023

  Serial.println(potValue);   //顯示可變電阻的數值

  

  motorValue = map(potValue, 0, 1023, 0, 180); //把0~1023的數值,轉換為0~180

  myServo.write(motorValue);//面對伺服器從0度以逆時針轉動

  delay(1000);

}