顯示具有 micro:bit 標籤的文章。 顯示所有文章
顯示具有 micro:bit 標籤的文章。 顯示所有文章

2025年8月5日 星期二

[micro:bit] 剪刀、石頭、布

記錄比賽結果,做出統計圖表,看看 micro:bit 和人類(或另一台 micro:bit)對戰時贏了幾場、輸了幾場、平手幾次



Python程式


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def on_button_pressed_a():
    global win
    basic.show_string("Win")
    if mode == 0:
        basic.show_number(win)
    else:
        win += 1
    basic.show_number(win)
input.on_button_pressed(Button.A, on_button_pressed_a)

def on_gesture_shake():
    global randomnumber
    randomnumber = randint(0, 2)
    if randomnumber == 0:
        basic.show_icon(IconNames.SMALL_SQUARE)
    elif randomnumber == 2:
        basic.show_icon(IconNames.SQUARE)
    else:
        basic.show_icon(IconNames.SCISSORS)
input.on_gesture(Gesture.SHAKE, on_gesture_shake)

def on_logo_pressed():
    global mode
    mode = (mode + 1) % 2
    if mode == 0:
        basic.show_string("View")
    else:
        basic.show_string("Edit")
input.on_logo_event(TouchButtonEvent.PRESSED, on_logo_pressed)

def on_button_pressed_ab():
    global tie
    basic.show_string("Tie")
    if mode == 0:
        basic.show_number(tie)
    else:
        tie += 1
    basic.show_number(tie)
input.on_button_pressed(Button.AB, on_button_pressed_ab)

def on_button_pressed_b():
    global lose
    basic.show_string("Lose")
    if mode == 0:
        basic.show_number(lose)
    else:
        lose += 1
    basic.show_number(lose)
input.on_button_pressed(Button.B, on_button_pressed_b)

randomnumber = 0
tie = 0
lose = 0
win = 0
mode = 0
mode = 0
win = 0
lose = 0
tie = 0

2025年7月24日 星期四

[micro:bit] 鋼鐡之心

 


Python 程式:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def on_button_pressed_a():
    global Run, Mode
    Run = 0
    Mode = (Mode + 1) % 9
    basic.show_number(Mode)
input.on_button_pressed(Button.A, on_button_pressed_a)

def on_button_pressed_b():
    global Run, Temp
    Run = 1
    basic.show_icon(IconNames.ANGRY)
    Temp = (Temp + 1) % 2
    if Mode != 5:
        ContinuousServo.turn_off_motor(DigitalPin.P2)
    if Mode != 6:
        strip.clear()
        strip.show()
    if Mode == 6 or Mode == 7:
        strip.show_rainbow(1, 360)
        strip.show()
input.on_button_pressed(Button.B, on_button_pressed_b)

Temp = 0
strip: neopixel.Strip = None
Run = 0
Mode = 0
basic.show_icon(IconNames.ANGRY)
Mode = 0
Run = 0
ContinuousServo.spin_one_way(AnalogPin.P2)
ContinuousServo.spin_other_way(AnalogPin.P2)
ContinuousServo.turn_off_motor(DigitalPin.P2)
strip = neopixel.create(DigitalPin.P1, 16, NeoPixelMode.RGB)
strip.show_rainbow(1, 360)
strip.clear()
strip.show()
strip.show_rainbow(1, 360)
mp3Player.mp3_set_serial(SerialPin.P0)
mp3Player.set_volume(25)

