MicroPython-Micro:bit | Grove-超声波游侠|为模块创建驱动程序

问题描述 投票:1回答:1

[我正在尝试将Raspberry的python代码转换为MicroBit MicroPython,以使用MicroPython驱动Grove-Ultrasonic Ranger模块。

http://wiki.seeedstudio.com/Grove-Ultrasonic_Ranger/

https://github.com/Seeed-Studio/grove.py/blob/master/grove/grove_ultrasonic_ranger.py

我这样做了,语法还可以:

from microbit import *
import time


_TIMEOUT1 = 1000
_TIMEOUT2 = 10000


def _get_distance():
    pin0.write_digital(0)
    time.sleep_us(2)
    pin0.write_digital(1)
    time.sleep_us(10)
    pin0.write_digital(0)


    t0 = time.ticks_us()
    count = 0
    while count < _TIMEOUT1:
        if pin0.read_digital():
            display.set_pixel(1, 1, 5)
            break
        count += 1
    if count >= _TIMEOUT1:
        return None

    t1 = time.ticks_us()
    count = 0
    while count < _TIMEOUT2:
        if not pin0.read_digital():
            display.set_pixel(0, 0, 5)
            break
        count += 1
    if count >= _TIMEOUT2:
        return None

    t2 = time.ticks_us()



    dt = int(time.ticks_diff(t1,t0) * 1000000)
    # The problem is upside !


    if dt > 530:
        return  None

    distance = (time.ticks_diff(t2,t1) * 1000000 / 29 / 2)    # cm


    return distance


def get_distance():
    while True:
        dist = _get_distance()
        if dist:
            return dist

#Appel de la fonction get_distance(void) et affichage sur le display
display.scroll(get_distance())

但是我对dt有很大的价值,我不知道为什么...感谢您的帮助!

micropython bbc-microbit
1个回答
1
投票

Seeed Studio代码使用Python的time.time()函数进行计时。从the help

time.time()→浮动

将自纪元以来的时间返回为浮点数。

您的代码使用MicroPython的time.ticks_us()函数。从its help

utime.ticks_ms()

返回带有任意参考点的递增毫秒计数器,该参考点在某个值后回绕。

...

utime.ticks_us()

就像上面的ticks_ms(),但以微秒为单位。

因此您在版本中获得的数字将比原始Python代码大10 ^ 6倍。好像您已经将时差乘以10 ^ 6即可将其转换为微秒,因此只需从计算中删除此系数即可。

© www.soinside.com 2019 - 2024. All rights reserved.