Lesson 9 Servo

Share for us
Share on facebook
Share on twitter
Share on pinterest
Share on whatsapp

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 one is VCC, and the orange one is signal line, as shown below.

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, the position detector returns a location signal to judge whether the 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_LcdStartKit /09_servo/servo.py)

Step 3: Modify the file permissions

chmod  +x  servo.py

Step 4: Run the program

python  servo.py

Press Enter, you can see the servo motor rotate 180 degrees. And then rotate in the opposite direction.

 Code

#Servo Control import time def set(property, value): try: f = open(“/sys/class/rpi-pwm/pwm0/” + property, ‘w’) f.write(value) f.close() except: print(“Error writing to: ” + property + ” value: ” + value) def setServo(angle): set(“servo”, str(angle)) set(“delayed”, “0”) set(“mode”, “servo”) set(“servo_max”, “180”) set(“active”, “1”) delay_period = 0.01 while True: for angle in range(0, 180): setServo(angle) time.sleep(delay_period) for angle in range(0, 180): setServo(180 – angle) time.sleep(delay_period)