def on_forever():
    global Temp, Mode
    if Run == 1:
        if Mode == 1:
            basic.show_icon(IconNames.HEART)
            basic.pause(500)
            basic.show_icon(IconNames.SMALL_HEART)
            basic.pause(500)
        elif Mode == 2:
            if input.light_level() >= 100:
                basic.show_icon(IconNames.HEART)
            else:
                basic.show_icon(IconNames.SMALL_HEART)
        elif Mode == 3:
            if input.compass_heading() >= 100:
                basic.show_icon(IconNames.HEART)
            else:
                basic.show_icon(IconNames.SMALL_HEART)
        elif Mode == 4:
            if input.sound_level() >= 150:
                if Temp == 0:
                    basic.show_icon(IconNames.HEART)
                else:
                    basic.show_icon(IconNames.SMALL_HEART)
                Temp = (Temp + 1) % 2
        elif Mode == 5:
            if Temp == 0:
                ContinuousServo.spin_one_way_with_speed(AnalogPin.P2, 50)
            else:
                ContinuousServo.spin_other_way_with_speed(AnalogPin.P2, 50)
        elif Mode == 6:
            strip.rotate(1)
            strip.show()
            basic.pause(200)
        elif Mode == 7:
            if Temp == 0:
                ContinuousServo.spin_one_way_with_speed(AnalogPin.P2, 50)
                strip.rotate(1)
            else:
                ContinuousServo.spin_other_way_with_speed(AnalogPin.P2, 50)
                strip.rotate(-1)
            strip.show()
            basic.pause(200)
        elif Mode == 8:
            mp3Player.set_tracking(1, mp3Player.repeatList.NO)
            mp3Player.execute(mp3Player.playType.PLAY)
            Mode = 0
basic.forever(on_forever)

2025年6月3日 星期二

水井村USR導覽暨測驗系統

元件:micro:bitSmart AI LensMP3 PlayerIoT擴充板

接線:MP3 Player接在第1支腳、Smart AI Lens接在第19、20支腳
積木式程式:

Python程式:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def RightWrong(num: number, ans: str):
    global Number2
    if answer[num] == ans:
        mp3Player.set_tracking(8, mp3Player.repeatList.NO)
        basic.show_icon(IconNames.YES)
    else:
        mp3Player.set_tracking(9, mp3Player.repeatList.NO)
        basic.show_icon(IconNames.NO)
    basic.pause(5000)
    Number2 = (Number2 + 1) % 5
    mp3Player.set_tracking(Number2 + 14, mp3Player.repeatList.NO)
    basic.pause(2000)
    basic.show_icon(IconNames.SQUARE)
Number2 = 0
answer: List[str] = []
basic.show_leds("""
    . # . # .
    # # # # #
    . # . # .
    # # # # #
    . # . # .
    """)
basic.pause(500)
mp3Player.mp3_set_serial(SerialPin.P1)
mp3Player.set_volume(25)
PlanetX_AILens.init_module()
PlanetX_AILens.switchfunc(PlanetX_AILens.FuncList.CARD)
basic.show_leds("""
    . . # # #
    . . . # #
    . . . . #
    # # . . .
    # # . . .
    """)
# 0:介紹、1測驗
mode = 0
answer = ["B", "C", "C", "D", "D"]

