ESP32(MicroPython) 步进电机相关程序增加位置输出

ESP32(MicroPython) 步进电机调速与位置输出

本人近期对步进电机相关程序进行了一些调整,尝试过在控制角度的程序中改用定时器控制步进电机,但在输入特定步数时不能正常运行,因此保留了之前用的使用延时控制步进电机的方式。这次主要改动是把步数在数码管上显示并通过串口输出。视频中只展示了步进电机调速程序。

步进电机串口控制与位置输出(步数模式) 

'''
接线说明:电机模块-->ESP32 IO
         (IN1-IN4)-->(15,2,0,4)
         
         电机模块输出-->28BYJ-48步进电机
         (5V)-->红线
         (O1)-->依次排序                  
'''
#导入Pin模块
from machine import Pin
import time
import tm1637

#定义数码管控制对象
smg=tm1637.TM1637(clk=Pin(16),dio=Pin(17))

#定义步进电机控制对象
motor_a=Pin(15,Pin.OUT,Pin.PULL_DOWN)
motor_b=Pin(2,Pin.OUT,Pin.PULL_DOWN)
motor_c=Pin(0,Pin.OUT,Pin.PULL_DOWN)
motor_d=Pin(4,Pin.OUT,Pin.PULL_DOWN)
    
#步进电机发送脉冲函数
def step_motor_send_pulse(step,fx):
    temp=step
    if fx==0:
        temp=7-step
    if temp==0:
        motor_a.value(1)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(0)
    elif temp==1:
        motor_a.value(1)
        motor_b.value(1)
        motor_c.value(0)
        motor_d.value(0)
    elif temp==2:
        motor_a.value(0)
        motor_b.value(1)
        motor_c.value(0)
        motor_d.value(0)
    elif temp==3:
        motor_a.value(0)
        motor_b.value(1)
        motor_c.value(1)
        motor_d.value(0)
    elif temp==4:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(1)
        motor_d.value(0)
    elif temp==5:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(1)
        motor_d.value(1)
    elif temp==6:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(1)
    elif temp==7:
        motor_a.value(1)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(1)

count=0
while True:
    print("位置",count)
    smg.show("%04d"%count)
    fx1=0
    step1=0
    s=0  
    i=int(input("输入步数(步数为正时顺时针转,反之逆时针转)"))
    count=count+i
    if count<0 :
        count+=4096
    if count>4095 :
        count-=4096
    if i<0 :
        fx1=1
        i=-i
    while True:
        step_motor_send_pulse(step1,fx1)
        step1+=1
        s+=1
        if s==i :
            break
        if step1==8:
            step1=0
        time.sleep_ms(1)
    

步进电机串口控制与位置输出(角度模式)

'''
接线说明:电机模块-->ESP32 IO
         (IN1-IN4)-->(15,2,0,4)
         
         电机模块输出-->28BYJ-48步进电机
         (5V)-->红线
         (O1)-->依次排序                  
'''
#导入Pin模块
from machine import Pin
import time
import tm1637

#定义数码管控制对象
smg=tm1637.TM1637(clk=Pin(16),dio=Pin(17))

#定义步进电机控制对象
motor_a=Pin(15,Pin.OUT,Pin.PULL_DOWN)
motor_b=Pin(2,Pin.OUT,Pin.PULL_DOWN)
motor_c=Pin(0,Pin.OUT,Pin.PULL_DOWN)
motor_d=Pin(4,Pin.OUT,Pin.PULL_DOWN)
    
#步进电机发送脉冲函数
def step_motor_send_pulse(step,fx):
    temp=step
    if fx==0:
        temp=7-step
    if temp==0:
        motor_a.value(1)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(0)
    elif temp==1:
        motor_a.value(1)
        motor_b.value(1)
        motor_c.value(0)
        motor_d.value(0)
    elif temp==2:
        motor_a.value(0)
        motor_b.value(1)
        motor_c.value(0)
        motor_d.value(0)
    elif temp==3:
        motor_a.value(0)
        motor_b.value(1)
        motor_c.value(1)
        motor_d.value(0)
    elif temp==4:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(1)
        motor_d.value(0)
    elif temp==5:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(1)
        motor_d.value(1)
    elif temp==6:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(1)
    elif temp==7:
        motor_a.value(1)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(1)

count=0
while True:
    print("位置",count)
    smg.show("%04d"%count)
    fx1=0
    step1=0
    s=0  
    i=int(input("输入角度(步数为正时顺时针转,反之逆时针转)"))
    count=count+i
    if count<0 :
        count+=360
    if count>359 :
        count-=360
    if i<0 :
        fx1=1
        i=-i
    i=i/365*4096    
    while True:
        step_motor_send_pulse(step1,fx1)
        step1+=1
        s+=1
        if s>=i :
            break
        if step1==8:
            step1=0
        time.sleep_ms(1)
    

步进电机调速与位置输出

(注意:高速模式可能丢步,需要精确读数时不建议使用)

'''
接线说明:电机模块-->ESP32 IO
         (IN1-IN4)-->(15,2,0,4)
         
         电机模块输出-->28BYJ-48步进电机
         (5V)-->红线
         (O1)-->依次排序
         
         按键模块-->ESP32 IO
         (K1-K4)-->(26,25,33,32)
按键功能:KEY1切换正反转,KEY2加速,KEY3减速,KEY4切换高、低速模式
'''
#导入Pin模块
from machine import Pin
import time
from machine import Timer
import tm1637

#定义数码管控制对象
smg=tm1637.TM1637(clk=Pin(16),dio=Pin(17))

#定义按键控制对象
key1=Pin(26,Pin.IN,Pin.PULL_UP)
key2=Pin(25,Pin.IN,Pin.PULL_UP)
key3=Pin(33,Pin.IN,Pin.PULL_UP)
key4=Pin(32,Pin.IN,Pin.PULL_UP)

#定义步进电机控制对象
motor_a=Pin(15,Pin.OUT,Pin.PULL_DOWN)
motor_b=Pin(2,Pin.OUT,Pin.PULL_DOWN)
motor_c=Pin(0,Pin.OUT,Pin.PULL_DOWN)
motor_d=Pin(4,Pin.OUT,Pin.PULL_DOWN)


#定义按键键值
KEY1_PRESS,KEY2_PRESS,KEY3_PRESS,KEY4_PRESS=1,2,3,4
key_en=1
#按键扫描函数
def key_scan():
    global key_en
    if key_en==1 and (key1.value()==0 or key2.value()==0 or
                      key3.value()==0 or key4.value()==0 ):
        time.sleep_ms(10)
        key_en=0
        if key1.value()==0:
            return KEY1_PRESS
        elif key2.value()==0:
            return KEY2_PRESS
        elif key3.value()==0:
            return KEY3_PRESS
        elif key4.value()==0:
            return KEY4_PRESS
    elif key1.value()==1 and key2.value()==1 and key3.value()==1 and key4.value()==1:
        key_en=1
    return 0
    

#步进电机发送脉冲函数
def step_motor_send_pulse(step,fx):
    temp=step
    if fx==0:
        temp=7-step
    if temp==0:
        motor_a.value(1)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(0)
    elif temp==1:
        motor_a.value(1)
        motor_b.value(1)
        motor_c.value(0)
        motor_d.value(0)
    elif temp==2:
        motor_a.value(0)
        motor_b.value(1)
        motor_c.value(0)
        motor_d.value(0)
    elif temp==3:
        motor_a.value(0)
        motor_b.value(1)
        motor_c.value(1)
        motor_d.value(0)
    elif temp==4:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(1)
        motor_d.value(0)
    elif temp==5:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(1)
        motor_d.value(1)
    elif temp==6:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(1)
    elif temp==7:
        motor_a.value(1)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(1)

def time0_irq(time0):
    global count
    if count>4095 :
        count-=4096
    if count<0 :
        count+=4096    
    print("位置",count)
    smg.show("%04d"%count)
    
