enum MabniMotor { //% block="left motor" Left = 0, //% block="right motor" Right = 1 } /** Motor-driver signals. A motor needs its own power and driver, never a bare GPIO pin. */ //% color="#098C92" icon="\uf013" weight=89 block="Motors & Robots" //% groups='["Drive", "Wiring"]' namespace mabniMotors { let directionA: DigitalPin[] = [DigitalPin.P8, DigitalPin.P13]; let directionB: DigitalPin[] = [DigitalPin.P12, DigitalPin.P14]; let speedPins: AnalogPin[] = [AnalogPin.P16, AnalogPin.P15]; /** Choose the IN1, IN2 and EN/PWM signals of an external H-bridge motor driver. */ //% blockId=mabni_motor_wiring block="wire %motor IN1 %a IN2 %b PWM %pwm" //% group="Wiring" weight=30 export function configure(motor: MabniMotor, a: DigitalPin, b: DigitalPin, pwm: AnalogPin): void { stop(motor); directionA[motor] = a; directionB[motor] = b; speedPins[motor] = pwm; stop(motor); } /** Positive speed goes forward, negative speed reverses. Supply motor power through a driver. */ //% blockId=mabni_motor_run block="run %motor at %speed percent" //% speed.min=-100 speed.max=100 speed.defl=40 //% group="Drive" weight=100 export function run(motor: MabniMotor, speed: number): void { speed = Math.clamp(-100, 100, speed); pins.analogWritePin(speedPins[motor], 0); pins.digitalWritePin(directionA[motor], 0); pins.digitalWritePin(directionB[motor], 0); if (speed > 0) pins.digitalWritePin(directionA[motor], 1); if (speed < 0) pins.digitalWritePin(directionB[motor], 1); pins.analogWritePin(speedPins[motor], Math.round(Math.abs(speed) * 1023 / 100)); } /** Remove the PWM drive signal and leave both direction signals low. */ //% blockId=mabni_motor_stop block="stop %motor" //% group="Drive" weight=95 export function stop(motor: MabniMotor): void { run(motor, 0); } /** Set the two motor speeds separately, for straight driving or turning. */ //% blockId=mabni_robot_drive block="robot left speed %left percent right speed %right percent" //% left.min=-100 left.max=100 left.defl=40 //% right.min=-100 right.max=100 right.defl=40 //% group="Drive" weight=90 export function drive(left: number, right: number): void { run(MabniMotor.Left, left); run(MabniMotor.Right, right); } /** Stop both motor-driver outputs. */ //% blockId=mabni_robot_stop block="stop robot motors" //% group="Drive" weight=85 export function stopAll(): void { drive(0, 0); } }