def on_forever():
    global mode, Number2
    PlanetX_AILens.camera_image()
    if mode == 0 and PlanetX_AILens.number_card(PlanetX_AILens.numberCards.ZERO):
        mp3Player.set_tracking(1, mp3Player.repeatList.NO)
    elif mode == 0 and PlanetX_AILens.number_card(PlanetX_AILens.numberCards.ONE):
        mp3Player.set_tracking(2, mp3Player.repeatList.NO)
    elif mode == 0 and PlanetX_AILens.number_card(PlanetX_AILens.numberCards.TWO):
        mp3Player.set_tracking(3, mp3Player.repeatList.NO)
    elif mode == 0 and PlanetX_AILens.number_card(PlanetX_AILens.numberCards.THREE):
        mp3Player.set_tracking(4, mp3Player.repeatList.NO)
    elif mode == 0 and PlanetX_AILens.number_card(PlanetX_AILens.numberCards.FOUR):
        mp3Player.set_tracking(5, mp3Player.repeatList.NO)
    elif mode == 0 and PlanetX_AILens.number_card(PlanetX_AILens.numberCards.FIVE):
        mp3Player.set_tracking(7, mp3Player.repeatList.NO)
        mode = 1
        Number2 = 0
        basic.pause(5000)
        mp3Player.set_tracking(14, mp3Player.repeatList.NO)
        basic.show_icon(IconNames.SQUARE)
    elif mode == 1 and PlanetX_AILens.letter_card(PlanetX_AILens.letterCards.A):
        mp3Player.set_tracking(10, mp3Player.repeatList.NO)
        RightWrong(Number2, "A")
    elif mode == 1 and PlanetX_AILens.letter_card(PlanetX_AILens.letterCards.B):
        mp3Player.set_tracking(11, mp3Player.repeatList.NO)
        RightWrong(Number2, "B")
    elif mode == 1 and PlanetX_AILens.letter_card(PlanetX_AILens.letterCards.C):
        mp3Player.set_tracking(12, mp3Player.repeatList.NO)
        RightWrong(Number2, "C")
    elif mode == 1 and PlanetX_AILens.letter_card(PlanetX_AILens.letterCards.D):
        mp3Player.set_tracking(13, mp3Player.repeatList.NO)
        RightWrong(Number2, "D")
    elif mode == 1 and PlanetX_AILens.letter_card(PlanetX_AILens.letterCards.E):
        mp3Player.set_tracking(6, mp3Player.repeatList.NO)
        mode = 0
        basic.show_leds("""
            . . # # #
            . . . # #
            . . . . #
            # # . . .
            # # . . .
            """)
    basic.pause(2500)
basic.forever(on_forever)

2025年4月20日 星期日

[micro:bit] 亮亮鼠-多工程式

 前一篇文章:亮亮鼠

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Imports go at the top
from microbit import *
mode = 0
value = 0

def my_sound_event():
    global mode
    if microphone.current_event() == SoundEvent.LOUD:
        mode+=1
        mode%=3

run_every(my_sound_event, ms=50)

# Code in a 'while True:' loop repeats forever
microphone.set_threshold(SoundEvent.LOUD, 80)
while True:
    display.show(mode+1)
    if button_a.was_pressed():
        mode+=1
        mode%=3
    if button_b.was_pressed():
        value = 1-value
    if mode == 0:
        pin0.write_digital(value)         
    if mode == 1:
        pin0.write_digital(value)    
        value = 1-value
    if mode == 2:
        if display.read_light_level()<70:
            pin0.write_digital(1)
        else:
            pin0.write_digital(0)
    sleep(500)  

2025年4月19日 星期六

[micro:bit]亮亮鼠





Python Editor:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Imports go at the top
from microbit import *
mode = 0
value = 0

# Code in a 'while True:' loop repeats forever
microphone.set_threshold(SoundEvent.LOUD, 100)
while True:
    display.show(mode+1)
    if button_a.was_pressed():
        mode+=1
        mode%=3
    if microphone.current_event() == SoundEvent.LOUD:
        mode+=1
        mode%=3
    if button_b.was_pressed():
        value = 1-value
    if mode == 0:
        pin0.write_digital(value)         
    if mode == 1:
        pin0.write_digital(value)    
        value = 1-value
        sleep(120)
    if mode == 2:
        if display.read_light_level()<70:
            pin0.write_digital(1)
        else:
            pin0.write_digital(0)
    sleep(120)

2025年4月8日 星期二

傾聽作品:拍掌牛擺頭外也能啟閉鳥叫聲

上一篇文章:彩虹鳥和行動牛



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def on_button_pressed_a():
    radio.send_string("action cow")
input.on_button_pressed(Button.A, on_button_pressed_a)

def on_button_pressed_b():
    radio.send_string("rainbow bird")
input.on_button_pressed(Button.B, on_button_pressed_b)

def on_sound_loud():
    global mode
    if listen == 1:
        mode = (mode + 1) % 2
        basic.show_icon(IconNames.HEART)
        servos.P1.set_angle(60)
        basic.pause(500)
        servos.P1.set_angle(120)
        basic.pause(500)
        servos.P1.set_angle(90)
        basic.show_icon(IconNames.ANGRY)
input.on_sound(DetectedSound.LOUD, on_sound_loud)

listen = 0
mode = 0
strip = neopixel.create(DigitalPin.P2, 4, NeoPixelMode.RGB)
strip.show_rainbow(1, 360)
strip.show()
servos.P1.set_angle(90)
mode = 0
radio.set_group(88)
basic.show_icon(IconNames.ANGRY)
listen = 1
mode = 0

def on_every_interval():
    if mode == 1:
        strip.rotate(1)
        strip.show()
loops.every_interval(500, on_every_interval)

def on_forever():
    global listen
    if mode == 1:
        listen = 0
        for index in range(randint(10, 200)):
            music.play_sound_effect(music.create_sound_effect(WaveShape.SAWTOOTH,
                    randint(1, 5000),
                    randint(1, 5000),
                    randint(0, 1024),
                    randint(0, 1024),
                    randint(40, 100),
                    SoundExpressionEffect.VIBRATO,
                    InterpolationCurve.CURVE),
                SoundExpressionPlayMode.UNTIL_DONE)
        basic.pause(600)
        listen = 1
        basic.pause(randint(1000, 10000))
basic.forever(on_forever)

2025年4月7日 星期一

傾聽作品:彩虹鳥和行動牛

 


MakeCode程式:


Python程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def on_button_pressed_a():
    radio.send_string("action cow")
input.on_button_pressed(Button.A, on_button_pressed_a)

def on_button_pressed_b():
    radio.send_string("rainbow bird")
input.on_button_pressed(Button.B, on_button_pressed_b)

def on_sound_loud():
    global mode
    mode = (mode + 1) % 2
    basic.show_icon(IconNames.HEART)
    servos.P1.set_angle(60)
    basic.pause(500)
    servos.P1.set_angle(120)
    basic.pause(500)
    servos.P1.set_angle(90)
    basic.show_icon(IconNames.ANGRY)
input.on_sound(DetectedSound.LOUD, on_sound_loud)

mode = 0
strip = neopixel.create(DigitalPin.P2, 4, NeoPixelMode.RGB)
strip.show_rainbow(1, 360)
strip.show()
servos.P1.set_angle(90)
mode = 0
radio.set_group(88)
basic.show_icon(IconNames.ANGRY)

def on_every_interval():
    if mode == 1:
        strip.rotate(1)
        strip.show()
loops.every_interval(500, on_every_interval)

def on_forever():
    for index in range(randint(10, 200)):
        music.play_sound_effect(music.create_sound_effect(WaveShape.SAWTOOTH,
                randint(1, 5000),
                randint(1, 5000),
                randint(0, 1024),
                randint(0, 1024),
                randint(40, 100),
                SoundExpressionEffect.VIBRATO,
                InterpolationCurve.CURVE),
            SoundExpressionPlayMode.UNTIL_DONE)
    basic.pause(randint(1000, 10000))
basic.forever(on_forever)


用micro:bit實作小鳥叫聲

參考資料:Jonny’s Bird

用隨機變數取替加速器資料。


Python程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def on_forever():
    for index in range(randint(10, 200)):
        music.play_sound_effect(music.create_sound_effect(WaveShape.SAWTOOTH,
                randint(1, 5000),
                randint(1, 5000),
                randint(0, 1024),
                randint(0, 1024),
                randint(40, 100),
                SoundExpressionEffect.VIBRATO,
                InterpolationCurve.CURVE),
            SoundExpressionPlayMode.UNTIL_DONE)
    basic.pause(randint(1000, 10000))
basic.forever(on_forever)


2025年1月1日 星期三

IoT MQTT Panel來察看micro:bit和電腦通訊情形


實作上圖的控制面板

前兩篇文章:micro:bit和電腦的串列通訊程式micro:bit和電腦的串列通訊程式加上MQTT

