Class Motor control. Pin setup ?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
ohaldi
Posts: 4
Joined: Mon Dec 21, 2020 9:50 pm

Class Motor control. Pin setup ?

Post by ohaldi » Mon Oct 25, 2021 3:09 pm

Hello
I'm a newbie with MicroPython. I can't find out my Problem.
I found this sample on the web to control a DC motor
The class:
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)
print('MAIN.PY : Direction des pins initialisées')
print(self.dir_pin1.value())
print(self.dir_pin2.value())

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

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

def set_speed(self, ratio):
"""
définit la vitesse par la valeur du cycle de travail pwm.
ratio : Le rapport de vitesse allant de 0 à 1.
Tout ce qui est supérieur à 1 sera considéré comme 1 et les valeurs négatives comme 0.
"""
if ratio < 0:
self.pwm.duty(0)
elif ratio <= 1.0:
self.pwm.duty(int(1024*ratio))
else:
self.pwm.duty(1024)
etc...

After the first boot, I send a commande like this:
# pin 14 for PWM / Speed
# pin 26 & 27 for the direction
motor = DCMotor(14,27,26)
motor.forward()
motor.set_speed(0.90)
sleep(5)
motor.stop()

If I try to restart the motor again, nothing happend. If I reset the ESP32 then it's work again.
I checked all pin values with the help of print(self.dir_pin2.value()), every think sem to be OK.
I'm using MicroPython Version esp32-idf3-20210202-v1.14.bin.
Many thanks in advance for your help
Otto

ohaldi
Posts: 4
Joined: Mon Dec 21, 2020 9:50 pm

Re: Class Motor control. Pin setup ?

Post by ohaldi » Mon Oct 25, 2021 9:55 pm

I found a solution with a another sample. This one work.
class LM298(object):
def __init__(self, en, in1, in2, freq=50):
self.freq = freq
self.speed = 0
self.p_en = PWM(Pin(en), freq=self.freq, duty=self.speed)
self.p_in1 = Pin(in1, Pin.OUT)
self.p_in2 = Pin(in2, Pin.OUT)
self.p_in1(0)
self.p_in2(0)

def stop(self):
self.p_en.duty(0)
self.p_in1(0)
self.p_in2(0)

def forward(self):
self.p_in2(0)
self.p_en.duty(self.speed)
self.p_in1(1)

def reverse(self):
self.p_in1(0)
self.p_en.duty(self.speed)
self.p_in2(1)

def set_speed(self, speed):
self.speed = min(1023, max(0, speed))

User avatar
OlivierLenoir
Posts: 126
Joined: Fri Dec 13, 2019 7:10 pm
Location: Picardie, FR

Re: Class Motor control. Pin setup ?

Post by OlivierLenoir » Tue Oct 26, 2021 5:11 am

You can find a driver for a L298 dual H-Dridge here.
An other forum topic exist here.

Post Reply