รู้จัก Servo Motor Servo เป็นคำศัพท์ที่ใช้กันทั่วไปในระบบควบคุมอัตโนมัติ มาจากภาษาละตินคำว่า Sevus หมายถึง “ทาส” (Slave) ในเชิงความหมายของ Servo Motor ก็คือ Motor ที่เราสามารถสั่งงานหรือตั้งค่า แล้วตัว Motor จะหมุนไปยังตำแหน่งองศาที่เราสั่งได้เองอย่างถูกต้อง โดยใช้การควบคุมแบบป้อนกลับ (Feedback Control) ส่วนประกอบภายนอก Servo Motor
*** การใช้งานแบบไม่ต้องการเชื่อมต่อสาย USB กับ คอมพิวเตอร์ ให้ใช้ Adapter DC 9V 1A Power Supply เป็นแหล่งจ่ายไฟ เสียบเข้ากับ DC Power Jack ของ บอร์ด Arduino ***
/*
Servo Motor Control with Potentiometer Arduino.
For more details visit:
https://miniarduino.blogspot.com/2019/03/arduino-servo-motor-potentiometer.html
*/
// include the library code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
// Set the LCD address to 0x27 or 0x3F for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo myservo; // create servo object to control a servo
int potpin = A0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
void setup() {
lcd.begin(); // initialize the LCD
lcd.backlight(); // Turn on the blacklight and print a message.
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)
lcd.setCursor(0, 0); // set the cursor to column 0, line 0
lcd.print("ADC = " + String(val)); // print (value // between 0 and 1023) to the LCD.
val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo value
lcd.setCursor(0, 1); // set the cursor to column 0, line 1
lcd.print("Servo = " + String(val)); // print (value // between 0 and 180) to the LCD.
// 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
}
4.1 อธิบายโค้ด
val = analogRead(potpin);
อ่านค่า Analog จาก Potentiometer ที่ต่ออยู่ที่ขา A0 เก็บไว้ในตัวแปร val
lcd.print("ADC = " + String(val));
แสดงค่า 0 – 1023 ที่จอ LCD
val = map(val, 0, 1023, 0, 180);
เนื่องจาก ADC ภายใน Arduino เป็น ADC ขนาด 10-bit จึงอ่านค่า Analog ได้ตั้งแต่ 0 – 1023 แต่ RC Servo Motor สามารถหมุนได้เพียงแค่ 0 - 180 องศา จึงต้องใช้ Function map เพื่อทำการสเกลค่าลงจาก 0 - 1023 เป็น 0 - 180 แล้วนำไปเก็บไว้ในตัวแปร val
lcd.print("Servo = " + String(val));
แสดงค่า 0 – 180 ที่จอ LCD
myservo.write(val);
เมื่อสเกลค่า จาก 0-1023 ลงเหลือ 0-180 แล้วก็นำมาสั่งให้ Servo Motor หมุนไปยังตำแหน่งในค่าตัวแปร val delay(15);
หน่วงเวลา 15 มิลลิวินาที.
ผลของการทำงานทำให้สามารถปรับตำแหน่งองศาของ Servo Motor ได้โดยการหมุนปรับค่า Potentiometer และแสดงค่าที่จอ LCD