MQTT Broker:broker.MQTTGO.io

IoT MQTT Panel:AndriodiOS

IoT MQTT Panel的連線設定:

新增一個溫度面板:


三個按鈕面板:







micro:bit和電腦的串列通訊程式加上MQTT

 前一篇文章:micro:bit和電腦的串列通訊程式


電腦執行的Python程式:


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
import serial
import random
import paho.mqtt.client as mqtt
import time

# MQTT 設定
BROKER = "broker.mqttgo.io"
PORT = 1883
TOPIC_PUBLISH = "temperature"
TOPIC_SUBSCRIBE = "messages"
MQTT_CLIENT_ID = "microbit_client"
USERNAME = ""  # 如果需要帳號,填入使用者名稱
PASSWORD = ""  # 如果需要密碼,填入密碼
message = ""

def on_connect(client, userdata, flags, rc):
    print(f"MQTT 連線狀態: {rc}")
    if rc == 0:
        print("成功連線到 MQTT Broker")
        client.subscribe(TOPIC_SUBSCRIBE)
    else:
        print("無法連線到 MQTT Broker")

def on_message(client, userdata, msg):
    global message
    print(f"接收到來自 {msg.topic} 的訊息: {msg.payload.decode('utf-8')}")
    # 處理收到的訊息
    payload = msg.payload.decode('utf-8')
    if payload in ["heart", "OK", "Error"]:
        message = payload
        print(f"處理訂閱訊息: {payload}")
    else:
        print("收到未知訊息")

def main():
    # 配置串列埠參數
    global message
    port = 'COM4'  # 替換為您的串列埠名稱
    baudrate = 115200  # 串列埠速率

    # 初始化 MQTT 客戶端
    client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, MQTT_CLIENT_ID)
    client.username_pw_set(USERNAME, PASSWORD)
    client.on_connect = on_connect
    client.on_message = on_message

    # 嘗試連線到 MQTT Broker
    try:
        client.connect(BROKER, PORT, 60)
        client.loop_start()

        # 開啟串列埠
        ser = serial.Serial(port, baudrate, timeout=1)
        print(f"已開啟串列埠: {ser.port}, 波特率: {ser.baudrate}")

        buffer = ""  # 初始化資料緩衝區

        while True:
            # 處理串列埠的輸入
            if ser.in_waiting > 0:
                data = ser.read(ser.in_waiting).decode('latin-1', errors='ignore').strip()
                buffer += data
                print(f"目前緩衝區資料: {buffer}")

                while '|' in buffer:
                    line, buffer = buffer.split('|', 1)  # 提取一行資料
                    line = line.strip()
                    print(f"處理資料: {line}")

                    if line.startswith("T="):
                        try:
                            # 發佈溫度值到 MQTT Broker
                            temperature = int(line.split("=")[1])
                            print(f"當前溫度: {temperature} 度")
                            client.publish(TOPIC_PUBLISH, temperature)
                        except ValueError:
                            print("無法解析溫度值")

            # 模擬隨機傳送訊息給 micro:bit
            #message = random.choice(["heart", "OK", "Error"])
            ser.write((message + "\n").encode('utf-8'))
            print(f"已傳送: {message}")

            time.sleep(1)

    except serial.SerialException as e:
        print(f"串列埠錯誤: {e}")

    except KeyboardInterrupt:
        print("程序中止")

    finally:
        # 清理資源
        if 'ser' in locals() and ser.is_open:
            ser.close()
            print("串列埠已關閉")

        client.loop_stop()
        client.disconnect()
        print("已斷開 MQTT 連線")

if __name__ == "__main__":
    main()

執行結果:
目前緩衝區資料: T=2|
處理資料: T=2
當前溫度: 2 度
已傳送: OK
已傳送: OK
目前緩衝區資料: T=21|
處理資料: T=21
當前溫度: 21 度
已傳送: OK
目前緩衝區資料: T=21
已傳送: OK
目前緩衝區資料: T=21T=21|
處理資料: T=21T=21
無法解析溫度值
已傳送: OK
目前緩衝區資料: T=21|
處理資料: T=21
當前溫度: 21 度
已傳送: OK

