一、介紹
無刷電機(jī)是通過電調(diào)進(jìn)行控制的,通過對(duì)PWM的調(diào)整控制電機(jī)轉(zhuǎn)速
二、代碼
# 控制電機(jī)函數(shù)
from pyb import Timer,Pin,ADC
import time
class Motor():
# 電機(jī)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])
# 電機(jī)初始化 設(shè)置最高油門和最低油門
def MotoSet(self,moto):
moto.pulse_width_percent(10)
time.sleep(2)
moto.pulse_width_percent(5)
# pwm 更新函數(shù) 1
# 可以用于調(diào)試單個(gè)電機(jī)
def MotoPwmUpdate(self,n,pwm):
if pwm < 0 or pwm > 100:
return None
self.motors[n].pulse_width_percent(5 + pwm*5/100)
# pwm 更新函數(shù) 2
# 用于實(shí)際飛行
def MotosPwmUpdate(self,pwms):
for moto,pwm in zip(self.motors,pwms):
moto.pulse_width_percent(5 + pwm*5/100)
# 電機(jī)停止轉(zhuǎn)動(dòng)
# 用于緊急制動(dòng)和測(cè)試
def MotoStop(self):
for moto in self.motors:
moto.pulse_width_percent(5)