2024年2月11日 星期日

建立Django 5.0的專案以及app

參考資料:Python架站特訓班Django 3最強實戰,碁峰。

 

1.打開cmd,輸入mkvirtualenv django_first命令建立虛擬環境。


2.輸入pip install django建立Django套件。


3.使用pip list命令檢查Django版本。


4.輸入django-admin startproject firstproject來建立Djano專案,利用cd firstproject來切換目錄,再利用dir來查看目錄中的檔案。


5.輸入Python manage.py startapp myapp來建立應用程式,利用md static來建立static目錄。


6.輸入python manage.py migrate指令進行模型(Model)與資料庫(Database)的同步。


7.輸入python manage.py runserver指令來啟動Server。


8.打開瀏覽器,輸入http://127.0.0.1:8000/網址,開啟首頁。


9.環境設定,設定settings.py,firstproject\settings.py。

  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
"""
Django settings for firstproject project.

Generated by 'django-admin startproject' using Django 5.0.2.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-+f^d-9+pr$ii+cb4aqa4out6pgey@#y-r9k*vva=x#s&dhf4nj'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['127.0.0.1']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'firstproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR/'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'firstproject.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'zh-hant'

TIME_ZONE = 'Asia/Taipei'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR/'static',
    ]

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

重新整理


10.設定URL,firstproject\urls.py。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""
URL configuration for firstproject project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myapp.views import sayhello

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', sayhello),
]

11.定義函式myapp\views.py。

1
2
3
4
5
6
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def sayhello(request):
    return HttpResponse("Hello Django")

重新整理


12.利用網址傳送參數
12.1 新增sayhello2,firstproject\ulrs.py
 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
"""
URL configuration for firstproject project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myapp.views import sayhello, sayhello2

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', sayhello),
    path('hello2/<str:username>', sayhello2),
]

12.2定義sayhello2函式,修改myapp\views.py。

1
2
3
4
5
6
7
8
9
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def sayhello(request):
    return HttpResponse("Hello Django")
    
def sayhello2(request, username):
    return HttpResponse("Hello " + username)

執行結果:
13.模版的使用
13.1 建立templates目錄,並新增templates\hello3.html檔案
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!DOCTYPE html>
<html>
<head>
	<meta charset='utf-8'>
	<title>雲林虎尾</title>
</head>
<body>
	<h1> 歡迎光臨:{{username}} </h1>
	<h2> 現在時間:{{now}} </h2>
</body>
</html>

13.2 設定firstproject\urls.py。

 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
"""
URL configuration for firstproject project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myapp.views import sayhello, sayhello2, sayhello3

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', sayhello),
    path('hello2/<str:username>', sayhello2),
    path('hello3/<str:username>', sayhello3),    
]

13.3 設定視圖函式myapp\views.py。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django.shortcuts import render
from django.http import HttpResponse
from datetime import datetime

# Create your views here.
def sayhello(request):
    return HttpResponse("Hello Django")
    
def sayhello2(request, username):
    return HttpResponse("Hello " + username)

def sayhello3(request, username):
    now = datetime.now()
    return render(request, "hello3.html", locals())

13.4 在瀏覽器上輸入127.0.0.1:8000/hello3/虎尾鎮。

14.加入static靜態檔案
14.1 加入hello4鏈結,firstproject\urls.py

 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
"""
URL configuration for firstproject project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myapp.views import sayhello, sayhello2, sayhello3, sayhello4

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', sayhello),
    path('hello2/<str:username>', sayhello2),
    path('hello3/<str:username>', sayhello3),  
    path('hello4/<str:username>', sayhello4),      
]

14.2 修改視圖myapp\views.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django.shortcuts import render
from django.http import HttpResponse
from datetime import datetime

# Create your views here.
def sayhello(request):
    return HttpResponse("Hello Django")
    
def sayhello2(request, username):
    return HttpResponse("Hello " + username)

def sayhello3(request, username):
    now = datetime.now()
    return render(request, "hello3.html", locals())
    
def sayhello4(request, username):
    now = datetime.now()
    return render(request, "hello4.html", locals())

14.3 修改様版templates\hello4.html。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
	<meta charset = 'utf-8'>
	<title>雲林虎尾</title>
	{% load static %}
	<link rel="stylesheet" href="{% static "css/style.css" %}">
</head>
<body>
	<div id="home">
		<img src="{% static "images/ball.png" %}" alt="歡迎光臨" width="32" height="32"/>
		<span class="info"> 歡迎光臨:{{username}} </span>
		<h2> 現在時間:{{now}} </h2>
	</div>
</body>
</html>

14.3 新增css,static/css/style.css。
1
2
3
4
.info {
	color:red;
	font-size: 1.5em;
}

執行結果:


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)