連上MQTTGO的執行結果如最上圖

micro:bit和電腦的串列通訊程式


功能:把micro:bit的溫度值經由串列埠傳給電腦,電腦端隨機產生字串傳給micro:bit,改變micro:bit的圖案。

micro:bit 積木程式:



micro:bit端的Python程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
MyString = ""
serial.redirect(SerialPin.USB_TX, SerialPin.USB_RX, BaudRate.BAUD_RATE115200)

def on_forever():
    global MyString
    MyString = convert_to_text(input.temperature())
    serial.write_string("T=" + MyString + "|")
    MyString = convert_to_text(input.light_level())
    if MyString == "heart":
        basic.show_icon(IconNames.HEART)
    elif MyString == "OK":
        basic.show_icon(IconNames.YES)
    elif MyString == "Error":
        basic.show_icon(IconNames.NO)
    basic.pause(500)
basic.forever(on_forever)

電腦端:
先裝serial套件
pip install pyserial


注意,要觀察當micro:bit連線插到電腦USB埠時,會用那一個通訊埠來和電腦溝通。
Python程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import serial
import random


def main():
    # 配置串列埠參數
    port = 'COM4'  # 替換為您的串列埠名稱(例如:'/dev/ttyUSB0' 或 'COM3')
    baudrate = 115200  # 串列埠速率
    messages = ["heart", "OK", "Error"]

    try:
        # 開啟串列埠
        ser = serial.Serial(port, baudrate, timeout=1)
        print(f"已開啟串列埠: {ser.port}, 波特率: {ser.baudrate}")

        buffer = ""  # 初始化資料緩衝區

        while True:
            if ser.in_waiting > 0:
                # 嘗試用指定編碼解碼資料
                data = ser.read(ser.in_waiting).decode('latin-1', errors='ignore').strip()
                buffer += data  # 將新資料串接到緩衝區
                print(f"目前緩衝區資料: {buffer.strip()}")

                # 嘗試處理緩衝區中的每一行資料
                while '|' in buffer:
                    line, buffer = buffer.split('|', 1)  # 提取第一行,更新緩衝區
                    line = line.strip()  # 去除行首尾空白
                    print(f"處理資料: {line}")

                    # 檢查是否為溫度資料
                    if line.startswith("T="):
                        try:
                            # 提取溫度值
                            temperature = int(line.split("=")[1])
                            print(f"當前溫度: {temperature} 度")
                        except ValueError:
                            print("無法解析溫度值")

                            
                    # 偵測退出指令
                    if line.lower() == "exit":
                        print("收到 'exit',結束程序")
                        return
                message = random.choice(messages)
                ser.write((message + "\n").encode('utf-8'))
                print(f"已傳送: {message}")

    except serial.SerialException as e:
        print(f"串列埠錯誤: {e}")

    finally:
        # 關閉串列埠
        if 'ser' in locals() and ser.is_open:
            ser.close()
            print("串列埠已關閉")

if __name__ == "__main__":
    main()

執行結果:
目前緩衝區資料: T=21|
處理資料: T=21
當前溫度: 21 度
已傳送: Error
目前緩衝區資料: T=21|
處理資料: T=21
當前溫度: 21 度
已傳送: OK
目前緩衝區資料: T=21|
處理資料: T=21
當前溫度: 21 度
已傳送: heart


2024年12月4日 星期三

[樹藝:micro:bit] 時尚兔玩AI

 

主要材料:樹藝、micro:bit、Smart AI Lens

MakeCode程式碼:


Python程式:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def on_button_pressed_a():
    global ID
    ID = (ID + 1) % 6
    basic.show_string("" + str((ID)))
    if ID == 0:
        PlanetX_AILens.switchfunc(PlanetX_AILens.FuncList.CARD)
    else:
        PlanetX_AILens.switchfunc(PlanetX_AILens.FuncList.THINGS)
    basic.pause(3000)