#程序入口
if __name__=="__main__":
    count=0
    key=0
    fx1=1
    speed1=1
    step1=0
    time0=Timer(0)  #创建time0定时器对象
    time0.init(period=100,mode=Timer.PERIODIC,callback=time0_irq)
    while True:
      if speed1<4:
        key=key_scan()
        if key==KEY1_PRESS:
            fx1=not fx1 
        elif key==KEY2_PRESS:
            if speed1>1:
                speed1-=1
        elif key==KEY3_PRESS:
                speed1+=1
        elif key==KEY4_PRESS:
                speed1=900        
        step_motor_send_pulse(step1,fx1)
        step1+=1
        if fx1==1 :
            count+=1
        if fx1==0 :
            count-=1    
        if step1==8:
            step1=0
        time.sleep_ms(speed1)
      elif 3<speed1<10:
        key=key_scan()
        if key==KEY1_PRESS:
            fx1=not fx1 
        elif key==KEY2_PRESS:
             speed1-=2
        elif key==KEY3_PRESS:
             speed1+=2
        elif key==KEY4_PRESS:
                speed1=900     
        step_motor_send_pulse(step1,fx1)
        step1+=1
        if fx1==1 :
            count+=1
        if fx1==0 :
            count-=1 
        if step1==8:
            step1=0
        time.sleep_ms(speed1)
      elif 9<speed1<22:
        key=key_scan()
        if key==KEY1_PRESS:
            fx1=not fx1 
        elif key==KEY2_PRESS:
             speed1-=4
        elif key==KEY3_PRESS:
             speed1+=4
        elif key==KEY4_PRESS:
                speed1=900     
        step_motor_send_pulse(step1,fx1)
        step1+=1
        if fx1==1 :
            count+=1
        if fx1==0 :
            count-=1 
        if step1==8:
            step1=0
        time.sleep_ms(speed1)
      elif 21<speed1<47:
        key=key_scan()
        if key==KEY1_PRESS:
            fx1=not fx1 
        elif key==KEY2_PRESS:
             speed1-=8
        elif key==KEY3_PRESS:
            if speed1<46:
              speed1+=8
        elif key==KEY4_PRESS:
                speed1=900     
        step_motor_send_pulse(step1,fx1)
        step1+=1
        if fx1==1 :
            count+=1
        if fx1==0 :
            count-=1 
        if step1==8:
            step1=0
        time.sleep_ms(speed1)
      elif speed1>599:
        key=key_scan()
        if key==KEY1_PRESS:
            fx1=not fx1 
        elif key==KEY2_PRESS:
            if speed1>600:
             speed1-=100
        elif key==KEY3_PRESS:
            if speed1<900:
             speed1+=100
        elif key==KEY4_PRESS:
                speed1=1     
        step_motor_send_pulse(step1,fx1)
        step1+=1
        if fx1==1 :
            count+=1
        if fx1==0 :
            count-=1 
        if step1==8:
            step1=0
        time.sleep_us(speed1)
        

相关外设驱动

tm1637

