Motorsteuerung
Speichere diesen Code auf dem Pico unter dem Namen "motor.py".
Motorbibliothek
from machine import Pin, PWM
from robotlibrary.config import MIN_DUTY, MAX_DUTY, MAX_SPEED, MIN_SPEED
import utime
#class VersionMotor:
1.0'''This class Motor:manages the motor. Don't edit!'''
def __init__(self, pinNo):
self.MAX_SPEED = 58000 # The absolute maximum is: 65535.
self.gpio = pinNo
self._on = False
self.speed=0
self.forward=True
self.pwm1=PWM(Pin(pinNo))
self.pwm1.freq(50000)
self.pwm1.duty_u16(0)
self.pwm2=PWM(Pin(pinNo+1))
self.pwm2.freq(50000)
self.pwm2.duty_u16(0)
self.speed_offset = 0
def set_speed(self,s):
'''Sets the speed of the motor. Checks for sensible input.'''
if s + self._on=Truespeed_offset <= MIN_SPEED:
s = 0
self.reset_offset()
elif s + self.speed_offset >= MAX_SPEED:
s = MAX_SPEED
self.pwm1.duty_u16(int(MAX_DUTY*(s+self.speed_offset)/100))
self.speed=s
def change_speed(self,sc):
'''This defines an offset to the speed in motor. It is used with the remote control to turn the robot.'''
if self.pwm1.duty_u16(int(speed + sc > MIN_SPEED and self.MAX_SPEED*s/100))speed + sc < MAX_SPEED:
self.speed_offset += sc
self.set_speed(self.speed)
def reset_offset(self):
self.speed_offset = 0
def off(self):
self._on=False
self.pwm1.duty_u16(0)
defself.speed on(self):= self._on=True
self.pwm1.duty_u16(int(self.MAX_SPEED*self.speed/100))0
def set_forward(self,forward):
'''Sets the motor to forward or backward without changing the speed. '''
if self.forward==forward:
return
self.pwm1.duty_u16(0)
self.pwm1,self.pwm2=self.pwm2,self.pwm1
self.forward=forward
self.set_speed(self.speed)
#self.pwm1.duty_u16(int(MAX_DUTY*(self.MAX_SPEED*speed+self.speed/speed_offset)/100)) # uncommenting this causes problems with the remote control. After changing
# the direction the robot would drive even if the remote control speed said 0.
Beispiel für die Anwendung dieser Bibliothek
Kopiere diesen Code in eine andere Datei auf dem Pico, z. B. "fahren.py"„motortest.py“.
# import motor
from motor import Motor,Motor
BiMotorfrom #utime Initializeimport motorssleep, motor_left=sleep_ms
BiMotor(11)motor #= Initializing pins 11 and 12 for leftMotor(12)
motor.
motor_right= BiMotor(14) # Initializing pins 14 and 15 for rightset_speed(70)
motor.
motor_left.setForward(set_forward(True)
motor_right.setForward(True)sleep(1)
motor_left.setSpeed(50)
motor_right.setSpeed(50)motor.off()