Skip to content

Instantly share code, notes, and snippets.

@tzechienchu
Created December 7, 2022 06:58
Show Gist options
  • Save tzechienchu/faad34c7d62e8e85258428f531dec180 to your computer and use it in GitHub Desktop.
Save tzechienchu/faad34c7d62e8e85258428f531dec180 to your computer and use it in GitHub Desktop.
Simulation Mouse + Motor Control
from machine import Pin, PWM
import time
import random
import uasyncio
t0 = 0
ref0 = 0
pinpwmin = Pin(5,Pin.IN)
pindir = Pin(6,Pin.IN)
def callback1(pin):
global t0, pinpwmin
t0 = time.ticks_us()
pinpwmin.irq(trigger=Pin.IRQ_FALLING, handler=callback2)
def callback2(pin):
global t0, pinpwmin
global ref0
ref0 = time.ticks_us() - t0
pinpwmin.irq(trigger=Pin.IRQ_RISING, handler=callback1)
pinpwmin.irq(trigger=Pin.IRQ_RISING, handler=callback1)
nowdeg = 0
newdeeg = 0
pwmout1 = 0
offset = 0
led = PWM(Pin(0))
led.freq(1000)
def rodan_dir(odir):
rstay = random.randint(0, 100);
if (rstay > 90):
rdir = random.randint(0, 100);
if (rdir > 50):
return 1
else:
return 0
else:
return odir
async def rodan_move():
global nowdeg, newdeg
global ref0, pwmout1
rstep = 0.4
rdir = 0
while(True):
rforce = random.randint(0, 10)
rdir = rodan_dir(rdir)
mmovedeg = rforce*rstep
if (rdir == 0):
newdeg = nowdeg + mmovedeg
else:
newdeg = nowdeg - mmovedeg
if (newdeg >= 360):
newdeg -= 360
if (newdeg < 0):
newdeg += 360
pwmout1 = int(newdeg*182)
await uasyncio.sleep_ms(50)
async def motor_control():
global nowdeg, newdeg, rdir
global ref0, pwmout1, offset
while(True):
refdir = pindir.value()
offset = int(ref0)
if (refdir == 1):
offset = -offset
else:
offset = offset
await uasyncio.sleep_ms(10)
async def combine(control=1):
global nowdeg, newdeg, rdir
global ref0, pwmout1, offset
while(True):
if (control == 1):
pwmout2 = pwmout1 + offset
led.duty_u16(pwmout2) #max 65535
nowdeg = int(pwmout2/182)
else:
led.duty_u16(pwmout1) #max 65535
nowdeg = newdeg
await uasyncio.sleep_ms(10)
async def main():
uasyncio.create_task(rodan_move())
uasyncio.create_task(motor_control())
uasyncio.create_task(combine(control=1))
await uasyncio.sleep_ms(1000*60*60)
uasyncio.run(main())
#print(newdeg, pwmout1, rdir, mmovedeg, pwmout2, refdir, offset)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment