Created
July 10, 2018 07:41
-
-
Save theodox/020f796bab2954f92645ff4bb8f31ed0 to your computer and use it in GitHub Desktop.
Micropython pyboard code for cailbrating and sensing with an ultrasonic sensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pyb import Pin, ExtInt, LED | |
import time | |
import utime | |
import micropython | |
micropython.alloc_emergency_exception_buf(100) | |
global last_ping, delta, LAG | |
ROUNDTRIP = 58.774 # speed of sound per cm in microseconds * 2 for round trip | |
LAG = 500 # totally hacky lag compensation | |
last_ping = utime.ticks_us() | |
delta = utime.ticks_diff(utime.ticks_us(), last_ping) | |
echo = Pin('Y7', Pin.IN) | |
trigger = Pin('Y8', Pin.OUT) | |
def print_delta(d): | |
# this is called by the interrupt handler | |
print (delta, " == ", ((d - LAG) // ROUNDTRIP), " cm") | |
def cb(_): | |
global last_ping, delta | |
# remember : no floating poing inside an interrupt! | |
delta = utime.ticks_diff(utime.ticks_us(), last_ping) - 20 | |
micropython.schedule(print_delta, delta) | |
ext = ExtInt(echo, ExtInt.IRQ_FALLING, Pin.PULL_UP, cb) | |
def ping(): | |
global last_ping, delta | |
trigger.low() | |
time.sleep_ms(100) | |
trigger.high() | |
last_ping = utime.ticks_us() | |
time.sleep_us(100) | |
trigger.low() | |
time.sleep_ms(2) | |
def calibrate(measured_distance_in_cm): | |
COUNT = 64 | |
global last_ping, delta, LAG | |
avg = 0 | |
for n in range(COUNT): | |
ping() | |
time.sleep_ms(16) | |
if n > 0: | |
avg += delta // (COUNT - 1) | |
print ("average roundtrip = ", avg) | |
print ("expected roundtrip = ", measured_distance_in_cm * ROUNDTRIP) | |
print ("---------------------") | |
LAG = avg - (measured_distance_in_cm * ROUNDTRIP) | |
print ("calculated lag = ", LAG) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment