Lesson 10 Servo

Share for us

Introduction

Servo is a type of geared motor that can only rotate 180 degrees. It is controlled by sending electrical pulses from your microcontroller. These pulses tell the servo what position it should move to.

A servo has three wires, the brown wire is GND, the red VCC, and the orange signal:

Components

– 1*Raspberry Pi

– 1*Breadboard

– 1*Network cable (or USB wireless network adapter)

– 1*Servo

– Several jumper wires

Experimental Principle

Servo consists of shell, circuit board, non-core motor, gear and location detection. Its working principle is as follow: Raspberry Pi controller sends PWM signal to servo motor, and then this signal is processed by IC on circuit board to calculate rotation direction to drive motor, and then this driving power is transferred to swing arm by reduction gear. At the same time, position detector returns location signal to judge whether set location is reached or not.

Experimental Procedures

Step 1: Connect the circuit

              Servo                                Raspberry Pi

                Orange line————————————— GPIO1

                  Red line —————————————-  +5V

                 Brown line—————————————-  GND

Step 2: Edit and save the code (see path/Rpi_ultraKit /10_servo/servo.py)

Step 3: Modify the file permissions

chmod  +x  servo.py 

Step 4: Run the program

python  servo.py 

Now you can see the servo motor rotate 180 degrees. And then rotate in opposite direction.

Code

#include <wiringPi.h>
#include <stdio.h>
#include <unistd.h>

#define   SIG   0

void servoInit(void)
{
 pinMode(SIG, OUTPUT);
 digitalWrite(SIG, 0);
}

void servoCtrl(int dutyCycle)
{
 digitalWrite(SIG, 1);
 delayMicroseconds(dutyCycle);
 digitalWrite(SIG, 0);
 delayMicroseconds(20000 - dutyCycle);
}

int main(void)
{
 int i;

 if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
  printf("setup wiringPi failed !");
  return 1;
 }
 
 servoInit();

 while(1){
/*  for(i=500;i<=2500;i+=5){
   servoCtrl(i);
   delay(150);
  }

  delay(1000);
*/ 
 /* for(i=2500;i>=500;i--){
   servoCtrl(i);
   delay(100);
  }
  delay(1000);*/
 
/*  servoCtrl(500);
  sleep(1);
  servoCtrl(1000);
  sleep(1);
*/  servoCtrl(1500);
  sleep(1);
  servoCtrl(2000);
  sleep(1);
  servoCtrl(2500);
  sleep(1);
 }

 return 0;
}