10067浏览
查看: 10067|回复: 0

[uPyCraft IDE] UpyCraft-micropython: 让Microbit燃烧起来

[复制链接]
通过这篇帖子,你将会知道:
  • 图像在microbit屏幕上显示之前,是什么样的代码
  • 乘法运算符怎么处理字符串、数字、图像
  • 怎么检测microbit发生摇晃
  • 怎么选择随机数
  • 怎么让microbit上的图像移动和变淡

所需工具:
硬件:
  • micro:bit主板
  • 数据线

软件:


代码:
  1. from microbit import *
  2. import random
  3. # create an empty image
  4. i = Image("00000:"*5)
  5. # start with the fire at medium intensity
  6. intensity = 0.5
  7. # keep looping
  8. while True:
  9.     # show the image and wait
  10.     display.show(i)
  11.     sleep(100)
  12.    
  13.     # shake the micro:bit to stoke the fire
  14.     if accelerometer.was_gesture("shake"):
  15.         intensity = 1
  16.      
  17.     # shift the image up and fade it slightly
  18.     i = i.shift_up(1) * intensity
  19.    
  20.     # let the fire burn down a little (reduce the intensity)
  21.     intensity *= 0.98
  22.    
  23.     # choose random brightness for bottom row of fire
  24.     for x in range(5):
  25.         i.set_pixel(x, 4, random.randint(0,9))
复制代码

第1行和第2行:导入需要的包
第4行到第7行:初始化图像,全为0表示没有图像。i = Image("00000:"*5)与i =Image("00000:00000:00000:00000:00000")效果一样,全为0表示没有图像,1-9表示有图像,1的颜色最浅
第8行:设置初始化的摇晃强度
第11行:循环开始,从第12行到28行会重复运行
第13行:将图片显示出来
第14行:睡眠0.1秒
第17行和第18行:判断语句,利用microbit的加速传感器检测是否发生摇晃,如果摇晃,将震动强度置1
第21行:将图像向上平移一个单位,并且亮度变为之前的0.98倍
第27行和第28行:一个for循环,循环5次,每一次循环,第4行第x个LED的亮度会随机变化。


效果:
1.没有摇晃
UpyCraft-micropython: 让Microbit燃烧起来图1
2.摇晃
UpyCraft-micropython: 让Microbit燃烧起来图2

根据以上步骤,将代码运行起来,显示的图像就像火焰在燃烧 ^-^

欢迎大家加入uPyCraft-micropython QQ群:619558168
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail