I have a motor class but I dont' know why this motor cannot change speed

class Motor:
    def __init__(self, pos, line_status=0):
        def set_motor_gpio(_a, _b, _pwm):
            self._A = _a
            self._B = _b
            self._PWM = _pwm
            GPIO.setup(self._A, GPIO.OUT)
            GPIO.setup(self._B, GPIO.OUT)
            GPIO.setup(self._PWM, GPIO.OUT)
            self.PWM = GPIO.PWM(self._PWM, 100)

                if pos == "L":
        if line_status == 0:
            set_motor_gpio(12, 11, 35)
        elif line_status == 1:
            set_motor_gpio(11, 12, 35)

        elif pos == "R":
            if line_status == 0:
                set_motor_gpio(13, 15, 37)
            elif line_status == 1:
                set_motor_gpio(15, 13, 37)

    def run(self, direction, speed):
        Make motor run
        :param direction: Forward or Backward as String
        :param speed: running speed
        if not (direction == "F" or "B"):
            raise Exception("run method's direction must be 'F' or 'B'")
        if direction == "F":
            GPIO.output(self._A, GPIO.HIGH)
            GPIO.output(self._B, GPIO.LOW)
        elif direction == "B":
            GPIO.output(self._A, GPIO.LOW)
            GPIO.output(self._B, GPIO.HIGH)
            GPIO.output(self._PWM, GPIO.HIGH)

I tested this code. before self.PWM.ChangeDutyCycle(speed), everything works. Although I assigned Motor to instance and Motor.run("F", 0), Motor ran. I think It should have stopped. Why is self.PWM.ChangeDutyCycle not working?


I did fix it. The problem was I didn't use self.PWM.start method. self.PWM.ChangeDutyCycle must be executed after self.PWM.start() method executed once at least.

  • Please accept your own answer with a click on the tick on its left side. Only this will finish the question and it will not pop up again year for year. – Ingo Dec 11 '19 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.