Banana Pi BPI-Leaf-S3 MicroPython with TB6612FNG PWM Motor

Hardware preparation

  • TB6612FNG module x 1
  • 5V DC motor x 1
  • Some wires for connection

BPI-Leaf-S3 :

All GPIO pins of the BPI-Leaf-S3 development board that are not occupied by other functions support PWM control.

Pulse-width modulation (PWM) is a method of reducing the average power delivered by an electrical signal, by effectively chopping it up into discrete parts. The average value of voltage (and current) fed to the load is controlled by turning the switch between supply and load on and off at a fast rate. The longer the switch is on compared to the off periods, the higher the total power supplied to the load.

The TB6612FNG is a great dual motor driver that is perfect for interfacing two small DC motors such as our micro metal gearmotors to a microcontroller, and it can also be used to control a single bipolar stepper motor. The MOSFET-based H-bridges are much more efficient than the BJT-based H-bridges used in older drivers such as the L298N and Sanyo’s LB1836M, which allows more current to be delivered to the motors and less to be drawn from the logic supply.

How to connect

TB6612FNG BPI-Leaf-S3
PWMA 11
AIN2 13
AIN1 12
STBY 10
VM 5V
VCC 3.3V
GND GND

Wiring sequence can be modified in the program code accordingly.

TB6612FNG Motor
AO1 Motor N pole
AO2 Motor S pole

The connection between AO1/AO2 and the motor can be arbitrarily exchanged in order to change the direction of rotation.

MicroPython Code

from machine import Pin,PWM
import time

PWM_A = PWM(Pin(11)) #Set PWM output pin
PWM_A.freq(20000) #Set PWM frequency
PWM_A.duty(0) #Set PWM duty cycle
AIN1 = Pin(12,Pin.OUT)
AIN2 = Pin(13,Pin.OUT)
STBY = Pin(10,Pin.OUT)
STBY.on() #When STBY pin is at high level, TB6612FNG starts.

def MOTOR_Forward():
    AIN1.on()
    AIN2.off()
def MOTOR_Reverse():
    AIN1.off()
    AIN2.on()

while True:
    MOTOR_Forward()
    #for cycle is used to control the PWM duty cycle change.
    #The PWM duty cycle control precision is 10bit, ie 0~1023.
    #Some motors require a certain PWM duty cycle to start.
    for i in range(350,1024,1):
       PWM_A.duty(i)
       time.sleep_ms(10)
    for i in range(1022,0,-1):
       PWM_A.duty(i)
       time.sleep_ms(5)
    
    MOTOR_Reverse()
    for i in range(350,1024,1):
       PWM_A.duty(i)
       time.sleep_ms(10)
    for i in range(1022,0,-1):
       PWM_A.duty(i)
       time.sleep_ms(5)

The motor will start to rotate in one direction and gradually accelerate to the maximum speed achievable by the current current in 7 seconds, then gradually decelerate to a standstill in 5 seconds, then rotate in the opposite direction and repeat the process.

wiki page: https://wiki.banana-pi.org/BPI-Leaf-S3