亲,“电路城论坛”已合并升级到更全、更大、更强的「新与非网」。了解「新与非网」
签到天数: 7 天
连续签到: 1 天
[LV.3]偶尔看看II
from microbit import * display.show(Image.ARROW_N) pin11.write_digital(0) pin12.write_digital(1) pin13.write_digital(0) pin19.write_digital(1) while True: num = 0 pin5.write_digital(0) pin5.write_digital(1) sleep(0.01) if pin8.read_digital() != True: pin5.write_digital(0) pin5.write_digital(1) sleep(0.01) while pin8.read_digital(): num = num + 1 if num <= 8: display.show(Image.ARROW_W) pin11.write_digital(1) pin12.write_digital(0) pin13.write_digital(0) pin19.write_digital(1) sleep(1000) display.show(Image.ARROW_N) pin11.write_digital(0) pin12.write_digital(1) pin13.write_digital(0) pin19.write_digital(1) 接下来,我们一起来分析一下代码。 通过上面的代码,不难发现,控制避障车前进的代码部分我们重复编写了两遍,在实际项目中这种写法是不合理的。为了让代码更加简洁,优雅,我们将控制前进的代码部分提取出来建立名称为Go()的函数,在需要执行前进的地方直接调用Go()函数即可。 from microbit import * def Go(): display.show(Image.ARROW_N) pin11.write_digital(0) pin12.write_digital(1) pin13.write_digital(0) pin19.write_digital(1) Go() while True: num = 0 pin5.write_digital(0) pin5.write_digital(1) sleep(0.01) if pin8.read_digital() != True: pin5.write_digital(0) pin5.write_digital(1) sleep(0.01) while pin8.read_digital(): num = num + 1 if num <= 8: display.show(Image.ARROW_W) pin11.write_digital(1) pin12.write_digital(0) pin13.write_digital(0) pin19.write_digital(1) sleep(1000) Go()复制代码
from microbit import * def Go(): display.show(Image.ARROW_N) pin11.write_digital(0) pin12.write_digital(1) pin13.write_digital(0) pin19.write_digital(1) def Turn(): display.show(Image.ARROW_W) pin11.write_digital(1) pin12.write_digital(0) pin13.write_digital(0) pin19.write_digital(1) def Detection(): num=0 pin5.write_digital(0) pin5.write_digital(1) sleep(0.01) if pin8.read_digital() != True: pin5.write_digital(0) pin5.write_digital(1) sleep(0.01) while pin8.read_digital(): num = num + 1 return num Go() while True: num = Detection() if num <= 8: Turn() sleep(1000) Go() 复制代码
下载资料失效了?点击此处告知管理员 > >
使用道具 举报
本版积分规则 发表回复 回帖后跳转到最后一页
查看 »
手机版|小黑屋|与非网
GMT+8, 2024-11-24 21:58 , Processed in 0.112380 second(s), 16 queries , MemCache On.
苏公网安备 32059002001037号
Powered by Discuz! X3.4
Copyright © 2001-2024, Tencent Cloud.