您现在的位置是: 网站首页 > 程序设计  > 树莓派 

树莓派驱动舵机转动

2021年5月15日 01:07 2981人围观

简介树莓派驱动舵机B站链接 https://www.bilibili.com/video/BV1Ap4y1t7NC/

一、SG90舵机-万能的舵机

二、接线

舵机有三条线,棕红黄。棕色线接地,红色接5V正电压,黄色接信号线。没有信号校准步骤。意思是接上就用!

舵机控制信号是频率50HZ,占空比为2.5%-12.5%的PWM信号

三、占空比与角度的关系

占空比与角度成线性关系

脉冲/ms   占空比 角度 
0.5     2.5%    0 
1.0     5%      45 
1.5     7.5%    90 
2.0     10%     135 
2.5     12.5%   180 

注意,0°不是说不转,0°也需要转动,可以得到alpha= frequency / 18 + 2.5

img

四、驱动代码

import time 
import random 
import RPi.GPIO as GPIO 

class MyGPIO(): 
    init_count = 0 
    mode = GPIO.BCM 

    def __init__(self, idx, init_with_high): 
        if MyGPIO.init_count == 0: 
            GPIO.setmode(MyGPIO.mode) 
        MyGPIO.init_count += 1 
        self.idx = idx 
        initial = GPIO.HIGH if init_with_high else GPIO.LOW 
        GPIO.setup(self.idx, GPIO.OUT, initial=initial) 

    def __del__(self): 
        MyGPIO.init_count -= 1 
        if MyGPIO.init_count == 0: 
            GPIO.cleanup() 

    def high(self): 
        GPIO.output(self.idx, GPIO.HIGH) 

    def low(self): 
        GPIO.output(self.idx, GPIO.LOW) 


class MyPWM(MyGPIO): 
    def __init__(self, idx, frequency): 
        super(MyPWM, self).__init__(idx, init_with_high=False) 
        self.pwm = GPIO.PWM(idx, frequency) 
        self.pwm.start(0) 

    def chanage_duty_cycle(self, cycle): 
        self.pwm.ChangeDutyCycle(cycle) 

class Steer(object): 
    frequency = 50 # 50HZ 

    def angle2frequency(self, alpha): 
        return int(alpha / 18. + 2.5) 

    def __init__(self, idx): 
        self.obj = MyPWM(idx, Steer.frequency) 
        times = 10 
        while times > 0: 
            self.turn_angle(random.randint(0, 180)) 
            time.sleep(0.3) 
            times -= 1 
        self.turn_angle(90) 
        time.sleep(1) 

    def turn_angle(self, alpha): 
        print("turn to %d angle" % alpha) 
        self.obj.chanage_duty_cycle(self.angle2frequency(alpha)) 

def main(): 
    idx = 5 
    steer = Steer(idx) 
    while True: 
        alpha = random.randint(0, 180) 
        steer.turn_angle(alpha) 
        time.sleep(1) 

if __name__ == "__main__": 
     main()