from machine import Pin, PWM, Timer from time import sleep from math import sin, pi, floor Out1 = Pin(18, Pin.OUT) Out2 = Pin(19, Pin.OUT) fwd = PWM(Pin(18)) rev = PWM(Pin(19)) fwd.freq(100) rev.freq(100) pin1 = Pin(26,Pin.IN) pin2 = Pin(27,Pin.IN,Pin.PULL_UP) N1 = N2 = N12 = 0 flag = 0 def ChanA(pin1): global pin2 global N1 if(pin1.value() ^ pin2.value()): N1 += 1 else: N1 -= 1 pin1.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=ChanA) def tick(timer): global N1, N2, N12, flag X = N1 N12 = N1 - N2 N2 = X flag = 1 tim = Timer() tim.init(freq=20, mode=Timer.PERIODIC, callback=tick) t = V = 0 dt = 1/20 kv = 65535 / 13.4 # convert volts to pwm kq = 2*pi/500 # convert counts to radians kw = 0.16*pi/2 fwd.duty_u16(0) rev.duty_u16(0) while(t < 2): while(flag == 0): pass flag = 0 if(t < 1): V = 5 else: V = 0 fwd.duty_u16(int(V*kv)) Angle = N1*kq Speed = N12*kw print('{: 7.2f}'.format(t), '{: 7.2f}'.format(V), '{: 7.4f}'.format(Angle), '{: 7.4f}'.format(Speed)) t += dt print('Stop') fwd.duty_u16(0) rev.duty_u16(0)