Speed and Direction

Button Control Program

Now that your H-Bridge is wired, you can write a program to control the motor. The key idea is:

  • To spin one direction: write 0 to P0 and 1 to P1
  • To spin the other direction: write 1 to P0 and 0 to P1
  • To stop: write 0 to both pins

Here is a program that uses buttons to control direction:

Button Control Program

You can import this program from GitHub: https://github.com/League-Microbit/H-Bridge-Control.git

After downloading the program, press the A button to turn the motor one direction, the B button to turn it the other, and the logo (the touch sensor between the buttons) to stop the motors.

Tip
If the motor spins the “wrong” way when you press A, you can either swap the red and black motor wires on the terminal block, or swap the P0/P1 pin assignments in your code.

Speed Control with Analog Write

You can also control the speed of the motor using the analog write command. Instead of writing a simple 1 or 0, analog write sends a PWM signal with a variable duty cycle. A higher value means the motor gets more power and spins faster.

Here is a program that demonstrates speed control:

Duty Cycle Program

You can import this program from GitHub: https://github.com/League-Microbit/duty-cycle-buttons

When you press the A or B buttons, this program writes a square wave duty cycle signal to the H-Bridge using the analog write feature, which will start the motor running slowly, then speed it up.

Tip
If the motor does not start spinning at low values, try increasing the starting value. Small motors often need a minimum duty cycle to overcome friction and begin turning.

Challenges

Ready for more? Try these:

  1. Ramp up and down – Write a program that gradually increases speed, holds at full speed for 2 seconds, then gradually decreases back to zero.
  2. Speed selector – Use button A to cycle through 3 preset speeds (slow, medium, fast) and button B to reverse direction.
  3. Two-motor control – Wire the second H-Bridge channel and control two motors independently.
Warning
Remember: always disconnect Vcc first before changing any wires, and connect it last when re-wiring.