# md13s.py - driver module for the Cytron MD13S motor driver.


# load CircuitPython hardware modules
import board
import pwmio
import digitalio

#--------------------------------------------------------------------------------
# Class to represent a single H-bridge driver.

class MD13S:
    def __init__(self, PWM=board.GP0, DIR=board.GP1, pwm_rate=20000):

        self.pwm_pin = pwmio.PWMOut(PWM, duty_cycle=0, frequency=pwm_rate)
        self.dir_pin = digitalio.DigitalInOut(DIR)
        self.dir_pin.direction = digitalio.Direction.OUTPUT
        return

    def write(self, rate, verbose=True):
        """Set the speed and direction of the motor drive.

        :param rate: modulation value between -1.0 and 1.0, full reverse to full forward."""

        # convert the rate into a 16-bit fixed point integer
        pwm = min(max(int(2**16 * abs(rate)), 0), 65535)

        self.pwm_pin.duty_cycle = pwm

        # this defines 'forward' as a CCW rotation as viewed from the shaft end
        # (i.e., shaft right-hand rule), if the red motor lead is attached to MA
        # and the black motor lead to MB.
        self.dir_pin.value = (rate < 0)

        if verbose:
            print("Setting motor driver:", rate)

        return
