目录
模块代码
from machine import *
import timeclass moto:def __init__(self, pwm0, pwm1):self.pwm0 = pwm0self.pwm1 = pwm1def 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 = pin0self.pin0.irq(trigger=Pin.IRQ_RISING, handler=self.handler0)self.pin1 = pin1self.pin1.irq(trigger=Pin.IRQ_RISING, handler=self.handler1)self.counter = 0self.speed = 0self.tim = Timer(i)self.tim.init(period=20, callback=self.timHandler)def handler0(self, a):if self.pin0.value():self.counter += 1else:self.counter -= 1def handler1(self, a):if not self.pin1.value():self.counter += 1else:self.counter -= 1def timHandler(self, t):self.speed = self.counterself.counter = 0def read(self):return self.speed
使用方法
from machine import *
import time
from moto import *
pin27 = Pin(27, Pin.IN)
pin14 = Pin(14, Pin.IN)
encoder = encoder(pin27, pin14, 0)
pwm5 = PWM(Pin(5), freq=1000)
pwm4 = PWM(Pin(4), freq=1000)
moto = moto(pwm5, pwm4)
moto.setPwm(500) while True:speed = encoder.read()print("speed:{}".format(speed))time.sleep(0.5)
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!