"""
MicroPython TM1637 quad 7-segment LED display driver
https://github.com/mcauser/micropython-tm1637

MIT License
Copyright (c) 2016 Mike Causer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from micropython import const
from machine import Pin
from time import sleep_us, sleep_ms

TM1637_CMD1 = const(64)  # 0x40 data command
TM1637_CMD2 = const(192) # 0xC0 address command
TM1637_CMD3 = const(128) # 0x80 display control command
TM1637_DSP_ON = const(8) # 0x08 display on
TM1637_DELAY = const(10) # 10us delay between clk/dio pulses
TM1637_MSB = const(128)  # msb is the decimal point or the colon depending on your display

# 0-9, a-z, blank, dash, star
_SEGMENTS = bytearray(b'\x3F\x06\x5B\x4F\x66\x6D\x7D\x07\x7F\x6F\x77\x7C\x39\x5E\x79\x71\x3D\x76\x06\x1E\x76\x38\x55\x54\x3F\x73\x67\x50\x6D\x78\x3E\x1C\x2A\x76\x6E\x5B\x00\x40\x63')

class TM1637(object):
    """Library for quad 7-segment LED modules based on the TM1637 LED driver."""
    def __init__(self, clk, dio, brightness=7):
        self.clk = clk
        self.dio = dio

        if not 0 <= brightness <= 7:
            raise ValueError("Brightness out of range")
        self._brightness = brightness

        self.clk.init(Pin.OUT, value=0)
        self.dio.init(Pin.OUT, value=0)
        sleep_us(TM1637_DELAY)

        self._write_data_cmd()
        self._write_dsp_ctrl()

    def _start(self):
        self.dio(0)
        sleep_us(TM1637_DELAY)
        self.clk(0)
        sleep_us(TM1637_DELAY)

    def _stop(self):
        self.dio(0)
        sleep_us(TM1637_DELAY)
        self.clk(1)
        sleep_us(TM1637_DELAY)
        self.dio(1)

    def _write_data_cmd(self):
        # automatic address increment, normal mode
        self._start()
        self._write_byte(TM1637_CMD1)
        self._stop()

    def _write_dsp_ctrl(self):
        # display on, set brightness
        self._start()
        self._write_byte(TM1637_CMD3 | TM1637_DSP_ON | self._brightness)
        self._stop()

    def _write_byte(self, b):
        for i in range(8):
            self.dio((b >> i) & 1)
            sleep_us(TM1637_DELAY)
            self.clk(1)
            sleep_us(TM1637_DELAY)
            self.clk(0)
            sleep_us(TM1637_DELAY)
        self.clk(0)
        sleep_us(TM1637_DELAY)
        self.clk(1)
        sleep_us(TM1637_DELAY)
        self.clk(0)
        sleep_us(TM1637_DELAY)

    def brightness(self, val=None):
        """Set the display brightness 0-7."""
        # brightness 0 = 1/16th pulse width
        # brightness 7 = 14/16th pulse width
        if val is None:
            return self._brightness
        if not 0 <= val <= 7:
            raise ValueError("Brightness out of range")

        self._brightness = val
        self._write_data_cmd()
        self._write_dsp_ctrl()

    def write(self, segments, pos=0):
        """Display up to 6 segments moving right from a given position.
        The MSB in the 2nd segment controls the colon between the 2nd
        and 3rd segments."""
        if not 0 <= pos <= 5:
            raise ValueError("Position out of range")
        self._write_data_cmd()
        self._start()

        self._write_byte(TM1637_CMD2 | pos)
        for seg in segments:
            self._write_byte(seg)
        self._stop()
        self._write_dsp_ctrl()

    def encode_digit(self, digit):
        """Convert a character 0-9, a-f to a segment."""
        return _SEGMENTS[digit & 0x0f]

    def encode_string(self, string):
        """Convert an up to 4 character length string containing 0-9, a-z,
        space, dash, star to an array of segments, matching the length of the
        source string."""
        segments = bytearray(len(string))
        for i in range(len(string)):
            segments[i] = self.encode_char(string[i])
        return segments

    def encode_char(self, char):
        """Convert a character 0-9, a-z, space, dash or star to a segment."""
        o = ord(char)
        if o == 32:
            return _SEGMENTS[36] # space
        if o == 42:
            return _SEGMENTS[38] # star/degrees
        if o == 45:
            return _SEGMENTS[37] # dash
        if o >= 65 and o <= 90:
            return _SEGMENTS[o-55] # uppercase A-Z
        if o >= 97 and o <= 122:
            return _SEGMENTS[o-87] # lowercase a-z
        if o >= 48 and o <= 57:
            return _SEGMENTS[o-48] # 0-9
        raise ValueError("Character out of range: {:d} '{:s}'".format(o, chr(o)))

    def hex(self, val):
        """Display a hex value 0x0000 through 0xffff, right aligned."""
        string = '{:04x}'.format(val & 0xffff)
        self.write(self.encode_string(string))

    def number(self, num):
        """Display a numeric value -999 through 9999, right aligned."""
        # limit to range -999 to 9999
        num = max(-999, min(num, 9999))
        string = '{0: >4d}'.format(num)
        self.write(self.encode_string(string))

    def numbers(self, num1, num2, colon=True):
        """Display two numeric values -9 through 99, with leading zeros
        and separated by a colon."""
        num1 = max(-9, min(num1, 99))
        num2 = max(-9, min(num2, 99))
        segments = self.encode_string('{0:0>2d}{1:0>2d}'.format(num1, num2))
        if colon:
            segments[1] |= 0x80 # colon on
        self.write(segments)

    def temperature(self, num):
        if num < -9:
            self.show('lo') # low
        elif num > 99:
            self.show('hi') # high
        else:
            string = '{0: >2d}'.format(num)
            self.write(self.encode_string(string))
        self.write([_SEGMENTS[38], _SEGMENTS[12]], 2) # degrees C

    def show(self, string, colon=False):
        segments = self.encode_string(string)
        if len(segments) > 1 and colon:
            segments[1] |= 128
        self.write(segments[:4])

    def scroll(self, string, delay=250):
        segments = string if isinstance(string, list) else self.encode_string(string)
        data = [0] * 8
        data[4:0] = list(segments)
        for i in range(len(segments) + 5):
            self.write(data[0+i:4+i])
            sleep_ms(delay)


class TM1637Decimal(TM1637):
    """Library for quad 7-segment LED modules based on the TM1637 LED driver.

    This class is meant to be used with decimal display modules (modules
    that have a decimal point after each 7-segment LED).
    """

    def encode_string(self, string):
        """Convert a string to LED segments.

        Convert an up to 4 character length string containing 0-9, a-z,
        space, dash, star and '.' to an array of segments, matching the length of
        the source string."""
        segments = bytearray(len(string.replace('.','')))
        j = 0
        for i in range(len(string)):
            if string[i] == '.' and j > 0:
                segments[j-1] |= TM1637_MSB
                continue
            segments[j] = self.encode_char(string[i])
            j += 1
        return segments

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以通过以下步骤使用Micropython控制ESP32上的42步进电机: 1. 首先,确保你的ESP32上已经安装了Micropython固件。你可以在官方网站上找到适用于ESP32Micropython固件,并按照官方文档的指导进行安装。 2. 连接步进电机ESP32。根据引用中提到的特性,你需要使用一个适当的驱动来控制步进电机。根据你的步进电机型号,选择合适的驱动电路,并将其连接到ESP32的GPIO引脚上。 3. 在Micropython中编写代码来控制步进电机。你可以使用GPIO库来控制ESP32的引脚。以下是一个示例代码,演示如何使用Micropython控制42步进电机: ```python import machine import utime # 定义步进电机的引脚 coil_A_1_pin = machine.Pin(12, machine.Pin.OUT) coil_A_2_pin = machine.Pin(14, machine.Pin.OUT) coil_B_1_pin = machine.Pin(27, machine.Pin.OUT) coil_B_2_pin = machine.Pin(26, machine.Pin.OUT) # 定义步进电机的步进顺序 StepCount = 8 Seq = range(0, StepCount) Seq[0] = [1, 0, 0, 0] Seq[1] = [1, 1, 0, 0] Seq[2] = [0, 1, 0, 0] Seq[3] = [0, 1, 1, 0] Seq[4] = [0, 0, 1, 0] Seq[5] = [0, 0, 1, 1] Seq[6] = [0, 0, 0, 1] Seq[7] = [1, 0, 0, 1] # 定义步进电机的转动方向 StepDir = 1 # 定义步进电机的转动速度 WaitTime = 0.001 # 控制步进电机转动指定的步数 def move_steps(steps): for i in range(steps): for pin in range(4): xpin = Seq[StepCounter][pin] if xpin != 0: if pin == 0: coil_A_1_pin.on() coil_A_2_pin.off() coil_B_1_pin.off() coil_B_2_pin.off() elif pin == 1: coil_A_1_pin.on() coil_A_2_pin.on() coil_B_1_pin.off() coil_B_2_pin.off() elif pin == 2: coil_A_1_pin.off() coil_A_2_pin.on() coil_B_1_pin.off() coil_B_2_pin.off() elif pin == 3: coil_A_1_pin.off() coil_A_2_pin.on() coil_B_1_pin.on() coil_B_2_pin.off() StepCounter += StepDir # 控制步进电机转动的速度 utime.sleep(WaitTime) # 控制步进电机转动一圈 move_steps(4096) ``` 这段代码使用了GPIO库来控制ESP32的引脚,通过改变引脚的状态来控制步进电机的转动。你可以根据你的具体引脚连接情况进行相应的修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路易斯720

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值