input.on_button_pressed(Button.A, on_button_pressed_a)

def doLight():
    if RUN == 0 or (RUN == 5 or RUN == 11):
        pins.digital_write_pin(DigitalPin.P1, 1)
        pins.digital_write_pin(DigitalPin.P2, 0)
        pins.digital_write_pin(DigitalPin.P13, 0)
        pins.digital_write_pin(DigitalPin.P14, 0)
        pins.digital_write_pin(DigitalPin.P15, 0)
    elif RUN == 1 or (RUN == 6 or RUN == 12):
        pins.digital_write_pin(DigitalPin.P1, 0)
        pins.digital_write_pin(DigitalPin.P2, 1)
        pins.digital_write_pin(DigitalPin.P13, 0)
        pins.digital_write_pin(DigitalPin.P14, 0)
        pins.digital_write_pin(DigitalPin.P15, 0)
    elif RUN == 2 or (RUN == 7 or RUN == 13):
        pins.digital_write_pin(DigitalPin.P1, 0)
        pins.digital_write_pin(DigitalPin.P2, 0)
        pins.digital_write_pin(DigitalPin.P13, 1)
        pins.digital_write_pin(DigitalPin.P14, 0)
        pins.digital_write_pin(DigitalPin.P15, 0)
    elif RUN == 3 or (RUN == 8 or RUN == 14):
        pins.digital_write_pin(DigitalPin.P1, 0)
        pins.digital_write_pin(DigitalPin.P2, 0)
        pins.digital_write_pin(DigitalPin.P13, 0)
        pins.digital_write_pin(DigitalPin.P14, 1)
        pins.digital_write_pin(DigitalPin.P15, 0)
    elif RUN == 4 or (RUN == 9 or RUN == 15):
        pins.digital_write_pin(DigitalPin.P1, 0)
        pins.digital_write_pin(DigitalPin.P2, 0)
        pins.digital_write_pin(DigitalPin.P13, 0)
        pins.digital_write_pin(DigitalPin.P14, 0)
        pins.digital_write_pin(DigitalPin.P15, 1)
def checkCard():
    global RUN
    if PlanetX_AILens.number_card(PlanetX_AILens.numberCards.ZERO) and RUN != 0:
        RUN = 0
        radio.send_number(10)
        basic.show_number(0)
    elif PlanetX_AILens.number_card(PlanetX_AILens.numberCards.ONE) and RUN != 1:
        RUN = 1
        radio.send_number(1)
        basic.show_number(1)
    elif PlanetX_AILens.number_card(PlanetX_AILens.numberCards.TWO) and RUN != 2:
        RUN = 2
        radio.send_number(2)
        basic.show_number(2)
    elif PlanetX_AILens.number_card(PlanetX_AILens.numberCards.THREE) and RUN != 3:
        RUN = 3
        radio.send_number(3)
        basic.show_number(3)
    elif PlanetX_AILens.number_card(PlanetX_AILens.numberCards.FOUR) and RUN != 4:
        RUN = 4
        radio.send_number(9)
        basic.show_number(4)
    elif PlanetX_AILens.number_card(PlanetX_AILens.numberCards.FIVE) and RUN != 5:
        RUN = 5
        radio.send_number(5)
        basic.show_number(5)
    elif PlanetX_AILens.number_card(PlanetX_AILens.numberCards.SIX) and RUN != 6:
        RUN = 6
        radio.send_number(4)
        basic.show_number(6)
    elif PlanetX_AILens.number_card(PlanetX_AILens.numberCards.SEVEN) and RUN != 7:
        RUN = 7
        radio.send_number(8)
        basic.show_number(7)
    elif PlanetX_AILens.number_card(PlanetX_AILens.numberCards.EIGHT) and RUN != 8:
        RUN = 8
        radio.send_number(7)
        basic.show_number(8)
    elif PlanetX_AILens.number_card(PlanetX_AILens.numberCards.NINE) and RUN != 9:
        RUN = 9
        radio.send_number(6)
        basic.show_number(9)

