esp8266通过micropython驱动l298n控制电机

硬件

  • NodeMCU ESP8266
  • L298N驱动板

接线图

这里以单电机为例,双电机同理

  • 电机A

    ENA – 为电机A启用PWM信号

    IN1 – 启用电机A

    IN2 – 启用电机A

  • 电机B

    ENB – 为电机B启用PWM信号

    IN3:启用电机B

    IN4:启用电机B

eniB5L

代码

L298n类将左右两个电机分为A和B,通过 *_A 方法分别对两个电机进行控制

# l298n.py
from machine import Pin, PWM


class L298n:
    def __init__(self, int1=None, int2=None, int3=None, int4=None, ena=None, enb=None, frequency=1000):
        self.int1 = Pin(int1, Pin.OUT) if int1 is not None else None
        self.int2 = Pin(int2, Pin.OUT) if int2 is not None else None
        self.int3 = Pin(int3, Pin.OUT) if int3 is not None else None
        self.int4 = Pin(int4, Pin.OUT) if int4 is not None else None
        self.ena = PWM(Pin(ena), frequency) if ena is not None else None
        self.enb = PWM(Pin(enb), frequency) if enb is not None else None

    def start_A(self, reverse=False, speed=1023):
        if self.int1 and self.int2:
            if reverse is True:
                self.int1.on()
                self.int2.off()
            else:
                self.int1.off()
                self.int2.on()
        else:
            raise 'L298n A start failed.'
        if self.ena:
            self.setup_speed_A(speed)

    def stop_A(self):
        self.int1.off()
        self.int2.off()


    def start_B(self, reverse=False, speed=1023):
        if self.int3 and self.int4:
            if reverse is True:
                self.int3.on()
                self.int4.off()
            else:
                self.int3.off()
                self.int4.on()
        else:
            raise 'L298n B start failed.'

        if self.enb:
            self.setup_speed_B(speed)

    def stop_B(self):
        self.int3.off()
        self.int4.off()

    def setup_speed_A(self, speed=1023):
        if not self.ena:
            raise 'L298n ena not found.'
        self.ena.duty(speed)

    def setup_speed_B(self, speed=1023):
        if not self.enb:
            raise 'L298n enb not found.'
        self.enb.duty(speed)

调用

from l298n import L298n

# 参数为esp8266引脚和l298n驱动板对应

GPIO0 - INT1
GPIO2 - INT2
GPIO4 - ENA

l = L298n(int1=0, int2=2, ena=4)

# 默认以全速运行
# reverse控制电机反转
l.start_A()

# speed的取值范围为0-1023
l.setup_speed_A(speed=600)

最后修改于: 2023年8月9日 17:05