首页 > 解决方案 > 从函数中获取连续值

问题描述

我目前有一个关于 micro:bit 的学校任务,更具体地说是 bit:bots。我正在尝试编写一个代码,当机器人距离墙壁 5 厘米或更近时,它会停止并反转。我的问题是我的代码只在每次代码执行时才获得与声纳(HC-SR04)的距离,而不是在真正需要检查距离的代码期间。

我尝试将声纳代码的不同部分设置为 while 循环,但没有成功(可能只是将错误的部分设置为循环)。我还尝试了不同的方法来编写主代码,它告诉机器人要遵循哪些功能。

from microbit import *
import neopixel
import time
from utime import ticks_us, sleep_us

np = neopixel.NeoPixel(pin13, 12) 
headlight = (150,150,100)
rearlight = (180,0,0)
reversinglight = (50,50,50)
indicator = (255,80,0)

def sonar():
    pin15.write_digital(1)
    sleep_us(10) 
    pin15.write_digital(0)
    pin15.set_pull(SONAR.NO_PULL)
    while pin15.read_digital() == 0:
        pass 
    start = ticks_us() 
    while pin15.read_digital() == 1:
        pass 
    end = ticks_us()
    echo = end-start 
    distance = int(0.01715 * echo)
    return distance 

def forover():
    pin1.write_analog(500)
    pin12.write_digital(0)
    pin0.write_analog(500)
    pin8.write_digital(0)

    np[9]  = headlight
    np[3]  = headlight
    np[5]  = headlight
    np[4]  = headlight
    np[10]  = headlight
    np[11]  = headlight
    np.show() 

    while True: 
        np[0]  = indicator
        np[1]  = indicator
        np[6]  = indicator
        np[7]  = indicator 
        np.show() 
        sleep(600)
        np[0]  = (0,0,0)
        np[1]  = (0,0,0)
        np[6]  = (0,0,0)
        np[7]  = (0,0,0)
        np.show() 
        sleep(600)

def reverse(): 
    pin1.write_analog(200) 
    pin12.write_digital(1) 
    pin0.write_analog(200) 
    pin8.write_digital(1) 

    np[5]  = rearlight
    np[4]  = rearlight
    np[11]  = rearlight
    np[10]  = rearlight
    np[9]  = reversinglight
    np[8]  = reversinglight
    np[3]  = reversinglight
    np[2]  = reversinglight
    np.show()

    while True:
        pin14.write_digital(1)
        np[0]  = indicator
        np[1]  = indicator
        np[6]  = indicator
        np[7]  = indicator
        np.show()
        sleep(600)
        np[0]  = (0,0,0)
        np[1]  = (0,0,0)
        np[6]  = (0,0,0)
        np[7]  = (0,0,0)
        np.show()
        pin14.write_digital(0) 
        sleep(600)

while True:
    if sonar() <= 5:
        reverse()
    else:
        forover()

我对python很陌生,所以只要它有助于我学习,我都会接受任何批评!希望有人能够帮助我:)

标签: python

解决方案


推荐阅读