【无标题】使用ESP32 CAM进行网络拍照控制

部件:
1 ESP32-CAM
2、舵机
实现了摄像头水平旋转控制,及照片查看

在这里插入代码片

import camera
import os
import network
from machine import Pin,Timer,WDT,PWM
import time
import socket
import ure
from os import stat

class WifiMgmt:
def init(self, ssid=‘XXX’, password=‘XXX’):
self.ssid = ssid
self.password = password
self._connect()

def _connect(self):
    self.wifi_status = network.WLAN(network.STA_IF)
    self.wifi_status.active(True)
    self.wifi_status.connect(self.ssid, self.password)
    # check wifi connected
    while self.wifi_status.isconnected() == False:
        print('Wifi connecting...')
        time.sleep(1)
    # if connected
    print('Wifi connect successful')
    print(self.wifi_status.ifconfig())

class CameraMgmt():
def init(self):
#摄像头初始化
try:
# ESP32 初始化摄像头会出现初始化失败,先释放,没再出现摄像头初始化失败的情况
camera.deinit()
time.sleep(1)
camera.init(0, format=camera.JPEG, fb_location=camera.PSRAM)
except Exception as e:
camera.deinit()
print(str(e))

    #图像设置----------------------------        # 上下翻转
    #camera.flip(1)
    # 左右翻转
    camera.mirror(1)         
    # framesize
    camera.framesize(camera.FRAME_QVGA )
    # saturation
    camera.saturation(0)
    # -2,2 (default 0). -2 grayscale          
    # brightness
    camera.brightness(0)
    # -2,2 (default 0). 2 brightness
    camera.speffect(camera.EFFECT_NONE)
    # The options are the following:
    # EFFECT_NONE (default) EFFECT_NEG EFFECT_BW EFFECT_RED EFFECT_GREEN EFFECT_BLUE EFFECT_RETRO         
    # white balance
    camera.whitebalance(camera.WB_NONE)
    # contrast
    camera.contrast(0)
    #-2,2 (default 0). 2 highcontrast 
    # quality
    camera.quality(10)
    # 10-63 lower number means higher quality

def capture_save_photo(self):
    buf = camera.capture()
    #buf = "sdfsdfsdfdsf"
    print(len(buf))
    try:
        f=open("img/1.jpg",'wb')
        f.write(bytearray(buf))
        f.close()
    except Exception as e:
        print(str(e))

舵机控制程序,水平旋转摄像头

class TillerControl:
def init(self, rotate_step=5, default_degree=90):
self.default_degree = default_degree
self.cur_degree = self.default_degree # 初始摄像头角度
self.rotate_step = rotate_step # 旋转步长
# 电调输出引脚
self.tiller_pwm = PWM(Pin(12, Pin.OUT))
# 设置pwm频率
self.tiller_pwm.freq(50)
self._motor_rotate(self.default_degree)

# 设置舵机旋转角度
def _motor_rotate(self, degree):
    '''
    公式为
    c / 180(最大角度) * 2(0°-180°高电平脉冲宽度) + 0.5(舵机角度0°时高电平脉冲宽度)/ 20ms(脉冲周期) * 1023
    '''
    ts = int((degree / 180 * 2 + 0.5) / 20 * 1023)
    # 输出占空比
    self.tiller_pwm.duty(ts)

#  向指定的方向,按照步长进行旋转 "L"-向左 R-向右 D-到default角度
def rotate_direction(self, direction="L"):
    if direction == "L":
        self.cur_degree += self.rotate_step
        if self.cur_degree > 180:
            self.cur_degree = 180
    elif direction == "R":
        self.cur_degree -= self.rotate_step
        if self.cur_degree < 0:
            self.cur_degree = 0
    elif direction == "D":
        self.cur_degree = self.default_degree
    else:
        pass
    self._motor_rotate(self.cur_degree)

#ESP32 WEB服务
class WebMgmt:
def init(self):
self.web_service= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.web_service.bind((‘’, 80))
self.web_service.listen(10)
self.camera_num = 1

