forked from donskytech/micropython-raspberry-pi-pico
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pio_ultrasonic2.py
50 lines (43 loc) · 1.45 KB
/
pio_ultrasonic2.py
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
import time
from machine import Pin
import rp2
dist = 0
echo = Pin(21,Pin.IN)
trig = Pin(20,Pin.OUT)
pwr = Pin(19, Pin.OUT)
pwr.on()
def get_cm(x):
global dist
dist = 300 - sm.get()
#print(dist,time.ticks_ms())
@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW)
def ping():
set(x,0b10010) # 300 in binary 100101100
mov(isr,x) # 5 msb to isr
set(x,0b1100) # 4 lsb
in_(x,4) # shift into isr
mov(x,isr) # mov isr back to x
set(pins,0) [9] # set trig to low 10 uSec
set(pins,1) [9] # set trig to high 10 uSec
set(pins,0) # set trig to low
wait(1,pin,0) # wait for echo input to go high
label('cm')
jmp(x_dec,'ck_echo') [28] # ck for timeout < 300
jmp('do_delay') # if so jmp to 80 ms delay
label('ck_echo')
jmp(pin,'cm') [28] # while echo high jmp to cm
mov(isr,x) # when echo goes low send x to isr
push() # then push to fifo
irq(rel(0)) # trigger irq to "get" value
label('do_delay')
mov(isr,invert(null)) # start timing loop
in_(null,12) # 12 bits = 4096 x 20 = 81920 cycles or ~80 ms
mov(y,invert(isr))
label("delay")
jmp(y_dec, "delay") [19] # end timing loop
sm = rp2.StateMachine(0, ping, freq=1000000, set_base=trig, jmp_pin=echo, in_base=echo)
sm.irq(get_cm)
sm.active(1)
while True:
time.sleep(.5)
print(dist)