Arduino範例程式: Knob
程式目的:輸入一電壓以控制Servomotor的轉向角度(0~180),將此類比電壓轉換成數位訊號(ADC),透過myservo函式輸出可控制Servomotor的訊號。
#include #include <Servo.h> Servo myservo; // create servo object to control a servo int potpin = 0; // analog pin used to connect the potentiometer int val; // variable to read the value from the analog pin void setup() { myservo.attach(9); // attaches the servo on pin 9 to the servo object } void loop() { val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023) val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180) myservo.write(val); // sets the servo position according to the scaled value delay(15); // waits for the servo to get there }
從波形圖來看,控制頻率為50Hz,轉向180度的正週期為2.4ms,轉向為0度的正週期為0.55ms。
但SG90的正週期介於0.5ms~2.0ms之間,因此無法正確轉向。
180度 / 0度
另外一種方式改採用writeMicroseconds()這個函式控制。
void loop() { val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023) val = map(val, 0, 1023, 500, 2000); // scale it to use it with the servo (value between 0 and 180) myservo.writeMicroseconds(val); // sets the servo position according to the scaled value delay(15); // waits for the servo to get there }
不過myservo.writeMicroseconds(val)需介於544~2400之間,因此還是無法符合規格.
程式說明:
[設定]
1.設定類比電壓輸入為PIN A0
2.設定Servomotor控制訊號為PIN 9
[主程序]
1.讀取邏輯電壓並轉換為數位訊號 (sensorValue = analogRead(analogInPin);)
2.將數位訊號轉換為PWM訊號可輸出區間 (outputValue = map(sensorValue, 0, 1023, 0, 180);)
3.輸出Servomotor控制訊號
4.等待轉向,延遲15ms.
使用函式:
讀取類比電壓並轉為數位訊號: 透過解析度10bit ADC將類比電壓轉換為數位訊號(如電壓0~5V->數位訊號0~1023階)
數植轉換:將0~1023轉換為0~180, 也可轉換為255~0
map(sensorValue, 0, 1023, 0, 180)
Servomotor控制:輸出0~180度的控制訊號
myservo.write(val) // val=0~180
輸出正週期寬度控制: 以us為單位, 設定正週期寬度,以微調Servomotor控制.
延遲函式:以ms為單位