def on_button_pressed_b():
    if ID == 1:
        PlanetX_AILens.learn_object(PlanetX_AILens.learnID.ID1)
    elif ID == 2:
        PlanetX_AILens.learn_object(PlanetX_AILens.learnID.ID2)
    elif ID == 3:
        PlanetX_AILens.learn_object(PlanetX_AILens.learnID.ID3)
    elif ID == 4:
        PlanetX_AILens.learn_object(PlanetX_AILens.learnID.ID4)
    elif ID == 5:
        PlanetX_AILens.learn_object(PlanetX_AILens.learnID.ID4)
    basic.pause(6000)
input.on_button_pressed(Button.B, on_button_pressed_b)

def checkLOGO():
    global RUN
    if PlanetX_AILens.object_check(PlanetX_AILens.learnID.ID1) and RUN != 11:
        RUN = 11
        basic.show_string("A")
        radio.send_number(16)
    elif PlanetX_AILens.object_check(PlanetX_AILens.learnID.ID2) and RUN != 12:
        RUN = 12
        basic.show_string("B")
        radio.send_number(17)
    elif PlanetX_AILens.object_check(PlanetX_AILens.learnID.ID3) and RUN != 13:
        RUN = 13
        basic.show_string("C")
        radio.send_number(18)
    elif PlanetX_AILens.object_check(PlanetX_AILens.learnID.ID4) and RUN != 14:
        RUN = 14
        basic.show_string("D")
        radio.send_number(19)
    elif PlanetX_AILens.object_check(PlanetX_AILens.learnID.ID5) and RUN != 15:
        RUN = 15
        basic.show_string("E")
        radio.send_number(20)
RUN = 0
ID = 0
basic.show_icon(IconNames.HEART)
PlanetX_AILens.init_module()
PlanetX_AILens.switchfunc(PlanetX_AILens.FuncList.CARD)
ID = 0
basic.show_leds("""
    . # . . #
    # . # . #
    # # # . #
    # . # . #
    # . # . #
    """)
RUN = 0
radio.set_group(49)
pins.digital_write_pin(DigitalPin.P1, 0)
pins.digital_write_pin(DigitalPin.P2, 0)
pins.digital_write_pin(DigitalPin.P13, 0)
pins.digital_write_pin(DigitalPin.P14, 0)
pins.digital_write_pin(DigitalPin.P15, 0)
Old_Run = 0
count = 12
LED_status = 0

def on_every_interval():
    global LED_status, count, Old_Run
    if Old_Run == RUN:
        if count > 10:
            if LED_status == 0:
                LED_status = 1
                pins.digital_write_pin(DigitalPin.P1, 1)
                pins.digital_write_pin(DigitalPin.P2, 1)
                pins.digital_write_pin(DigitalPin.P13, 1)
                pins.digital_write_pin(DigitalPin.P14, 1)
                pins.digital_write_pin(DigitalPin.P15, 1)
            else:
                LED_status = 0
                pins.digital_write_pin(DigitalPin.P1, 0)
                pins.digital_write_pin(DigitalPin.P2, 0)
                pins.digital_write_pin(DigitalPin.P13, 0)
                pins.digital_write_pin(DigitalPin.P14, 0)
                pins.digital_write_pin(DigitalPin.P15, 0)
        else:
            count = count + 1
    else:
        Old_Run = RUN
        count = 0
loops.every_interval(500, on_every_interval)

def on_forever():
    PlanetX_AILens.camera_image()
    if ID == 0:
        checkCard()
    else:
        checkLOGO()
    if count < 10:
        doLight()
    basic.pause(200)
    basic.show_leds("""
        . # . . #
        # . # . #
        # # # . #
        # . # . #
        # . # . #
        """)
basic.forever(on_forever)