方法二、ftp://210.70.242.16/
帳密stu,資料夾download>圖科-陳姿穎
方法一、https://drive.google.com/file/d/1Ow8QV3kjLDasvYSHdhYm7-RV3qC5rZnl/view?usp=sharing
方法二、ftp://210.70.242.16/
帳密stu,資料夾download>圖科-陳姿穎
Lab 01-亮滅與閃爍LED
from machine import Pin
import time
led = Pin(2, Pin.OUT)
led.value(0)
time.sleep(3)
led.value(1)
from machine import Pin
import time
led = Pin(2, Pin.OUT)
while True:
led.value(0)
time.sleep(0.5)
led.value(1)
time.sleep(0.5)
python -m pip install --upgrade pip
python -m pip install --upgrade esptool
Lab 02-SSD1306 OLED 0.96吋
2-1顯示文字
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
i2c = I2C(scl=Pin(5), sda=Pin(4))
oled = SSD1306_I2C(128, 64, i2c)
oled.text("I love PYTHON!", 0, 0)
oled.show()
2-2更新資料
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import utime
i2c = I2C(scl=Pin(5), sda=Pin(4))
oled = SSD1306_I2C(128, 64, i2c)
while True:
system_time = utime.ticks_ms()
oled.fill(0)
oled.text("System time: ", 0, 0)
oled.text(str(system_time), 0, 16)
oled.show()
utime.sleep_ms(100)
2-3心形與方框 (http://dotmatrixtool.com/#)
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import framebuf
oled = SSD1306_I2C(128, 64, I2C(scl=Pin(5), sda=Pin(4)))
pic_list = [0x1e, 0x3f, 0x7e, 0xfc, 0x7e, 0x3f, 0x1e, 0x00]
pic_buffer = bytearray(pic_list)
pic = framebuf.FrameBuffer(pic_buffer, 8, 8,
framebuf.MONO_VLSB)
oled.text("I", 8, 8)
oled.blit(pic, 20, 8)
oled.text("PYTHON", 32, 8)
oled.rect(4, 4, 80, 16, 1) # 畫方框
oled.show()
Lab 03-超音波模組
import machine, time
from machine import Pin
__version__ = '0.2.0'
__author__ = 'Roberto Sánchez'
__license__ = "Apache License 2.0. https://www.apache.org/licenses/LICENSE-2.0"
class HCSR04:
"""
Driver to use the untrasonic sensor HC-SR04.
The sensor range is between 2cm and 4m.
The timeouts received listening to echo pin are converted to OSError('Out of range')
"""
# echo_timeout_us is based in chip range limit (400cm)
def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500*2*30):
"""
trigger_pin: Output pin to send pulses
echo_pin: Readonly pin to measure the distance. The pin should be protected with 1k resistor
echo_timeout_us: Timeout in microseconds to listen to echo pin.
By default is based in sensor limit range (4m)
"""
self.echo_timeout_us = echo_timeout_us
# Init trigger pin (out)
self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)
self.trigger.value(0)
# Init echo pin (in)
self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)
def _send_pulse_and_wait(self):
"""
Send the pulse to trigger and listen on echo pin.
We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.
"""
self.trigger.value(0) # Stabilize the sensor
time.sleep_us(5)
self.trigger.value(1)
# Send a 10us pulse.
time.sleep_us(10)
self.trigger.value(0)
try:
pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us)
return pulse_time
except OSError as ex:
if ex.args[0] == 110: # 110 = ETIMEDOUT
raise OSError('Out of range')
raise ex
def distance_mm(self):
"""
Get the distance in milimeters without floating point operations.
"""
pulse_time = self._send_pulse_and_wait()
# To calculate the distance we get the pulse_time and divide it by 2
# (the pulse walk the distance twice) and by 29.1 becasue
# the sound speed on air (343.2 m/s), that It's equivalent to
# 0.34320 mm/us that is 1mm each 2.91us
# pulse_time // 2 // 2.91 -> pulse_time // 5.82 -> pulse_time * 100 // 582
mm = pulse_time * 100 // 582
return mm
def distance_cm(self):
"""
Get the distance in centimeters with floating point operations.
It returns a float
"""
pulse_time = self._send_pulse_and_wait()
# To calculate the distance we get the pulse_time and divide it by 2
# (the pulse walk the distance twice) and by 29.1 becasue
# the sound speed on air (343.2 m/s), that It's equivalent to
# 0.034320 cm/us that is 1cm each 29.1us
cms = (pulse_time / 2) / 29.1
return cms
3-1 讀取、顯示障礙物距離
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
from hcsr04 import HCSR04
import utime
oled = SSD1306_I2C(128, 64, I2C(scl=Pin(5), sda=Pin(4)))
sonar = HCSR04(trigger_pin=14, echo_pin=12)
while True:
distance = sonar.distance_cm()
oled.fill(0)
oled.text("Distance:", 0, 0)
oled.text(str(distance) + " cm", 0, 16)
oled.show()
print("偵測距離: " + str(distance) + " 公分")
utime.sleep_ms(25)
3-2防盜警報器
from machine import Pin, I2C, PWM
from ssd1306 import SSD1306_I2C
from hcsr04 import HCSR04
import utime
alarm_distance = 10 # 觸發警報距離
oled = SSD1306_I2C(128, 64, I2C(scl=Pin(5), sda=Pin(4)))
sonar = HCSR04(trigger_pin=14, echo_pin=12)
buzzer = PWM(Pin(15, Pin.OUT), freq=880, duty=0)
while True:
distance = sonar.distance_cm()
oled.fill(0)
oled.text("Distance:", 0, 0)
oled.text(str(distance) + " cm", 0, 16)
if 2 <= distance <= alarm_distance:
buzzer.duty(512)
oled.text("!!! ALARM !!!", 0, 40)
print("!!! 觸發警報 !!!")
else:
buzzer.duty(0)
print("無警報")
oled.show()
utime.sleep_ms(25)
3-3倒車雷達
from machine import Pin, I2C, PWM
from ssd1306 import SSD1306_I2C
from hcsr04 import HCSR04
import utime
oled = SSD1306_I2C(128, 64, I2C(scl=Pin(5), sda=Pin(4)))
sonar = HCSR04(trigger_pin=14, echo_pin=12)
buzzer = PWM(Pin(15, Pin.OUT), freq=784, duty=0)
sound_delay = 500
buzzer_time = utime.ticks_ms()
while True:
distance = sonar.distance_cm()
oled.fill(0)
oled.text("Distance:", 0, 0)
oled.text(str(distance) + " cm", 0, 16)
oled.show()
print("偵測距離: " + str(distance) + " 公分")
if 2 <= distance <= 50:
buzzer.duty(512)
utime.sleep_ms(10)
buzzer.duty(0)
sound_delay = int(distance) * 10 - 10
else:
sound_delay = 500
utime.sleep_ms(sound_delay)
3-4無弦空氣琴
from machine import Pin, I2C, PWM
from ssd1306 import SSD1306_I2C
from hcsr04 import HCSR04
import utime
note_min = 220 # 最小頻率(Hz)
note_max = 880 # 最大頻率(Hz)
dist_min = 40 # 測距最小距離(公厘)
dist_max = dist_min + (note_max - note_min) # 測距最大距離(公厘)
oled = SSD1306_I2C(128, 64, I2C(scl=Pin(5), sda=Pin(4)))
sonar = HCSR04(trigger_pin=14, echo_pin=12)
buzzer = PWM(Pin(15, Pin.OUT), freq=0, duty=0)
while True:
distance = sonar.distance_mm()
if dist_min <= distance <= dist_max:
key = note_min + (distance - dist_min)
buzzer.freq(key)
buzzer.duty(512)
else:
key = 0
buzzer.duty(0)
oled.fill(0)
oled.text("Dist: " + str(distance) + " mm", 0, 0)
oled.text("Note: " + str(key) + " Hz", 0, 16)
oled.show()
print("偵測距離: " + str(distance) + " 公厘, 播放頻率: " + str(key) + " 赫茲")
utime.sleep_ms(10)
Lab 04-亮度感測模組
bh1750fvi
# Copyright 2016 Peter Dahlberg
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
OP_SINGLE_HRES1 = 0x20
OP_SINGLE_HRES2 = 0x21
OP_SINGLE_LRES = 0x23
DELAY_HMODE = 180 # 180ms in H-mode
DELAY_LMODE = 24 # 24ms in L-mode
def sample(i2c, mode=OP_SINGLE_HRES1, i2c_addr=0x23):
"""
Performs a single sampling. returns the result in lux
"""
i2c.writeto(i2c_addr, b"\x00") # make sure device is in a clean state
i2c.writeto(i2c_addr, b"\x01") # power up
i2c.writeto(i2c_addr, bytes([mode])) # set measurement mode
time.sleep_ms(DELAY_LMODE if mode == OP_SINGLE_LRES else DELAY_HMODE)
raw = i2c.readfrom(i2c_addr, 2)
i2c.writeto(i2c_addr, b"\x00") # power down again
# we must divide the end result by 1.2 to get the lux
return ((raw[0] << 24) | (raw[1] << 16)) // 78642
4-1環境亮度監測
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import bh1750fvi, utime
i2c = I2C(scl=Pin(5), sda=Pin(4))
oled = SSD1306_I2C(128, 64, i2c)
while True:
light_level = bh1750fvi.sample(i2c, mode=0x23)
oled.fill(0)
oled.text("Light level:", 0, 0)
oled.text(str(light_level) + " lux", 0, 16)
oled.show()
print("偵測亮度: " + str(light_level) + " lux")
4-2照度不足提醒裝置
from machine import Pin, PWM, I2C
from ssd1306 import SSD1306_I2C
import bh1750fvi, utime
i2c = I2C(scl=Pin(5), sda=Pin(4))
oled = SSD1306_I2C(128, 64, i2c)
buzzer = PWM(Pin(15, Pin.OUT), freq=110, duty=0)
while True:
light_level = bh1750fvi.sample(i2c, mode=0x23)
print("偵測亮度: " + str(light_level) + " lux")
oled.fill(0)
oled.text("Light level:", 0, 0)
oled.text(str(light_level) + " lux", 0, 16)
if 20 < light_level < 300:
oled.text("!! Warning !!", 0, 32)
oled.text("TOO DARK", 0, 48)
print("警告 !! 亮度不足 !!")
buzzer.freq(110)
buzzer.duty(512)
else:
buzzer.duty(0)
oled.show()
Lab 05-RGBLED
5-1隨機炫彩燈
from machine import Pin
import utime, urandom
r = Pin(14, Pin.OUT)
g = Pin(12, Pin.OUT)
b = Pin(13, Pin.OUT)
while True:
r.value(urandom.getrandbits(1))
g.value(urandom.getrandbits(1))
b.value(1 if r.value() == 0 and g.value() == 0 else urandom.getrandbits(1))
"""
if r.value() == 0 and g.value() == 0:
b.value(1)
else:
b.value(urandom.getrandbits(1))
"""
utime.sleep_ms(500)
5-2七彩呼吸燈
from machine import Pin, PWM
import utime, urandom
while True:
#隨機指定每個燈號是否要亮起
r_switch = urandom.getrandbits(1)
g_switch = urandom.getrandbits(1)
b_switch = 1 if r_switch == 0 and g_switch == 0 else urandom.getrandbits(1)
#指定的燈號要亮起時再建立該 PWM 物件
if r_switch == 1:
r = PWM(Pin(14, Pin.OUT), freq=1000, duty=0)
if g_switch == 1:
g = PWM(Pin(12, Pin.OUT), freq=1000, duty=0)
if b_switch == 1:
b = PWM(Pin(13, Pin.OUT), freq=1000, duty=0)
for i in range(1024):
if r_switch == 1:
r.duty(i)
if g_switch == 1:
g.duty(i)
if b_switch == 1:
b.duty(i)
utime.sleep_ms(1)
for i in reversed(range(1024)):
if r_switch == 1:
r.duty(i)
if g_switch == 1:
g.duty(i)
if b_switch == 1:
b.duty(i)
utime.sleep_ms(1)
#每次燈滅掉後都關閉所有的 PWM 物件
if r_switch == 1:
r.deinit()
if g_switch == 1:
g.deinit()
if b_switch == 1:
b.deinit()
思考
以下是放在「while True:」之下,可以亮紅燈,並50%亮度:
r_pwm.duty(512)
g_pwm.duty(0)
b_pwm.duty(0)
utime.sleep_ms(1000) # 延遲1秒
r_pwm.duty(0) # 關閉紅燈
若要調整亮度,放PWM控制亮度,還要定義:
r_pwm = PWM(r_pin)
並改寫:
from machine import Pin, PWM
5-3不同亮度六彩燈
from machine import Pin, PWM
import utime
# 定義RGB LED
r_pin = Pin(14, Pin.OUT)
g_pin = Pin(12, Pin.OUT)
b_pin = Pin(13, Pin.OUT)
# 建立PWM,控制亮度
r_pwm = PWM(r_pin)
g_pwm = PWM(g_pin)
b_pwm = PWM(b_pin)
# 定義顏色的RGB值
colors = [
(255, 0, 0), # 紅色
(255, 165, 0), # 橙色
(255, 255, 0), # 黃色
(0, 255, 0), # 綠色
(0, 0, 255), # 藍色
(128, 0, 128) # 紫色
]
# 定義不同亮度
brightness_levels = [1.0, 0.5, 0.25]
while True:
for color in colors:
for brightness in brightness_levels:
r_pwm.duty(int(color[0] * brightness))
g_pwm.duty(int(color[1] * brightness))
b_pwm.duty(int(color[2] * brightness))
utime.sleep_ms(1000) # 顯示1秒
r_pwm.duty(0) # 關閉紅燈
g_pwm.duty(0) # 關閉綠燈
b_pwm.duty(0) # 關閉藍燈
5-4智慧小夜燈
from machine import Pin, I2C, PWM
from hcsr04 import HCSR04
import bh1750fvi, utime
sonar = HCSR04(trigger_pin=0, echo_pin=16)
r = PWM(Pin(14, Pin.OUT), freq=1000, duty=0)
g = PWM(Pin(12, Pin.OUT), freq=1000, duty=0)
b = PWM(Pin(13, Pin.OUT), freq=1000, duty=0)
while True:
distance = sonar.distance_cm()
light_level = bh1750fvi.sample(I2C(scl=Pin(5), sda=Pin(4)), mode=0x23)
if 2 <= distance <= 30:
led_light_value = 1023
else:
if light_level > 256:
light_level = 256
led_light_value = (256 - light_level) * 4 - 1
r.duty(led_light_value)
g.duty(led_light_value)
b.duty(led_light_value)
utime.sleep_ms(50)