2024年2月10日 星期六

micro:bit Python Editor簡介以及範例

micro:bit Python Editor:https://python.microbit.org/v/3


從上圖來看,由左到右分別為主功能表、程式編輯區、以及micro:bit模擬區,感覺上設計很友善。在左下方的語言和設置選項,可以更改為繁體中文。


選擇繁體中文後,畫面如下:
以下說明參考文件。
1.變數(Variables)
變數可用來儲存可改變的數據,例如:作品的名稱、長或寛等。 

 2.顯示器(Display)

顯示數據在micro:bit 5x5 矩陣LED上,clear()表示清除,show()為顯示。

範例一、運用scroll和show來顯示文字或數字,scroll會以捲動方式呈現。 

1
2
3
4
5
from microbit import display
name = 'Tree Art'
display.scroll(name)
width = 2
display.show(width)

範例二、用Image來設計矩陣LED顯示的圖案,以0-9數字表示,0表示全暗,9表示全亮,':'表示換行。set_pixel(x,y,亮度)可以設計(x,y)的亮度。
1
2
3
4
5
6
7
from microbit import display

display.show(Image('01234:56789:'
                   '01234:'
                   '56789:'
                   '01234'))
display.set_pixel(1,0,9)

執行結果:

3.按鈕(Buttons)
範例三、is_pressed()和was_pressed()的差別,前者是當下按下,而後者是曾經按下。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from microbit import *

while True:
    if button_a.is_pressed() and button_b.is_pressed():
        display.scroll('A and B')
    elif button_a.is_pressed():
        display.scroll('A')
    elif button_b.was_pressed():
        display.scroll('B')
    sleep(1000)

範例四:讀取按鍵被按下次數
1
2
3
4
5
from microbit import *

display.scroll('Press A')
sleep(3000)
display.scroll(button_a.get_presses())

4.迴圈(Loops)
範例五、雙迴圈
1
2
3
4
5
6
from microbit import *

for y in range(5):
    for x in range(5):
        display.set_pixel(x, y, 9)
        sleep(50)

5.邏輯(Logic)
範例六、if-break的使用範列
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from microbit import *

while True:
    if button_a.was_pressed():
        display.show('A')
    elif button_b.was_pressed():
        display.show('B')
    if accelerometer.was_gesture('shake'):
        break
display.scroll('Game over')

6.加速度感測器(Accelermeter)
範例七、當加速度感測器偵測到遙動以及向上時,分別顯示相對應圖示。
1
2
3
4
5
6
7
from microbit import *

while True:
    if accelerometer.was_gesture('shake'):
        display.show(Image.CONFUSED)
    if accelerometer.was_gesture('up'):
        display.show(Image.ARROW_N)

7.註解(Comments)
用#做為註解的開頭符號,範例請參考範例八。

8.數學(Maths)
範例八、取亂數、絕對值、和整數等數學運算
1
2
3
4
5
6
7
8
9
from microbit import *
import random

#隨機產生1到6的其中一個數字,並顯示在5x5矩陣LED上
display.scroll(random.randint(1, 6))
#取得加速計的y軸數值,並取其絕對值
display.scroll(abs(accelerometer.get_y()))
#取4.9數值的整數值
display.scroll(int(4.9))

9.列表(陣列)(Lists(aarays))
範例九、樹藝是利用樹皮、葉脈、種子的工藝
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from microbit import *
TreeArt=[]
TreeArt.append('bark')#樹皮
TreeArt.append('vein')#葉脈
TreeArt.append('seed')#種子
display.scroll('Tree Art is the art of using ')
while True:
    for index, name in enumerate(TreeArt):
        display.scroll(name)
        if index<2:
            display.scroll(', ')
        else:
            display.scroll('.')
說明:for index, name in enumerate(TreeArt),利用enumerate(TreeArt)分別回傳項目的索引值和名稱。

10.功能或函式(Functions)
範例十、定義函式
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from microbit import *
#定義函式
def ShowTreeArt():
    TreeArt=[]
    TreeArt.append('bark')#樹皮
    TreeArt.append('vein')#葉脈
    TreeArt.append('seed')#種子
    display.scroll('Tree Art is the art of using ')
    for index, name in enumerate(TreeArt):
       display.scroll(name)
       if index<2:
           display.scroll(', ')
       else:
           display.scroll('.')
while True:
    ShowTreeArt()#呼叫函式
    display.clear()
    sleep(2000)
11.無線電(Radio)
範例十一、Send a smile,網址:https://python.microbit.org/v/3/ideas/send-a-smile
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from microbit import *
import radio


radio.config(group=1)
radio.on()

while True:
    message = radio.receive()
    if message:
        display.show(Image.HAPPY)
    if button_a.was_pressed():
        display.clear()
        radio.send('smile')
說明:

上圖右下角有模擬無線電傳送功能,在其左方有一個下拉表單,按下後可以查看傳送和接收情形。


12.光度(Light level)
範例十二、讀取光度
1
2
3
4
from microbit import *


display.scroll(display.read_light_level())
執行結果:


13.溫度(Temperature)
範例十三、溫度
1
2
3
from microbit import *

display.scroll(temperature())
執行結果:

14.羅盤(Compass)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from microbit import *

display.scroll(compass.heading())
magnet_strength_x = compass.get_x()
display.scroll(magnet_strength_x)
magnet_strength_y = compass.get_y()
display.scroll(magnet_strength_y)
magnet_strength_z = compass.get_z()
display.scroll(magnet_strength_z)
magnet_strength_all = compass.get_field_strength()
display.scroll(magnet_strength_all)
執行結果:

15.聲音(Sound)
範例十五、聲音和語音
1
2
3
4
5
6
7
8
import music
import speech
from microbit import *

music.play(music.BIRTHDAY)
speech.say('Hello, world. How are you?')
music.play(['c', 'd', 'e', 'c'])
audio.play(Sound.GIGGLE)

16.麥克風(Microphone) V2
範例十六、麥克風
1
2
3
4
5
6
7
from microbit import *

while True:
    if microphone.current_event() == SoundEvent.LOUD:
        display.show(Image.HAPPY)
    elif microphone.current_event() == SoundEvent.QUIET:
        display.show(Image.ASLEEP)
執行結果:

17.觸控標誌(Touch logo) V2
範例十七、觸控標誌
1
2
3
4
5
from microbit import *

while True:
    if pin_logo.is_touched():
        display.show(Image.HAPPY)
執行結果:

18.數據記錄(Data logging) V2
範例十八、每隔1秒,記錄溫度、聲音、和光度。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from microbit import *
import log


log.set_labels('temperature', 'sound', 'light')
@run_every(s=1)
def log_data():
    log.add({
      'temperature': temperature(),
      'sound': microphone.sound_level(),
      'light': display.read_light_level()
    })
    
while True:
    sleep(100000)
執行結果:

19.引腳(Pins)
20.NeoPixels
有關引腳和NeoPixel的範例,可以參考micro:bit -悟空板(WuKong):NeoPixel測試 (Python版)
21.資料處理(Data types)
範例十九、數字轉字串
1
2
3
4
from microbit import *

score = 17
display.scroll('Score: ' + str(score))
22.字串操作(String manipulation)
可以參考範例十九
23.文字輸入和輸出(Text input and output)
範例二十、文字輸入和輸出
1
2
3
4
5
6
7
from microbit import *

while True:
    name = input('What is your name? ')
    print('Hello', name)
    display.scroll('Hello'+ name)
    sleep(1000)
執行結果:

24.高等數學(Advanced maths)
範例二十一、數學和邏輯運算
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from microbit import *
from math import *

display.scroll(pi)
display.scroll(sqrt(25))
display.scroll(cos(1))
display.scroll(radians(180))#角度轉徑度
display.scroll(degrees(3))#徑度轉角度
display.scroll(log(10, 2))
number = 0b11111111#二進位
display.scroll(number)
number = 0xFF#十六進位
display.scroll(number)
x = 0b11110000
y = 0b10101010
display.scroll(bin(x & y))#和
display.scroll(bin(x | y))#或
display.scroll(bin(x ^ y))#互斥
display.scroll(bin(x << 4))#左移
display.scroll(bin(x >> 2))#右移
display.scroll(bin(~x))#取補數

2024年1月28日 星期日

micro:bit -悟空板(WuKong):土壤溼度(Soil Humidity)感測器測試 (MakeCode版)

準備材料:

  1. micro:bit主板 x 1
  2. USB 連接線 x 1
  3. GVS接腳的LED x1
  4. GVS接腳的土壤溼度計 x 1
  5. 悟空板 WuKong x 1

接線:

  1. LED接在P15
  2. 土壤溼度感測器接在P0

程式:





執行結果:



micro:bit -悟空板(WuKong):馬達測試 (MakeCode版)

悟空板介紹:Wukong Breakout Board 悟空擴充板

馬達連接接腳

程式編輯:https://makecode.microbit.org/#editor

安裝悟空板的驅動


選擇上圖wukong選項。

範例一、馬達測試:


執行結果:


範例二、按鈕控制


執行結果:




micro:bit -悟空板(WuKong):NeoPixel測試 (Python版)

範例一:分別以紅色、綠色、藍色、白色點亮悟空板上的四顆燈 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Imports go at the top
from microbit import *
import neopixel
np = neopixel.NeoPixel(pin16, 4)


# Code in a 'while True:' loop repeats forever
while True:
    np[0] = (255, 0, 0)
    np[1] = (0, 255, 0)
    np[2] = (0, 0, 255)
    np[3] = (255, 255, 255)
    np.show()

執行結果:

範例二:同範例一,顯示資料用串列變數來儲存

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Imports go at the top
from microbit import *
import neopixel
np = neopixel.NeoPixel(pin16, 4)

leds=[(255,0,0), (0,255,0), (0,0,255), (255,255,255)]
# Code in a 'while True:' loop repeats forever
while True:
    np[0] = leds[0]
    np[1] = leds[1]
    np[2] = leds[2]
    np[3] = leds[3]
    np.show()

