完成 camera 模組的初始化與擷取函式測試後, 接下來就可以來做一些應用實驗了, 本篇要做的測試是每當按下按鈕時就擷取鏡頭影像並存檔 (即按鈕拍照).
本系列之前的文章參考 :
首先準備一個按鈕, 它的短邊 (距離較短) 接點平時是 OFF 不相接, 按下時 ON 相接, 將其一端接 ESP32 的 GND, 另一端接一個 GPIO 腳, 例如 GPIO13, 在程式中設定其為輸入腳並開啟此上拉電阻, 這樣當按鈕未按下時輸入為 HIGH, 按下時為 LOW.
程式碼如下 :
# push_shot_1.py
import time, camera
from machine import reset, Pin
def init_camera(**config): # 初始化鏡頭
config.setdefault('fb_location', camera.PSRAM)
config.setdefault('format', camera.JPEG)
config.setdefault('xclk_freq', camera.XCLK_10MHz)
config.setdefault('framesize', camera.FRAME_QVGA)
camera.init(
0, d0=4, d1=5, d2=18, d3=19, d4=36, d5=39, d6=34, d7=35,
href=23, vsync=25, reset=-1, sioc=27, siod=26, xclk=21,
pclk=22, **config)
def capture_image(file_name='capture.jpg'): # 拍攝照片並存檔
time.sleep(2) # 等待攝像頭穩定
buf=camera.capture()
if buf:
with open(f'/{file_name}', 'wb') as f:
f.write(buf)
print(f'Image has been saved as {file_name}')
else:
print('Failed to capture image')
camera.deinit()
del buf
button=Pin(13, Pin.IN, Pin.PULL_UP)
file_counter=1 # 檔案計數器
try:
while True:
if button.value() == 0: # 按鈕被按下
file_name=f'capture{file_counter:02d}.jpg' # 格式化檔名
print(f'Button pressed! Capturing image as {file_name}...')
init_camera() # 初始化鏡頭
capture_image(file_name) # 擷取影像
file_counter += 1 # 更新檔案編號
time.sleep(1) # 避免按鈕抖動影響
except KeyboardInterrupt:
print("Program stopped.")
此程式使用 polling 法以無窮迴圈偵測鈕是否欸按下, 是的話就先初始化鏡頭後拍照存檔, 下面是執行後連按 5 次的輸出 :
Button pressed! Capturing image as capture01.jpg...
0
4
10000000
5
True
10132
Image has been saved as capture01.jpg
True
Button pressed! Capturing image as capture02.jpg...
0
4
10000000
5
True
9959
Image has been saved as capture02.jpg
True
Button pressed! Capturing image as capture03.jpg...
0
4
10000000
5
True
9948
Image has been saved as capture03.jpg
True
Button pressed! Capturing image as capture04.jpg...
0
4
10000000
5
True
9898
Image has been saved as capture04.jpg
True
Button pressed! Capturing image as capture05.jpg...
0
4
10000000
5
True
cam_hal: EV-EOF-OVF
cam_hal: EV-VSYNC-OVF
9974
Image has been saved as capture05.jpg
True
開發板上的檔案列表顯示有 5 個 jpeg 檔 :
這五張 jpeg 都是如下相同的圖 :
其實就是我的電腦桌啦.
沒有留言:
張貼留言