使用1。21-2023-10-13
micropython_v1.21.0_2023_10_13_camera_no_ble.bin
import machine
import network
import socket
import camera
import time
# Wi-Fi 配置
SSID = 'Bili-Net'
PASSWORD = '0932388283'
# 初始化相機
def init_camera():
camera.init(0, format=camera.JPEG) # 確保格式設為JPEG
camera.framesize(camera.FRAME_VGA) # VGA分辨率 640x480
camera.quality(10) # JPEG品質設為10
print("相機初始化成功!")
# 連接到Wi-Fi
def connect_to_wifi():
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(SSID, PASSWORD)
while not station.isconnected():
pass
print('Connected to Wi-Fi.')
print('Network config:', station.ifconfig())
return station
# 定義Web Server
def web_server(station):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
print('Web server running on http://{}'.format(station.ifconfig()[0]))
while True:
conn, addr = s.accept()
try:
print('Got a connection from %s' % str(addr))
request = conn.recv(1024)
print('Request:', request)
request = str(request)
if '/capture' in request:
print("Capturing image...")
photo = camera.capture()
if photo:
print("Sending image...")
conn.sendall(b'HTTP/1.1 200 OK\r\n')
conn.sendall(b'Content-Type: image/jpeg\r\n')
conn.sendall(b'Connection: close\r\n\r\n')
conn.sendall(photo)
else:
print("Failed to capture image")
conn.sendall(b'HTTP/1.1 404 Not Found\r\n')
conn.sendall(b'Connection: close\r\n\r\n')
else:
html = """<!DOCTYPE html>
<html>
<head>
<title>ESP32-CAM</title>
<style>
body, html {
height: 100%;
margin: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #f0f0f0;
}
#header {
font-size: 24px;
color: #333;
padding: 10px;
text-align: center;
}
#image-container {
width: 640px;
height: 480px;
display: flex;
justify-content: center;
align-items: center;
background: #fff;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
img {
width: 100%;
height: auto; /* maintain aspect ratio */
max-height: 100%; /* limit height to container */
}
</style>
</head>
<body>
<div id="header">ESP32 即時相機</div>
<div id="image-container">
<img src="/capture?time=0" id="cam-image">
</div>
<script>
function refreshImage() {
var img = document.getElementById('cam-image');
img.src = '/capture?time=' + new Date().getTime();
}
setInterval(refreshImage, 300); // 每300毫秒更新一次
</script>
</body>
</html>"""
conn.sendall(b'HTTP/1.1 200 OK\r\n')
conn.sendall(b'Content-Type: text/html; charset=utf-8\r\n')
conn.sendall(b'Connection: close\r\n\r\n')
conn.sendall(html.encode('utf-8'))
except OSError as e:
print('Connection closed: OSError', e)
finally:
conn.close()
# 主程序
def main():
init_camera()
station = connect_to_wifi()
web_server(station)
if __name__ == '__main__':
main()