"""Module 14: ramp Motor 2 up/down in CCW, then CW, with a stopped pause."""

import time
import board
import pwmio
from adafruit_motor import motor
import busio
import adafruit_ssd1306


def show_motor_status(direction, percent, status):
    # Percentage is the requested drive level, not a measured motor RPM.
    duty = int(percent * 65535 / 100)
    oled.fill(0)
    oled.text('(14) DC Motor 2', 0, 0, 1)
    oled.text('Direction: ' + direction, 0, 14, 1)
    oled.text('PWM cmd: {}'.format(duty), 0, 26, 1)
    oled.text('Speed cmd: {}%'.format(percent), 0, 38, 1)
    oled.text(status, 0, 50, 1)
    oled.show()
    print('{} | PWM: {} | Speed: {}% | {}'.format(direction, duty, percent, status))


RAMP_STEP_PERCENT = 5
RAMP_DELAY = 0.25
DIRECTION_PAUSE = 1.5

i2c = busio.I2C(board.GP5, board.GP4, frequency=400000)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
motor_pwms = (
    pwmio.PWMOut(board.GP12, frequency=10000),
    pwmio.PWMOut(board.GP13, frequency=10000),
)
motor_2 = motor.DCMotor(motor_pwms[0], motor_pwms[1])
motor_2.throttle = 0


def set_speed(direction, sign, percent, status):
    throttle = sign * percent / 100
    motor_2.throttle = throttle
    show_motor_status(direction, percent, status)


def run_direction(direction, sign):
    # Positive throttle follows the existing EDU PICO CCW connection.
    for percent in range(RAMP_STEP_PERCENT, 101, RAMP_STEP_PERCENT):
        set_speed(direction, sign, percent, 'Increasing')
        time.sleep(RAMP_DELAY)
    for percent in range(100 - RAMP_STEP_PERCENT, 0, -RAMP_STEP_PERCENT):
        set_speed(direction, sign, percent, 'Decreasing')
        time.sleep(RAMP_DELAY)
    # Zero throttle brakes Motor 2 before applying the opposite direction.
    set_speed(direction, sign, 0, 'Stopped {:.1f} s'.format(DIRECTION_PAUSE))
    time.sleep(DIRECTION_PAUSE)

try:
    while True:
        run_direction('CCW', 1)
        run_direction('CW', -1)
finally:
    motor_2.throttle = 0
    for pwm in motor_pwms:
        pwm.deinit()
    i2c.deinit()