def web_page(self):
    html = """\
           <html>
            <head>
            <title>ESP Web Server</title>
              <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="icon" href="data:,">
            <style>
              html{font-family: Helvetica;
                  display:inline-block;
                  margin: 0px auto;
                  text-align: center;}
              h1{color: #0F3376; padding: 2vh;}
              p{font-size: 1.5rem;}
              .button{display: inline-block;
                  background-color: #e7bd3b; border: none;
                  border-radius: 4px; color: white;
                  padding: 16px 20px; text-decoration: none;
                  font-size: 16px; margin: 2px; cursor: pointer;}
              .button2{background-color: #4286f4;}
              </style>
           </head>
          <body>
          <h1>Cam Monitor</h1>
          <div style="text-align: center" id="container">
          <p><a href="/?degree=left"><button class="button button2">&lt--</button></a>
          <a href="/?degree=default"><button class="button" id="obtn">O</button></a>
          <a href="/?degree=right"><button class="button button2">--&gt</button></a> </p>
          <br />
          </div>

          <div><img src="img" id="photo"  /></div>
          </body>            
          </html>
          """
    return html

def getMimeTypeFromFilename(self, filename):
    filename = filename.lower()
    for ext in _mimeTypes:
        if filename.endswith(ext) :
            return _mimeTypes[ext]
    return None

def send_response(self, client, payload, status_code=200):
    content_length = len(payload)
    self.send_header(client, status_code, content_length)
    if content_length > 0:
        client.sendall(payload)
    client.close()

# 发送响应头
def send_header_file(self, client, status_code=200, content_length=None, content_type='text/html'):
    client.sendall("HTTP/1.0 {} OK\r\n".format(status_code))
    # 响应内容是 text/html
    client.sendall("Content-Type: {}\r\n".format(content_type))
    if content_length is not None:
        client.sendall("Content-Length: {}\r\n".format(content_length))
    client.sendall("\r\n")

# 处理 图片请求
def handle_image(self, client, url):
    jpg_data = camera.capture()
    if jpg_data is None or (not jpg_data):
        return False        
    size = len(jpg_data)
    self.send_header_file(client, 200, size, ".jpg" )
    try:
        if client.write(jpg_data):
            return True
        else:
            return False
    except Exception as e:
        print(str(e))
        return False
    return False

# 发送响应头
def send_header(self, client, status_code=200, content_length=None):
    client.sendall("HTTP/1.0 {} OK\r\n".format(status_code))
    # 响应内容是 text/html
    client.sendall("Content-Type: text/html\r\n")
    if content_length is not None:
        client.sendall("Content-Length: {}\r\n".format(content_length))
    client.sendall("\r\n")

# 找不到请求的相关处理,一般是因为输入错误请求内容
@staticmethod
def handle_not_found(self, client, url):
    self.send_response(client, "Path not found: {}".format(url), status_code=404)

# 处理主页面请求
def handle_homepage(self, client):
    self.send_header(client)
    client.sendall(self.web_page())
    client.close()

def build_web_service(self):
    while True:
        conn, addr = self.web_service.accept()
        #conn.settimeout(5.0)
        print('Connection: %s' % str(addr))
        try:
            req = b""
            while "\r\n\r\n" not in req:
                req += conn.recv(512)
            req = str(req)
            # 请求如果不是http直接忽略
            if "HTTP" not in req:  # skip invalid requests
                continue
            print('Connect = %s' % req)
            try:
                url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", req).group(1).decode("utf-8").rstrip("/")
            except Exception:
                url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", req).group(1).rstrip("/")
            print("URL is ", url)
            if url == "img":
                self.handle_image(conn, url)
            elif url == "":
                btn_lst = ['/?degree=left', '/?degree=right', '/?degree=default']
                search_pos = -1
                for btn_index, btn_value in enumerate(btn_lst):
                    search_pos = req.find(btn_value)
                    if search_pos > 0:
                        break
                print("btn_index", btn_index)
                if search_pos > 0:
                    if btn_index == 0:
                        my_tiller.rotate_direction("L")
                    elif btn_index == 1:
                        pass
                        #self.handle_image(conn, "img")
                    elif btn_index == 2:
                        print("default")
                        my_tiller.rotate_direction("D")
                    else:
                        pass
                self.handle_homepage(conn)

        finally:
            conn.close()

my_wifi = WifiMgmt()
my_camera = CameraMgmt()
my_tiller = TillerControl()
my_web = WebMgmt()
my_web.build_web_service()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值