一、介绍
无刷电机是通过电调进行控制的,通过对PWM的调整控制电机转速
二、代码
# 控制电机函数
from pyb import Timer,Pin,ADC
import time
class Motor():
# 电机pwm初始化
def __init__(self,isInit=False):
timerMotor_1 = Timer(3, freq=50)
timerMotor_2 = Timer(4, freq=50)
self.motor1 = timerMotor_1.channel(1, Timer.PWM, pin=Pin('B4'))
self.motor2 = timerMotor_1.channel(2, Timer.PWM, pin=Pin('B5'))
self.motor3 = timerMotor_2.channel(3, Timer.PWM, pin=Pin('B8'))
self.motor4 = timerMotor_2.channel(4, Timer.PWM, pin=Pin('B9'))
self.motors = [self.motor1,self.motor2,self.motor3,self.motor4]
# self.x = ADC(Pin('X2'))
# self.btn_stop = Pin('X4',Pin.IN)
if not isInit:
for moto in self.motors:
self.MotoSet(moto)
time.sleep(1)
self.MotosPwmUpdate([0,0,0,0])
# 电机初始化 设置最高油门和最低油门
def MotoSet(self,moto):
moto.pulse_width_percent(10)
time.sleep(2)
moto.pulse_width_percent(5)
# pwm 更新函数 1
# 可以用于调试单个电机
def MotoPwmUpdate(self,n,pwm):
if pwm < 0 or pwm > 100:
return None
self.motors[n].pulse_width_percent(5 + pwm*5/100)
# pwm 更新函数 2
# 用于实际飞行
def MotosPwmUpdate(self,pwms):
for moto,pwm in zip(self.motors,pwms):
moto.pulse_width_percent(5 + pwm*5/100)
# 电机停止转动
# 用于紧急制动和测试
def MotoStop(self):
for moto in self.motors:
moto.pulse_width_percent(5)