python - 从函数中获取连续值
问题描述
我目前有一个关于 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很陌生,所以只要它有助于我学习,我都会接受任何批评!希望有人能够帮助我:)
解决方案
推荐阅读
- chatbot - 消息模板在 kore.ai 中不起作用
- html - 由 css 网格驱动的“复杂”矩阵样式网格是否可能?
- javascript - 上传文件后在本地保存文件
- python - 无法将正则表达式与 pyinotify 一起使用
- javascript - 如何保存由复选框列表选择的文件
- gluon - 在android应用程序中使用gluon mobile时不断收到NullPointerException
- r - 将编号分配给与 R 中的循环编号相似的行
- javascript - 设置在另一个模块中实现的抽象、实时可解析的 Vuex 存储?
- spring - 多个测试文件和 MockRestServiceServer,期待来自其他测试文件的调用
- c# - 超时关闭在控制台中无法关闭启动画面