First, we have the guide on how to buy a Servo motor for basic DIY electronics. Second, we already pointed on how to build a DIY robotic arm. Here is Basic Servo Motor Arduino Code to Test Newly Purchased Servo Motor or Perform Some Basic Action. We Can Fine Tune Degrees of Sweep. For this tutorial, we are using TowerPro SG-5010 Servo Motor, this should work for the cheaper TowerPro SG-90 Servo Motor as well.
Servo Motor Arduino Code : Basic
Unlike 3V DC Motor Code, we need not much extra electronics part to drive a servo motor. The big difference between a 3V DC Motor and a Servo Motor is the number of inputs. We will connect the black wire from the servo to the GND pin on the Arduino, the red wire from the servo to the +5V pin on the Arduino and the yellow (or white) wire from the servo to a digital pin on the Arduino – let us use number 4 digital pin. Setup is very easy :
Servo Motor Arduino Code
We can include the Arduino servo library. However, it is better to start from the basic, without including the library, here is the code :
---
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | int servopin = 4; int pulse = 1500; void setup () { pinMode(servopin, OUTPUT); Serial.begin(9600); } void loop() { digitalWrite(servopin, HIGH); delayMicroseconds(pulse); digitalWrite(servopin, LOW); delay(20); } |
We kept the code as Github Gist for you.
That int pulse = 1500
value is in microseconds. 5V for 1500 microseconds (1.5 milliseconds) corresponds to 90 degrees. 500 microseconds corresponds to 0 degrees and 2500 microseconds corresponds to 180 degrees. delay(20)
means send pulse every 20ms.
If we want repeat 180 degree sweep including the Arduino Library, we can use the modified official code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <Servo.h> Servo thecustomizewindows; // create servo object to control a servo int pos = 0; // variable to store the servo position void setup() { thecustomizewindows.attach(4); // attaches the servo on pin 4 to the servo object } void loop() { for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees // in steps of 1 degree thecustomizewindows.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees thecustomizewindows.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } } |
That is it.
Tagged With arduino servo motor code , servo motor arduino code , basic arduino coding , servomotor , arduino servo motor basiss if , basic arduino code dc motor to servp , sg90 arduino connection , basic arduino motor code , basic servo code , cod 6 servo motor