当前位置:   article > 正文

micropython编程 esp32+drv8833+霍尔编码器_micropython drv8833

micropython drv8833

模块代码

from machine import *
import time


class moto:
    def __init__(self, pwm0, pwm1):
        self.pwm0 = pwm0
        self.pwm1 = pwm1
        
    def setPwm(self, pwm):
        pwm = int(pwm)
        if pwm < 0:
            self.pwm0.duty(-pwm)
            self.pwm1.duty(0)
        else:
            self.pwm0.duty(0)
            self.pwm1.duty(pwm)
            
            
class encoder:
    def __init__(self, pin0, pin1, i):
        self.pin0 = pin0
        self.pin0.irq(trigger=Pin.IRQ_RISING, handler=self.handler0)
        self.pin1 = pin1
        self.pin1.irq(trigger=Pin.IRQ_RISING, handler=self.handler1)
        self.counter = 0
        self.speed = 0
        
        self.tim = Timer(i)
        self.tim.init(period=20, callback=self.timHandler)
    
    def handler0(self, a):
        if self.pin0.value():
            self.counter += 1
        else:
            self.counter -= 1
    
    def handler1(self, a):
        if not self.pin1.value():
            self.counter += 1
        else:
            self.counter -= 1
                
    def timHandler(self, t):
        self.speed = self.counter
        self.counter = 0
                
    def read(self):
        return self.speed

  • 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
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

使用方法

from machine import *
import time
from moto import *


# 编码器初始化
pin27 = Pin(27, Pin.IN)
pin14 = Pin(14, Pin.IN)   
encoder = encoder(pin27, pin14, 0)   # 参数(编码器A相引脚,编码器B相引脚,定时器序号)

# 电机初始化
pwm5 = PWM(Pin(5), freq=1000)
pwm4 = PWM(Pin(4), freq=1000)
moto = moto(pwm5, pwm4)
moto.setPwm(500)  # 范围0-1023

  
while True:
    speed = encoder.read()
    print("speed:{}".format(speed))
    time.sleep(0.5)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/599739
推荐阅读
相关标签
  

闽ICP备14008679号