執行結果同上題

範列三:每隔0.5秒燈色旋轉

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Imports go at the top
from microbit import *
import neopixel
np = neopixel.NeoPixel(pin16, 4)
i = 0
leds=[(255,0,0), (0,255,0), (0,0,255), (255,255,255)]
# Code in a 'while True:' loop repeats forever
while True:
    np[0] = leds[i]
    np[1] = leds[(i+1)%4]
    np[2] = leds[(i+2)%4]
    np[3] = leds[(i+3)%4]
    np.show()
    sleep(500)
    i=(i+1)%4

執行結果:


範例四、用迴圈改寫程式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Imports go at the top
from microbit import *
import neopixel
np = neopixel.NeoPixel(pin16, 4)
i = 0
leds=[(255,0,0), (0,255,0), (0,0,255), (255,255,255)]
# Code in a 'while True:' loop repeats forever
while True:
    for j in range(4):
        np[j] = leds[(i+j)%4]
    np.show()
    sleep(500)
    i=(i+1)%4

執行結果:
同範例三

micro:bit -悟空板(WuKong):NeoPixel測試 (MakeCode版)

悟空板介紹:Wukong Breakout Board 悟空擴充板

在悟空板上Pin 16接上四顆LED,分別是LED1, LED2, LED3, 和LED4,如下圖。

程式編輯:https://makecode.microbit.org/#editor


在上圖右下方,點選Extensions選項。


點選上圖左方 neopixel的選項,就可以安裝驅動程式。

範例一、依序點亮


執行結果:


範例二、每隔0.5秒循環


執行結果:

範例三、依照聲音大小用長條圖來改變燈條燈數



執行結果:




2024年1月27日 星期六

micro:bit Python 初體驗以樹藝工坊為例

在南投縣草屯鎮國立臺灣工藝研究暨發展中心有一間樹藝工坊,進駐藝術家是李永謨老師,李老師說:樹藝的定義是代表一種;生命的重生、樹生命「特性力量」的發揮。大家可以到臺灣樹藝再生之美李永謨粉絲頁查看李老師的相關作品,我們今天micro:bit Python就以樹藝工坊為例,來說明micro:bit Python的基本程式設計。

功能如下:

  1. 啟動顯示HAPPY圖示
  2. 按下LOGO顥示:Welcome to Tree-Art Workshop!
  3. 拍掌顯示:'I am Lee, Yung-Moo.
  4. 按下A鍵或Pin0,隨機顯示1-6其中一個數字。
  5. 按下B鍵或Pin1,播放音樂。
  6. 按下Pin2顯示ANGRY圖示。

程式編輯器:micro:bit Python Editor (microbit.org)



程式如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Imports go at the top
from microbit import *
import random
import music
display.show(Image.HAPPY)

# Code in a 'while True:' loop repeats forever
while True:
    if pin_logo.is_touched():
        display.scroll('Welcome to Tree-Art Workshop!')
        display.show(Image.HEART)
    if microphone.current_event() == SoundEvent.LOUD:
        display.scroll('I am Lee, Yung-Moo.')
        display.show(Image.HAPPY)
    if button_a.was_pressed() or pin0.is_touched():
        display.show(random.randint(1, 6))
    if button_b.was_pressed() or pin1.is_touched():
        music.play(['c', 'd', 'e', 'c'])
        display.show(random.randint(0, 99))
    if pin2.is_touched():
        display.show(Image.ANGRY)
    sleep(100)

2024年1月24日 星期三

用micro:bit學習Python請用Python Editor

micro:bit官網:https://microbit.org/

micro:bit編輯器:微軟MakeCodePython Editor

MicroPython教材:BBC micro:bit MicroPython documentation

microbit.org官網提供兩種程式語言編輯器,分別是MakeCode和Python編輯器,MakeCode是由微軟開發,提供積木、JavaScript、Python等三種程式語言,積木程式語言適合初學者,以積木方式建立初學者的邏輯概念。我們可以在編輯器的上方,切換不同的程式語言。在MakeCode,不管是JavaScript還是Python,都是和積木呈現1對1的對應關係,對初學者而言,可以經由積木程式語言,來認識JavaScript或Python。雖然MakeCode有支援Python程式語言,但Python編輯器較能提供道地的Python,我們以顯示大心和小心為例。


我們把大心和小心顯示之積木程式轉換成Python。

MakeCode的Python程式:

1
2
3
4
5
6
def on_forever():
    basic.show_icon(IconNames.HEART)
    basic.pause(1000)
    basic.show_icon(IconNames.SMALL_HEART)
    basic.pause(1000)
basic.forever(on_forever)

Python編輯器的Python程式:

1
2
3
4
5
6
7
8
9
# Imports go at the top
from microbit import *

# Code in a 'while True:' loop repeats forever
while True:
    display.show(Image.HEART)
    sleep(1000)
    display.show(Image.HEART_SMALL)
    sleep(1000)

想利用micro:bit來學習Python,請使用Python編輯器。