在本Arduino伺服電機教程中,您將學習如何使用Arduino UNO板和電位器控制伺服電機。
一旦你啟動并運行了這個示例項目,你就掌握了從Arduino控制伺服電機的技能。這可以成為更先進的機器人項目的基礎。
您需要的組件:
Arduino的板
5V伺服電機(如SG90)
電位器(1k及以上的任意值)
面包板和跳線
電路設置:
將舵機的電源線(通常為紅色)連接到 Arduino 上的 5V 輸出。
將舵機的接地電纜(通常為棕色或黑色)連接到 Arduino 上的一個 GND 引腳。
將舵機的信號線(通常為橙色或黃色)連接到 Arduino 上的數(shù)字引腳 9。
將電位器插入試驗板,并將其一個外部引腳連接到 5V,另一個外部引腳連接到 Arduino 上的 GND。
將電位計的中間引腳連接到Arduino上的模擬引腳A0。
示例代碼 1:自動伺服運動
首先,要測試伺服電機是否工作,請上傳以下測試代碼。上傳后,伺服電機應開始在 0 到 180 度之間來回移動。確保您的舵機連接到引腳
9,如電路圖所示。
#include < Servo.h > // Include the Servo library
Servo myservo; // Create a servo object to control the servo motor
void setup() {
myservo.attach(9); // Attaches the servo on pin 9 to the servo object
}
void loop() {
// Goes from 0 degrees to 180 degrees in steps of 1 degree
for (int pos = 0; pos <= 180; pos += 1) {
myservo.write(pos); // Tell servo to go to position in variable 'pos'
delay(15); // Waits for the servo to reach the position
}
// Goes from 180 degrees to 0 degrees
for (int pos = 180; pos >= 0; pos -= 1) {
myservo.write(pos); // Tell servo to go to position in variable 'pos'
delay(15); // Waits for the servo to reach the position
}
}
上傳代碼:
通過 USB 數(shù)據(jù)線將 Arduino UNO 連接到計算機。
在計算機上打開Arduino IDE。
將提供的代碼復制到新草圖中。
在“工具”菜單下選擇正確的主板和端口。
單擊“上傳”按鈕將代碼傳輸?shù)紸rduino。
示例代碼 2:使用電位計控制伺服
此示例草圖使用電位計來控制伺服電機的位置。當您轉(zhuǎn)動電位器時,伺服電機應相應地移動到電位器電阻所指示的位置。
此代碼基于基本的Arduino電位器示例。
#include < Servo.h >
Servo myservo; // Servo object to control the motor
int potpin = A0; // Where the potentiometer is connected
int val; // Variable to read the potentiometer value
void setup() {
// Tell the servo object which pin to use
myservo.attach(9);
}
void loop() {
// Read the value of the potentiometer (value between 0 and 1023)
val = analogRead(potpin);
// Scale it to use it with the servo (value between 0 and 180)
val = map(val, 0, 1023, 0, 180);
// Set the servo position according to the scaled value
myservo.write(val);
// Wait for the servo to reach the position
delay(15);
}
上傳代碼后,轉(zhuǎn)動電位器將改變電阻和Arduino讀取的模擬值,從而控制伺服電機的位置。
現(xiàn)在,您可以對位置進行試驗,并了解伺服電機如何響應電位計的調(diào)整。
Arduino伺服電機故障排除
如果伺服電機沒有響應:
根據(jù)原理圖檢查所有連接。
確保在IDE中正確選擇了Arduino板。
確保試驗板上沒有短路。
確保您的舵機在 5V 下工作
審核編輯:陳陳
-
電位器
+關(guān)注
關(guān)注
14文章
1013瀏覽量
66975 -
伺服電機
+關(guān)注
關(guān)注
85文章
2057瀏覽量
58190 -
Arduino
+關(guān)注
關(guān)注
188文章
6477瀏覽量
187816
發(fā)布評論請先 登錄
相關(guān)推薦
評論