Controlling a motor on nodeMCU (ESP8266)

I have bought a CQRobot Metal DC Geared Motor w/Encoder with Metal Mounting Bracket -12V/40RPM /80Kg.cm

From the specs:

This is a Gear Motor w/Encoder, Support 6V and 12V working voltage, for Projects Such as Robot, Custom Servo, Arduino and 3D Printers.

The schematics suggested

The nodeMCU has this pinout

node MCU pinout

I used this nice class from OutOfCheeseError to control the motor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from machine import Pin, ADC, PWM

class DCMotor:
def __init__(self, pwm_pin, direction_pin1, direction_pin2):
"""
pwm_pin: PWM capable pin id. This pin should be connected to ENA/B.
direction_pin1 and direction_pin1: Direction pins to be connected to
N1/2 or N3/4.
"""
self.dir_pin1 = Pin(direction_pin1, mode=Pin.OUT)
self.dir_pin2 = Pin(direction_pin2, mode=Pin.OUT)
self.pwm_pin = Pin(pwm_pin, mode=Pin.OUT)
self.pwm = PWM(self.pwm_pin, freq=100, duty=0)

def forward(self):
self.dir_pin1.on()
self.dir_pin2.off()

def backward(self):
self.dir_pin1.off()
self.dir_pin2.on()

def stop(self):
self.dir_pin1.off()
self.dir_pin2.off()

def set_speed(self, ratio):
"""
sets speed by pwm duty cycle value.
ratio: The speed ratio ranging from 0 to 1.
Anything above 1 will be taken as 1 and negative
as 0.
"""
if ratio < 0:
self.pwm.duty(0)
elif ratio <= 1.0:
self.pwm.duty(int(1024*ratio))
else:
self.pwm.duty(1024)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# D1,D2, D3
motor = DCMotor(5, 4, 0)

print("forward")
motor.forward()
motor.set_speed(0)
sleep(5)
motor.set_speed(0.5)

print("backward")
sleep(5)
motor.backward()
motor.set_speed(1)

print("stop")
sleep(2)
motor.set_speed(0)
motor.stop()