Servo

A servo mechanism is something like a motor, but instead of turning around it can turn only 180 degrees. Imagine this mechanism as a system that turns from 0 to 180 degrees and then back to 0. It has also the capability to stay at a specific angle, where a simple DC motor cannot stop, it keeps spinning until we cut the power. A simple servo like the one that we will use in our project is shown in the following screenshot:

It has three wires, the first one is for the 5V input power, the second one is for the ground, and the last one is for the signal, which determines the position of the servo. The following code turns the servo from 0 to 180 degrees and back to 0. To use the following code with the Arduino microcontroller, we need a library called Servo.h.

Firstly, we have need to include the library in our sketch:

#include <Servo.h>

Then, define a Servo variable:

Servo myServo;

And then, in the setup() function, initiate the servo and define the pin to which our servo is attached. We can do this with the following code:

myServo.attach(4); // We assume that we attached the servo in the 4 digital ping

Then, in the loop() function, we have to turn the servo from 0 to 180 and back to 0. To do this, we will use a for loop and write every position from 0 to 180:

for(int i=0; i<180; i++) { 
   myServo.write(i); 
} 
for(int i=180; i>0; i--) { 
   myServo.write(i); 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.229.253