2024年4月7日 星期日

micro:bit OLED1306 製作螢幕畫面

 電子元件有micro:bit主板、iot:bit底板、以及SSD OLED1306

OLED驅動程式:fizban99/microbit_ssd1306

程式編輯工具:micro:bit Python Editor

程式檔案管理:除了main.py外,其餘檔案來自OLED驅動程式

1.利用小畫家以128*64來設計畫面


2.改寫OLED驅動程式microbit_ssd1306/sample_images/bitmapconverter.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
import struct
from PIL import Image
filename = 'treeart'

pic = [0x00 for _ in range(128*64)]

bmp_image = Image.open( filename+'.bmp' )

index=0
for i_horizon  in range(bmp_image.width):
    for i_vertical in range(bmp_image.height//8):
        b=0x0
        for i in range(0, 8):
            b>>=1
            if bmp_image.getpixel((i_horizon, i_vertical*8+i)) == 255:
                b |= 0x80
        pic[i_horizon+i_vertical*bmp_image.width]=b
        index+=1

newFileByteArray = bytearray(pic)
with open(filename, 'wb') as newFile:
    newFile.write(newFileByteArray)

print("Done")

3.把相關檔案載入


4.利用步驟2的程式進行轉碼,再撰寫micro:bit Python程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from ssd1306 import initialize, clear_oled
from ssd1306_bitmap import show_bitmap
from microbit import *

initialize()
clear_oled()
while True:
    show_bitmap('microbit_logo')
    display.scroll('Welcome to ')
    show_bitmap('craft_center')
    display.scroll('National Taiwan Craft Research and Development')
    show_bitmap('nfu')
    display.scroll('National Formosa University')   
    show_bitmap('treeart')
    display.scroll('Workshop of Tree Art')  
    show_bitmap('steam')
    display.scroll('OUTSTEAM International')  
    show_bitmap('smartcreating')
    display.scroll('SmartCreating Co., Ltd.')  
    show_bitmap('goods')
    display.scroll('Taiwan Rural Goods Promotion Alliance') 

5.下載到micro:bit後,執行。


2024年4月6日 星期六

micro:bit OLED初接觸

電子元件有micro:bit主板、iot:bit底板、以及SSD OLED1306

OLED驅動程式:fizban99/microbit_ssd1306

程式編輯工具:micro:bit Python Editor

程式檔案管理:除了main.py外,其餘檔案來自OLED驅動程式


Python程式碼:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from ssd1306 import initialize, clear_oled
from ssd1306_text import add_text
from ssd1306_bitmap import show_bitmap
from microbit import *

initialize()
clear_oled()
show_bitmap('microbit_logo')
sleep(2000)
clear_oled()
add_text(0, 0, 'TreeArt:bit')
i=0
while True:
    add_text(0, 2, str(i))
    sleep(1000)
    i=i+1

執行結果:




2024年4月5日 星期五

用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
class Count:
    def __init__(self, str):
        self.words = 0
        self.halfwords = 0
        self.fullwords = 0
        self.charactersWithSpace = len(str)
        self.charactersWithoutSpace = len(str)
        contineflag = 0
        for c in str:
            if c == ' ':
                self.charactersWithoutSpace-=1
                contineflag = 0
            if '\u4e00' <= c <= '\u9fef':
                self.words+=1
                self.fullwords+=1
                contineflag = 0
            else:
                if contineflag == 0:
                    self.halfwords+=1
                    self.words+=1
                    contineflag = 1
                    
        
str = input("請輸入文字含中英文:")
cnt = Count(str)
print("字元數含空白", cnt.charactersWithSpace)
print("字元數不含空白", cnt.charactersWithoutSpace)
print("字數", cnt.words)
print("半型字數", cnt.halfwords)
print("全型字數", cnt.fullwords)

執行結果1:
請輸入文字含中英文:Hello World
字元數含空白 11
字元數不含空白 10
字數 2
半型字數 2
全型字數 0

執行結果2:
請輸入文字含中英文:國立虎尾科技大學
字元數含空白 8
字元數不含空白 8
字數 8
半型字數 0
全型字數 8

執行結果3:
請輸入文字含中英文:1a一2b Hello Word
字元數含空白 16
字元數不含空白 14
字數 5
半型字數 4
全型字數 1

檔案的簡易操作

 1.寫中文資料到檔案

1
2
3
4
fp=open("test.txt", "w", encoding = "UTF-8")
fp.write("好吃芋頭在雲林縣林內鄉烏塗村\n")
fp.write("好吃花生在雲林縣元長鄉和虎尾鎮")
fp.close()

2.讀取資料
1
2
3
4
5
fp=open("test.txt", "r", encoding = "UTF-8")
lines=fp.readlines()
for line in lines:
    print(line)
fp.close()

執行結果:
好吃芋頭在雲林縣林內鄉烏塗村

好吃花生在雲林縣元長鄉和虎尾鎮

3.檔案已有換行字元'\n',輸出可以不用換行
1
2
3
4
5
fp=open("test.txt", "r", encoding = "UTF-8")
lines=fp.readlines()
for line in lines:
    print(line, end="")
fp.close()

執行結果:
好吃芋頭在雲林縣林內鄉烏塗村
好吃花生在雲林縣元長鄉和虎尾鎮

4.使用with/as來讀取檔案內容
1
2
3
4
5
with open("test.txt", "r", encoding = "UTF-8") as fp:
    lines=fp.readlines()
    for line in lines:
        print(line, end="")
    fp.close()

執行結果:
好吃芋頭在雲林縣林內鄉烏塗村
好吃花生在雲林縣元長鄉和虎尾鎮

1
2
3
4
5
6
7
8
with open("test.txt", "r", encoding = "UTF-8") as fp:
    lines = fp.read().split("\n")
    line_cnt = len(lines)
    word_cnt = char_cnt = 0
    for line in lines:
        words = line.split()
        word_cnt, char_cnt = word_cnt + len(words), char_cnt + len(line)
    print("File {0} has {1} lines, {2} words, {3} characters".format("test.txt", line_cnt, word_cnt, char_cnt))

執行結果:
File test.txt has 2 lines, 2 words, 29 characters

眼尖的朋友是否覺得有問題呢?
中文字數不能用split()來計算,29字元數就是中文字數。



用Python求最大公因收和最小公倍數

 

1.找因數

1
2
3
4
5
6
a=int(input('請輸入大於零的整數:'))
if(a>0):
    for i in range(1,a+1):
        if(a%i==0):
            print(i,end=" ")
    print("")

執行結果:
請輸入大於零的整數:12
1 2 3 4 6 12 

2.利用集合生成式找因數

1
2
3
a=int(input('請輸入大於零的整數:'))
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
print(a_set)

執行結果:
請輸入大於零的整數:9
{1, 3, 9}

3.找出兩數的公因數

1
2
3
4
5
a=int(input('請輸入大於零的整數A:'))
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
b=int(input('請輸入大於的整數B:'))
b_set={n for n in range(1,b+1) if b>0 and b%n==0}
print(a_set & b_set)

執行結果:
請輸入大於零的整數A:12
請輸入大於的零整數B:9
{1, 3}

4.找出兩數的最大公因數

1
2
3
4
5
a=int(input('請輸入大於零的整數A:'))
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
b=int(input('請輸入大於的整數B:'))
b_set={n for n in range(1,b+1) if b>0 and b%n==0}
print(max(a_set & b_set))

執行結果:
請輸入大於零的整數A:12
請輸入大於零的整數B:9
3

5.找出兩數的最小公倍數

1
2
3
4
5
a=int(input('請輸入大於零的整數A:'))
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
b=int(input('請輸入大於的整數B:'))
b_set={n for n in range(1,b+1) if b>0 and b%n==0}
print(a*b//max(a_set & b_set))

執行結果:
請輸入大於零的整數A:12
請輸入大於零的整數B:9
36

6.一次輸入兩個數,找出兩數的最小公倍數

1
2
3
4
5
a,b=int(input('請輸入大於的整數(A, B):'))
print(a,b)
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
b_set={n for n in range(1,b+1) if b>0 and b%n==0}
print(a*b//max(a_set & b_set))

執行結果:
請輸入大於零的整數(A, B):9, 12
Traceback (most recent call last):
  File "C:/Users/cheng-min/AppData/Local/Programs/Python/Python311/test.py", line 1, in <module>
    a,b=int(input('請輸入大於零的整數(A, B):'))
ValueError: invalid literal for int() with base 10: '9, 12'

將int()改成eval()函式:

1
2
3
4
5
a,b=eval(input('請輸入大於零的整數(A, B):'))
print(a,b)
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
b_set={n for n in range(1,b+1) if b>0 and b%n==0}
print(a*b//max(a_set & b_set))

執行結果:
請輸入大於零的整數(A, B):9, 12
9 12
36

7.用自定函式來求最大公因收和最小公倍數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def gcd(a, b):
    if b==0:
        return a
    else:
        return gcd(b, a%b)

def lcm(a, b):
    return a*b//gcd(a, b)


a,b=eval(input('請輸入大於零的整數(A, B):'))
print("gcd(",a,",",b,")=", gcd(a,b))
print("lcm(",a,",",b,")=", lcm(a,b))

執行結果:
請輸入大於零的整數(A, B):9, 12
gcd( 9 , 12 )= 3
lcm( 9 , 12 )= 36

8.利用math套件求最大公因收和最小公倍數

1
2
3
4
import math
a,b=eval(input('請輸入大於零的整數(A, B):'))
print("gcd(",a,",",b,")=", math.gcd(a,b))
print("lcm(",a,",",b,")=", math.lcm(a,b))

執行結果:
請輸入大於零的整數(A, B):9,12
gcd( 9 , 12 )= 3
lcm( 9 , 12 )= 36

9.利用sympy套件求最大公因收和最小公倍數

1
2
3
4
from sympy import *
a,b=eval(input('請輸入大於的整數(A, B):'))
print("gcd(",a,",",b,")=", gcd(a,b))
print("lcm(",a,",",b,")=", lcm(a,b))

執行結果:
Traceback (most recent call last):
  File "C:/Users/cheng-min/AppData/Local/Programs/Python/Python311/test.py", line 1, in <module>
    from sympy import *
ModuleNotFoundError: No module named 'sympy'

安裝sympy套件

執行結果:
請輸入大於零的整數(A, B):9, 12
gcd( 9 , 12 )= 3
lcm( 9 , 12 )= 36

10.改用import寫法

1
2
3
4
import sympy
a,b=eval(input('請輸入大於零的整數(A, B):'))
print("gcd(",a,",",b,")=", gcd(a,b))
print("lcm(",a,",",b,")=", lcm(a,b))

執行結果:
Traceback (most recent call last):
  File "C:/Users/cheng-min/AppData/Local/Programs/Python/Python311/test.py", line 3, in <module>
    print("gcd(",a,",",b,")=", gcd(a,b))
NameError: name 'gcd' is not defined

修改程式:

1
2
3
4
import sympy
a,b=eval(input('請輸入大於零的整數(A, B):'))
print("gcd(",a,",",b,")=", sympy.gcd(a,b))
print("lcm(",a,",",b,")=", sympy.lcm(a,b))

執行結果:
請輸入大於零的整數(A, B):9,12
gcd( 9 , 12 )= 3
lcm( 9 , 12 )= 36

為什麼要介紹sympy套件,不妨可以參考夠Python,一行指令找質數

2024年4月2日 星期二

在pythonanywhere設計Django網站的卡片(Card)功能(新增資料庫)

延續文章:在pythonanywhere設計Django網站的卡片(Card)功能(新增For Template)

1.定義資料庫

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from django.db import models

# Create your models here.

class vegetableDB(models.Model):
    image = models.CharField(max_length = 20, null = False)
    title = models.CharField(max_length = 20, blank = True, default='')
    subtitle = models.CharField(max_length = 20, blank = True, default='')

    def __str__(self):
        return self.image

2.修改mysite/myapp/views.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.shortcuts import render
from myapp.models import vegetableDB

# Create your views here.
def index(request):
    slide1 = {'image':'fruits01.jpg', 'active':'active', 'interval':'10000', 'title':'水果01', 'subtitle':'好水果在雲林'}
    slide2 = {'image':'fruits02.jpg', 'active':'', 'interval':'2000', 'title':'水果02', 'subtitle':'好水果在雲林'}
    slide3 = {'image':'fruits03.jpg', 'active':'', 'interval':'3000', 'title':'水果03', 'subtitle':'好水果在雲林'}
    slides = [slide1, slide2, slide3]
    return render(request, 'index.html', locals())

def vegetable(request):
    vegetables = vegetableDB.objects.all().order_by('id')
    return render(request, 'vegetable.html', locals())

def fruit(request):
    return render(request, 'fruit.html', locals())

3.重新Reload並執行,但發生錯誤,是因為沒有資料庫

4. 開啟Bash,下達 python manage.py makemigrations


5.修改mysite/mysite/settings.py,把static拿掉。

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

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.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/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-8c5r7ez2#g2j5n@yxeczdyhw6-zwgj_l64=nark$wc_mn+kf*4'

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

ALLOWED_HOSTS = ['cmlin.pythonanywhere.com']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap5',
    '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 = 'mysite.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 = 'mysite.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/4.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/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = 'static/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# default static files settings for PythonAnywhere.
# see https://help.pythonanywhere.com/pages/DjangoStaticFiles for more info
MEDIA_ROOT = '/home/cmlin/mysite/media'
MEDIA_URL = '/media/'
STATIC_ROOT = '/home/cmlin/mysite'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR/'static',
    ]

6.下達下列2個指令,順利完成資料庫的同步作業
python manage.py makemigrations
python manage.py migrate


7.執行後發現蔬菜內的照片全部不見,這是因為資料庫內沒有任何資料。

8.建立超級使用者
python manage.py createsuperuser

9.登入後台
cmlin.pythonanywhere.com/admin

在下圖依然沒有看到資vegetableDB資料

10.為資料庫設定管理者,修改mysite/myapp/admin.py

1
2
3
4
5
6
7
8
9
from django.contrib import admin
from myapp.models import vegetableDB

# Register your models here.

class vegetableAdmin(admin.ModelAdmin):
    list_display=('id', 'image', 'title', 'subtitle')

admin.site.register(vegetableDB, vegetableAdmin)

11.在後台新增一筆資料

12.重新載入




2024年4月1日 星期一

在pythonanywhere設計Django網站的卡片(Card)功能(新增For Template)

延續文章: 在pythonanywhere設計Django網站的卡片(Card)功能


1.修改mysite/templates/vegetable.html的程式

 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
<!DOCTYPE html>
<html>
<head>
  {% load bootstrap5 %}
  {% bootstrap_css %}
  {% bootstrap_javascript %}
  {% load static %}
</head>
<body>
<div class="container">
  <ul class="nav bg-info">
    <li class="nav-item">
      <a class="nav-link link-light" href="/">首頁</a>
    </li>
    <li class="nav-item">
      <a class="nav-link link-light" href="/vegetable/">蔬菜</a>
    </li>
    <li class="nav-item">
      <a class="nav-link link-light" href="/fruit/">水果</a>
    </li>
  </ul>

<h1>蔬菜</h1>
<div class="row">
    {% for vegetable in vegetables %}
        <div class="card" style="width:300px">
            <img class="card-img-top" src="{% static "images/" %}{{ vegetable.image }}" alt="Card image">
            <div class="card-img-overlay">
                <h4 class="card-title" style="color:white;">{{ vegetable.title }}</h4>
                <p class="card-text" style="color:white;">{{ vegetable.subtitle }}</p>
                <a href="#" class="btn btn-primary">說明</a>
            </div>
        </div>
    {% endfor %}
</div>
  {% block content %}
  {% endblock %}
</div>
</body>
</html>

2.修改mysite/myapp/views.py的程式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django.shortcuts import render

# Create your views here.
def index(request):
    slide1 = {'image':'fruits01.jpg', 'active':'active', 'interval':'10000', 'title':'水果01', 'subtitle':'好水果在雲林'}
    slide2 = {'image':'fruits02.jpg', 'active':'', 'interval':'2000', 'title':'水果02', 'subtitle':'好水果在雲林'}
    slide3 = {'image':'fruits03.jpg', 'active':'', 'interval':'3000', 'title':'水果03', 'subtitle':'好水果在雲林'}
    slides = [slide1, slide2, slide3]
    return render(request, 'index.html', locals())

def vegetable(request):
    vegetable1 = {'image':'vegetable01.jpg','title':'蔬菜01', 'subtitle':'好蔬菜在雲林'}
    vegetable2 = {'image':'vegetable02.jpg','title':'蔬菜02', 'subtitle':'好蔬菜在雲林'}
    vegetable3 = {'image':'vegetable03.jpg','title':'蔬菜03', 'subtitle':'好蔬菜在雲林'}
    vegetable4 = {'image':'vegetable04.jpg','title':'蔬菜04', 'subtitle':'好蔬菜在雲林'}
    vegetables = [vegetable1, vegetable2, vegetable3, vegetable4]
    return render(request, 'vegetable.html', locals())

def fruit(request):
    return render(request, 'fruit.html', locals())