树莓派控制舵机和步进电机

树莓派GPIO引脚输出PWM

import RPi.GPIO as GPIO
import time

Pwm=GPIO.PWM(pin,frequence) #创建PWM实例

Pwm.start(dc) #启动PWM dc值 占空比(0.0

Pwm.ChangeFrequency(freq) #改变PWM频率

Pwm.ChangeDutyCycle(dc) # 改变PWM的占空比0.0<=dc <=100.

Pwm.stop() #停止PWM

控制舵机实例

舵机电源接入树莓派5v供电,控制端接GPIO.1引脚

import RPi.GPIO as GPIO
import time

pin = 12 # GPIO端口号,根据实际修改
frequence = 50  # Hz (软件PWM方式,频率不能设置过高)
a = 10
b = 2

def setDirection(direction):
    duty = a / 180 * direction + b
    pwm.ChangeDutyCycle(duty)
    time.sleep(1) 

GPIO.setmode(GPIO.BOARD)
GPIO.setup(P_SERVO, GPIO.OUT)
pwm = GPIO.PWM(pin,frequence)
pwm.start(50)

setDirection(10)
setDirection(20)
setDirection(10)
setDirection(30)
setDirection(10)
GPIO.cleanup() 

控制步进电机实例

共阴接DIR和PUL,DIR+和PUL+分别接引脚19和26

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(19, GPIO.OUT)
GPIO.setup(26, GPIO.OUT)
p1 = GPIO.PWM(26, 1000) 
p2 = GPIO.PWM(19, 1000)
while True:
    p1.start(50) 
    p2.start(50) 
    time.sleep(10)

你可能感兴趣的:(树莓派,gpio,Raspberry,Pi,树莓派,步进电机,舵机)