I want to control two DC motors with two L298N.
I want to use the class DCmotor.
How do I have to adapt this sample code so that I can control two DC motors?
from dcmotor import DCMotor from machine import Pin, PWM from time import sleep frequency = 15000 pin1 = Pin(12, Pin.OUT) pin2 = Pin(14, Pin.OUT) enable = PWM(Pin(13), frequency) dc_motor = DCMotor(pin1, pin2, enable) #Set min duty cycle (350) and max duty cycle (1023) #dc_motor = DCMotor(pin1, pin2, enable, 350, 1023) dc_motor.forward(50) sleep(5) dc_motor.stop() sleep(5) dc_motor.backwards(100) sleep(5) dc_motor.forward(5) sleep(5) dc_motor.stop()
2 Answers
Hi.
First, you need to declare pins for the second motor. For example:
motor2_pin1 = Pin(25, Pin.OUT) motor2_pin2 = Pin(26, Pin.OUT) motor2_enable = PWM(Pin(27), frequency)
You can use any other pins. I’m just showing an example.
Then, you need to create another DCMotor object using those properties. For example:
dc_motor2 = DCMotor(motor2_pin1, motor2_pin2, enable)
Then, to control this motor, you just need to use the forward() and stop() methods on this new DCMotor object.
For example:
dc_motor2.forward(20) dc_motor2.stop()
I hope this is clear.
Regards,
Sara