
#Simple servo motor arduino code code
The following is an example code that rotates a Servo motor from 0 to 180 degrees and from 180 degrees back to 0 degree. The read() method returns the current value of angle of the servo which is the last value passed to the write() method.Įxample Program Code for Servo Control using Motor Shield and Arduino

On standard servo, 1000 microseconds, 1500 microseconds and 2000 microseconds corresponds to fully counter clockwise, midway and fully clockwise rotation angle. In the above example, 1000 microseconds is specified, so the motor shaft will rotate to the position corresponding to 1000 microseconds. The writeMicroseconds() methods is used to rotate the servo motor shaft to specified orientation by providing microseconds value. In the above example, angle in degree of 80 has been specified so the servo will rotate to that orientation. The write() method is used to control the positioning of the servo shaft by providing angle value to the method. It returns TRUE or FALSE depending upon whether the variable servo object is attached or not attached to any pins. The attached() method is used to check whether the servo object is attached to any pins. Once disconnected the pwm pin can be used for other works. The detach() method is used to disconnect the servo motor object from the pwm pin to which it is connected. If you don't specify the min and max values then the default values 5 microseconds are used. The other two are optional and are the minimum and maximum pulse width in microseconds corresponding to 0 degree angle and 180 degree angle. The first parameter is the pin number which in above example is 9.

Where attach() is a method which can accepts 3 parameters. The attach() method is mandatory and should be declared in the setup() function in the program code. Where myservo is instantiated object of class Servoĭepending upon what you want to do with the servo motor, you can use different available methods. Create a Servo object using the Servo class So unlike for controlling stepper motor or DC motor we do not need the Adafruit motor library.Ģ. Programming Arduino for Servo motor control using Motor Shieldįor programming servo motor we can use the Servo library that comes with Arduino IDE installation.
