**前言:**本篇博客为手把手教学的基于 ESP32S3 与 OV5640 的自制 DIY 相机项目,项目使用的 MCU 为乐鑫 ESP32S3 搭配豪威的 OV5640 摄像头进行视频采集显示。本项目基于 FreeRTOS 系统进行各个模块的代码逻辑编写,代码包括:OV5640 驱动、2.4 寸 LCD 驱动、SD 卡、电池电量采样与按键操作等。本项目自制 ESP32S3 相机包含软件与硬件的设计,综合学习性尚可且项目可以后续迭代简单的 AI 视频识别功能。希望这篇博文能给读者朋友的工程项目给予些许帮助,Respect(代码开源)!
**硬件与软件:**ESP32S3、OV5640、LCD_ili9341、ESP32_IDF、嘉立创EDA




一、ESP32S3 的自制相机项目介绍
1.1 OV5640 概述
OV5640 是豪威(OmniVision)推出的 1/4 英寸、500 万像素 CMOS 图像传感器(SoC),采用 OmniBSI 背照式像素技术,像素尺寸 1.4μm,片内集成完整 ISP 图像处理、JPEG 压缩引擎、自动对焦驱动。OV5640 最初面向手机自动对焦摄像头市场设计,后来因其高性价比、接口灵活、软件生态成熟,被广泛用于各类嵌入式视觉项目。典型应用包括:嵌入式视觉与机器视觉(STM32、ESP32-S3、NXP i.MX RT 等平台)、安防监控与智能门禁、机器人平台与无人机、车牌识别与条码扫描、智能家居与 IoT 相机设备等

硬件接口:
1、SCCB(I2C 兼容):寄存器配置控制接口,用于设置分辨率、白平衡、曝光等参数;
2、DVP 并行接口:8‑10bit 并口,适合 STM32 DCMI、FPGA;PCLK、VSYNC、HSYNC、D 9:0;
3、MIPI CSI‑2(双 Lane):高速差分串行接口,用于高性能平台;
支持输出格式:
1、RAW‑RGB(原始拜耳);
2、RGB565 / RGB555 / RGB444;
3、YUV422、YUV420;
1.2 Camera DVP 介绍
DVP(Digital Video Port)是传统的 Sensor 输出接口,采用并行输出方式,数据位宽有 8bit、10bit、12bit、16bit 等。其广泛用于 OV2640、OV5640、GC0308 等摄像头模组,STM32 DCMI、ESP32-S3、CH32、瑞芯微、全志等 MCU/SoC 都内置 DVP 接收控制器;它不是标准化国际协议,是行业通用并行视频时序规范,没有数据包、CRC、重传机制,属于极简的同步并行传输接口。

核心定位与特点
1. 传输方向: Sensor(发送端)→ 主控(接收端);Sensor 由主控提供参考时钟 XCLK,通过 I2C(SCCB)配置寄存器。
2. 信号类型: 全部为单端信号,无差分,布线简单但抗干扰弱、传输距离短(一般建议 PCB 走线 <10cm)。
3. 带宽上限: PCLK 典型上限 80~96MHz,多用于 5MP 以内、低帧率场景;高分辨率高帧率一般改用 MIPI CSI-2。
4. 无协议开销: 只有同步时序,没有帧头、校验、ACK,出错直接丢像素,没有纠错,适合低成本嵌入式视觉(人脸识别、扫码、视觉巡线、简易监控)。
5. 两种同步模式
HREF 模式(主流,OV 系列默认): HREF = 高代表本行有效像素区间,消隐区 HREF 拉低;
**HSYNC 模式:**HSYNC 脉冲标记行起始,和 VGA 时序一致,现在用得少。
信号定义(标准 DVP 引脚):
| 信号名 | 方向 | 说明 |
|---|---|---|
| PCLK(Pixel Clock) | Sensor → 主控 | 像素时钟,每一个 PCLK 对应 1 个像素采样;数据在 PCLK 上升沿 / 下降沿采样(极性可配置),由 Sensor 内部分频产生,来自 XCLK |
| VSYNC(Vertical Sync) | Sensor → 主控 | 帧同步信号,标记一帧图像的开始 / 结束;一帧只产生一次脉冲 / 电平区间,极性可编程(高有效 / 低有效) |
| HREF(HSYNC / HD) | Sensor → 主控 | 行有效信号;HREF 有效期间,D 7:0 上的数据是本行有效像素;HREF 无效为行消隐(行前肩、行后肩) |
| D7:0 / D9:0 / D11:0 | Sensor → 主控 | 并行像素数据线,最常用 8bit;10bit/12bit 用于高动态 RAW 传感器 |
| XCLK(EXTCLK) | 主控 → Sensor | 传感器参考主时钟,一般 12MHz / 24MHz;Sensor 基于 XCLK 分频生成 PCLK |
| SDA / SCL(SCCB/I2C) | 双向 | 独立于视频数据流,用于配置 Sensor 寄存器、分辨率、帧率、输出格式 |
1.3 ESP32S3 的自制相机介绍
本项目使用乐鑫信息科技股份有限公司的 ESP32S3 作为核心 MCU,搭配豪威 OV5640 摄像头进行视频采集。使用 OV5640 传感器采集相机所拍摄到的视频画面并在 2.4 寸 LCD 上进行显示,此外本项目还增加了 SD 卡存储与ADC电池电量采集功能。本项目最终制作的 ESP32S3 相机可以进行简单的生活记录,类似于大疆的 Osmo-Action 系列。项目框架如下图所示:

二、ikun Camera 的硬件设计
2.1 ikun Camera 的电路设计
ikun Camera 外围电路都是属于比较简单的,作者这边仅搭建项目所需的元器件,如下:
1、MCU部分:使用乐鑫 ESP32S3 作为核心搭建最小系统核心电路;
2、ESP32S3 自动下载电路:利用 2 个 NPN 三极管搭配 CH340K 组成;
3、电源切换电路:利用 PMOS 管的导通特性进行项目的电源切换;
4、按键 Key 电路:Key1 和 Key2 摄像视频的保存与暂停操作;
5、SD卡存储:简单的标准 SD 卡存储电路;
6、OV5640 电路:根据官方手册绘制 OV5640 的基础电路设计,并提供相关引脚供电;
1、ESP32S3 程序自动下载电路设计:
利用 2 个 NPN 三极管搭配 CH340K 组成 ESP32 系列 MCU 最经典的自动下载电路:
1、阶段 1:复位芯片(DTR#=高,RTS#=低)
DTR# 输出高 → Q1 NPN 三极管导通 → **EN 被强行拉低,ESP32‑S3 进入复位,停止运行
RTS# 输出低 → Q2 三极管截止 → GPIO0 保持上拉高电平。此时芯片被死死按住复位,不会启动。
2、阶段 2:切换电平,制造下载条件(关键一步)DTR#=低,RTS#=高
DTR# 变为低 → Q1 截止,EN 由 10K 上拉电阻拉到高电平;**EN 产生上升沿,芯片开始启动
RTS# 变为高 → Q2 导通 → **GPIO0 被拉低**
⚡最重要:EN 从低变高(复位释放上电瞬间),GPIO0 正好处于低电平,ESP32‑S3 内部 ROM 采样 strapping 引脚,判定进入串口 ROM 下载模式,等待 UART 接收固件。
3、阶段 3:烧录固件(DTR#= 低,RTS#= 高)
- UART0(CH340K‑TXD/RXD)传输 bin 固件到 ESP32。
4、阶段 4:烧录完成,恢复正常运行(DTR#=高,RTS#=高)
Q1、Q2 全部截止
EN、GPIO0 全部被 10K 上拉为高电平
ESP32 再次复位,GPIO0 为高电平,从 Flash 运行刚刚烧录好的用户程序。

2、ikun Camera 的电源供电与电池电量采集电路设计:
ikun Camera 为了满足可以移动测量的需求,搭配了锂电池的电量采集和自动充电设计:
1、VBAT 电池电压经过 R10 (5.1k)+R11 (10k) 电阻分压,分压点进 MCU ADC 引脚;C9 (100nF) 做 RC 滤波,平滑电压采样,抑制噪声。 分压比:Vadc = Vbat × R11/(R11+R10) 例:锂电池满电 4.2V 时:Vadc = 4.2 × 10/(10+5.1) ≈ 2.78V,适配 3.3V 参考电压的 ADC;
2、HX4054A 是单节锂电池线性充电 IC(TP4054 同类型);
3、VBUS(5V)和 VBAT(锂电池)自动选通,输出 VIN 给后级 XC6206 LDO;

3、ikun Camera 的 OV5640 的电路设计;
按照官方的 OV5640 参考电路设计进行绘制,并保证 OV_I2C 启用 4.7k 上拉电阻进行 i2c 通信。 使用 XC6206 系列电源芯片提供 OV5640 所需的 1.2v 和 2.8v 电压;

4、ESP32S3 的外围电路设计:
ESP32S3 的外围电路是很简单的,除安排 ikun Camera 的功能 IO 之外保证 VCC 电源引脚的 10uF 退耦电容即可;

2.2 ikun Camera 的 PCB 设计
ikun Camera 项目涉及到的信号走线都属于普通信号线,故整个项目的 Layout 布局要求并不是很严格的,读者朋友们仅需将电源部分的走线尽量粗一点,ESP32S3 附近的退耦电容靠近对应 GPIO 引脚即可。当然,因为 OV5640 的电源引脚档位偏多(1.2v、2.8v、3.3v),故作者绘制了 4 层板子,第 3 层 PWR 负责走线 1.2v 和 2.8v。
信号线中需要做等长处理的:1、USBDM 和 USBDP;2、OV5640 的 D0~D7;
1、信号线中的等长处理部分:

2、ikun Camera 的 PCB:

三、ESP32S3 核心代码
3.1 OV5640 代码编写
作者因为绘制的硬件 PCB 原因并不能启用 ESP32S3 的 PSRAM,仅可以使用内部的 RAM(读者朋友们进行 2 创的时候可以试试看启用外部 PSRAM ,这样留给相机图像缓存的空间就会大很多,可以拍摄的图像画质也会高很多)。
ikun camera 直接使用的是 DVP 外设接口:ESP32-S3 的 LCD_CAM 外设按 PCLK/VSYNC/HREF 采样 8 位数据,GDMA 直接搬进内存。XCLK 由 LEDC 产生,20 MHz。
项目的框架结构如下:
cpp
main.c 业务主循环:预览、按键、拍照、电量
camera_app.c 引脚表、双模式配置、内存策略、取景裁剪
esp32-camera 传感器寄存器序列、PLL、DMA、帧队列
ESP-IDF LCD_CAM、GDMA、LEDC、GPIO
esp32-camera 组件通过`EXTRA_COMPONENT_DIRS` 引入本地源码,应用层只调用两套接口:
`esp_camera_init()` /`esp_camera_fb_get()` /`esp_camera_deinit()`
`sensor_t` :`set_res_raw()` 、`set_hmirror()`
也就是说,OV5640 的初始化表、JPEG 量化表、PLL 计算都在组件里,作者做的事情是配置 + 策略 。

camera_app.c:
cpp
/**
* @file camera_app.c
* @brief Camera initialization, QVGA preview and full-resolution stills.
*
* Owns the sensor pin map (taken from the board schematic) and all
* esp32-camera driver configuration. The preview runs in QVGA RGB565 in
* internal DRAM; a still capture temporarily reconfigures the sensor to
* JPEG at its maximum frame size and uses every free byte of internal
* RAM as JPEG buffer.
*/
#include "camera_app.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
/** @brief Log tag used by this module. */
static const char *TAG = "camera";
/**
* @defgroup camera_pins OV2640/OV5640 pin map
* @brief GPIO assignment taken from the board schematic.
*
* The parallel data bus, the SCCB control bus and the three sync signals
* are routed to the ESP32-S3 through the LCD connector.
* @{
*/
/** @brief Power-down output; not connected on this board. */
#define CAM_PIN_PWDN -1
/** @brief Sensor reset (OV_RESET). */
#define CAM_PIN_RESET 46
/** @brief Master clock generated by the ESP32-S3 LEDC peripheral. */
#define CAM_PIN_XCLK 3
/** @brief SCCB data line (OV_SDA). */
#define CAM_PIN_SIOD 41
/** @brief SCCB clock line (OV_SCL). */
#define CAM_PIN_SIOC 42
/** @brief Pixel data bit 7. */
#define CAM_PIN_D7 18
/** @brief Pixel data bit 6. */
#define CAM_PIN_D6 17
/** @brief Pixel data bit 5. */
#define CAM_PIN_D5 16
/** @brief Pixel data bit 4 (unlabeled in schematic, verify if preview is off). */
#define CAM_PIN_D4 9
/** @brief Pixel data bit 3. */
#define CAM_PIN_D3 15
/** @brief Pixel data bit 2. */
#define CAM_PIN_D2 7
/** @brief Pixel data bit 1. */
#define CAM_PIN_D1 6
/** @brief Pixel data bit 0. */
#define CAM_PIN_D0 5
/** @brief Frame valid / vertical sync. */
#define CAM_PIN_VSYNC 19
/** @brief Line valid / horizontal reference. */
#define CAM_PIN_HREF 20
/** @brief Pixel clock driven by the sensor. */
#define CAM_PIN_PCLK 8
/** @} */
/** @brief XCLK frequency fed to the sensor, in hertz. */
#define CAM_XCLK_HZ 20000000
/** @brief Preview frame size; matches the 320x240 LCD panel. */
#define PREVIEW_FRAMESIZE FRAMESIZE_QVGA
/** @brief Preview pixel format; written to the LCD without any decode. */
#define PREVIEW_PIXFORMAT PIXFORMAT_RGB565
/**
* @brief Internal RAM kept free while a still buffer is allocated.
*
* Covers the 16 KB camera DMA buffer, the FAT/VFS buffers used while
* writing the finished JPEG to the SD card, and general slack.
*/
#define STILL_RAM_MARGIN (32 * 1024)
/** @brief One still-capture attempt: frame size and JPEG quality. */
typedef struct {
framesize_t size; /**< Sensor frame size to program. */
int quality; /**< JPEG quality, 0-63, lower means better. */
} still_attempt_t;
/**
* @brief Attempts tried in order for a still picture.
*
* 1600x1200 at the best JPEG quality is the target; 1280x1024 is a
* fallback for a scene whose JPEG overflows the buffer. On the OV5640 the
* readout is cropped to the preview's field of view, so the saved picture
* keeps roughly the same pixel count with the same framing as the LCD.
*/
static const still_attempt_t k_still_ladder[] = {
{ FRAMESIZE_UXGA, 12 }, /* 1600x1200 */
{ FRAMESIZE_SXGA, 12 }, /* 1280x1024 */
};
/**
* @defgroup view_window View window shared with the LCD preview
* @brief Fraction of the sensor frame that the panel shows.
*
* lcd_write_frame_upright() maps the panel onto sensor columns 70..249
* of a 320-wide frame (full height) and rotates the result. The still
* capture programs the same window in the sensor, so the photo and the
* preview show the same field of view.
* @{
*/
/** @brief Width of the sensor frame the LCD mapping is based on. */
#define VIEW_FRAME_WIDTH 320
/** @brief First sensor column shown on the panel. */
#define VIEW_X_START 70
/** @brief One past the last sensor column shown on the panel. */
#define VIEW_X_END 250
/** @} */
/**
* @defgroup ov5640_window OV5640 4:3 readout window and timing
* @brief Values the sensor driver programs for its full 4:3 frame.
* @{
*/
#define OV5640_WIN_X0 0
#define OV5640_WIN_X1 2623
#define OV5640_WIN_Y0 0
#define OV5640_WIN_Y1 1951
#define OV5640_OFFSET_X 32
#define OV5640_OFFSET_Y 16
#define OV5640_TOTAL_X 2844
#define OV5640_TOTAL_Y 1968
/** @} */
/** @brief Output size of the last cropped capture, 0 when not cropped. */
static int s_view_width;
static int s_view_height;
/**
* @brief Program the sensor readout window used by the preview.
*
* The window keeps the full sensor height and the middle strip that the
* LCD shows, so the JPEG frames exactly what the user sees. The output
* keeps a 3:4 aspect at the pixel count of @p size.
*
* @param[in] sensor OV5640 handle.
* @param[in] size Requested frame size, selects the output height.
* @return ESP_OK when the window was applied.
*/
static esp_err_t apply_view_window(sensor_t *sensor, framesize_t size)
{
if (sensor == NULL || sensor->set_res_raw == NULL) {
return ESP_ERR_NOT_SUPPORTED;
}
const int win_w = OV5640_WIN_X1 - OV5640_WIN_X0 + 1;
const int start_x = OV5640_WIN_X0 +
(win_w * VIEW_X_START) / VIEW_FRAME_WIDTH;
const int end_x = OV5640_WIN_X0 +
(win_w * VIEW_X_END) / VIEW_FRAME_WIDTH - 1;
const int out_h = (size == FRAMESIZE_SXGA) ? 1280 : 1600;
const int out_w = (out_h * 3) / 4;
int err = sensor->set_res_raw(sensor, start_x, OV5640_WIN_Y0, end_x,
OV5640_WIN_Y1, OV5640_OFFSET_X,
OV5640_OFFSET_Y, OV5640_TOTAL_X,
OV5640_TOTAL_Y, out_w, out_h, true, false);
if (err != 0) {
ESP_LOGW(TAG, "View window not applied (0x%x), full frame kept", err);
s_view_width = 0;
s_view_height = 0;
return ESP_FAIL;
}
/* The preview pipeline mirrors the sensor image as well as rotating it
* (see lcd_write_frame_upright); mirror the still in the sensor so the
* file only needs a 90° clockwise turn to look exactly like the panel. */
if (sensor->set_hmirror != NULL) {
sensor->set_hmirror(sensor, 1);
}
s_view_width = out_w;
s_view_height = out_h;
ESP_LOGI(TAG, "View window %d..%d -> %dx%d (mirrored)", start_x, end_x,
out_w, out_h);
return ESP_OK;
}
/**
* @brief Check that a captured frame is a complete JPEG.
*
* The EOI marker is searched for instead of being required in the last
* two bytes, because some sensors pad the end of the buffer. A frame
* without any EOI was cut off at the buffer limit and must not be saved.
*
* @param[in] data JPEG bitstream.
* @param[in] len Length of @p data in bytes.
* @return true when the SOI and EOI markers are present.
*/
static bool jpeg_is_complete(const uint8_t *data, size_t len)
{
if (len < 4 || data[0] != 0xFF || data[1] != 0xD8) {
return false;
}
for (size_t i = len; i >= 2; i--) {
if (data[i - 2] == 0xFF && data[i - 1] == 0xD9) {
return true;
}
}
return false;
}
/**
* @brief Fill in the board and driver settings shared by both modes.
*
* The caller only has to override the pixel format, frame size and JPEG
* options for the mode it wants.
*
* @param[out] config Configuration to initialize.
*/
static void camera_config_defaults(camera_config_t *config)
{
*config = (camera_config_t){
.pin_pwdn = CAM_PIN_PWDN,
.pin_reset = CAM_PIN_RESET,
.pin_xclk = CAM_PIN_XCLK,
.pin_sccb_sda = CAM_PIN_SIOD,
.pin_sccb_scl = CAM_PIN_SIOC,
.pin_d7 = CAM_PIN_D7,
.pin_d6 = CAM_PIN_D6,
.pin_d5 = CAM_PIN_D5,
.pin_d4 = CAM_PIN_D4,
.pin_d3 = CAM_PIN_D3,
.pin_d2 = CAM_PIN_D2,
.pin_d1 = CAM_PIN_D1,
.pin_d0 = CAM_PIN_D0,
.pin_vsync = CAM_PIN_VSYNC,
.pin_href = CAM_PIN_HREF,
.pin_pclk = CAM_PIN_PCLK,
.xclk_freq_hz = CAM_XCLK_HZ,
.ledc_timer = LEDC_TIMER_0,
.ledc_channel = LEDC_CHANNEL_0,
.fb_count = 1,
.fb_location = CAMERA_FB_IN_DRAM,
.grab_mode = CAMERA_GRAB_WHEN_EMPTY,
};
}
/**
* @brief Start the driver with the given configuration.
*
* @param[in] config Complete camera configuration.
* @return ESP_OK on success, otherwise the esp_camera_init() error.
*/
static esp_err_t camera_start(const camera_config_t *config)
{
esp_err_t err = esp_camera_init(config);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Camera init failed: 0x%x", err);
}
return err;
}
/**
* @brief Start the camera in QVGA RGB565 preview mode.
*
* The frame buffer stays in internal DRAM because PSRAM is not enabled on
* this board; the LCD is fed straight from it without any conversion.
*
* @return ESP_OK on success, otherwise the esp_camera_init() error.
*/
esp_err_t camera_app_init(void)
{
camera_config_t config;
camera_config_defaults(&config);
config.pixel_format = PREVIEW_PIXFORMAT;
config.frame_size = PREVIEW_FRAMESIZE;
config.jpeg_quality = 12; /* unused for RGB565 */
return camera_start(&config);
}
/**
* @brief Restart the QVGA preview after a still capture.
*
* The driver is deinitialized first, so a camera left running in JPEG mode
* and a camera that failed mid-way are handled identically.
*
* @return ESP_OK on success, otherwise the esp_camera_init() error.
*/
esp_err_t camera_app_resume_preview(void)
{
/* The still capture leaves the driver either running in JPEG mode or
* already stopped; deinit makes both cases identical. */
esp_camera_deinit();
return camera_app_init();
}
/**
* @brief Capture one full-resolution JPEG still.
*
* Stops the preview, then tries each entry of the attempt ladder: JPEG at
* the requested size, a readout window that matches the preview field of
* view (OV5640 only, mirrored like the panel pipeline) and a buffer made of
* all remaining internal RAM minus a safety margin. A frame without an EOI
* marker is treated as a failure so a truncated picture never reaches the
* card. The driver is left running in JPEG mode on success.
*
* @return Frame buffer owned by the caller (release it with
* esp_camera_fb_return()), or NULL when every attempt failed.
*/
camera_fb_t *camera_app_capture_still(void)
{
/* Detect the sensor before the driver is stopped: only the OV5640
* supports the windowed readout that matches the preview framing. */
sensor_t *sensor = esp_camera_sensor_get();
bool can_crop = (sensor != NULL && sensor->id.PID == OV5640_PID);
s_view_width = 0;
s_view_height = 0;
/* Stop the preview and release its QVGA frame buffer. */
esp_camera_deinit();
const size_t count = sizeof(k_still_ladder) / sizeof(k_still_ladder[0]);
for (size_t i = 0; i < count; i++) {
/* Give the driver every free internal-RAM byte minus a safety
* margin; the JPEG must fit into this single buffer. */
size_t largest = heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL |
MALLOC_CAP_8BIT);
if (largest <= STILL_RAM_MARGIN) {
ESP_LOGE(TAG, "Only %u KB internal RAM left, cannot capture",
(unsigned)(largest / 1024));
return NULL;
}
size_t buffer_size = largest - STILL_RAM_MARGIN;
camera_config_t config;
camera_config_defaults(&config);
config.pixel_format = PIXFORMAT_JPEG;
config.frame_size = k_still_ladder[i].size;
config.jpeg_quality = k_still_ladder[i].quality;
config.jpeg_buffer_size = buffer_size;
ESP_LOGI(TAG, "Still attempt: framesize %d, quality %d, buffer %u KB",
(int)k_still_ladder[i].size, k_still_ladder[i].quality,
(unsigned)(buffer_size / 1024));
if (camera_start(&config) != ESP_OK) {
continue;
}
/* Match the preview framing before the frame is grabbed. */
if (can_crop) {
apply_view_window(esp_camera_sensor_get(),
k_still_ladder[i].size);
}
camera_fb_t *fb = esp_camera_fb_get();
if (fb != NULL) {
if (jpeg_is_complete(fb->buf, fb->len)) {
ESP_LOGI(TAG, "Still captured: %dx%d, %u bytes",
s_view_width ? s_view_width : fb->width,
s_view_height ? s_view_height : fb->height,
(unsigned)fb->len);
return fb;
}
/* A frame that hit the buffer limit is handed over truncated,
* without the EOI marker, and would be unusable on a PC. Treat
* it as a failed attempt so the next size is tried instead. */
ESP_LOGW(TAG, "JPEG frame incomplete (no EOI), next attempt");
esp_camera_fb_return(fb);
} else {
/* The compressed frame exceeded the buffer and was dropped;
* try the next attempt (lower quality or lower resolution). */
ESP_LOGW(TAG, "Frame does not fit, next attempt");
}
esp_camera_deinit();
}
ESP_LOGE(TAG, "Still capture failed");
return NULL;
}
3.2 LCD_ili9341 的代码编写
ikun Camera 的视频流显示使用 LCD_ili9341 驱动芯片,这款 LCD 驱动 IC 的使用很常规,考虑到文章篇幅受这边仅粘贴出详细代码为主,不做过多代码详解;老规矩为了搭配 ikun 主题,作者借助 AI 设计了 ikun 的 DIY 相机的主题 UI;

lcd_ili9341.c:
这部分考虑到博客篇幅有限,全部代码可以参考开源出的项目源码!!!推荐的相关学习博客:基于ESP32S3与MLX90640的热成像仪项目(代码开源)-CSDN博客

3.3 SD 卡存储代码
作者开机的时候利用 EPS32S3 的 SPI3 挂载 FAT(不自动格式化)并扫描下一个 IMG 编号,拍照前卸载 SDK 卡腾出约 100 KB 内存给 JPEG 缓冲、拍完立刻重挂,写盘时插入 EXIF 方向标记并做完整性/大小三重校验,只让能打开的完整 JPEG 落地。EXIF 段逐字段解读如下:
cpp
FF E1 APP1 标记
00 22 段长度 34(含长度字段自身)
45 78 69 66 00 00 "Exif\0\0"
49 49 2A 00 "II*\0":小端 TIFF
08 00 00 00 IFD0 偏移 8
01 00 1 个条目
12 01 标签 0x0112 = Orientation
03 00 类型 SHORT
01 00 00 00 数量 1
06 00 00 00 值 6 = 顺时针旋转 90°
00 00 00 00 没有下一个 IFD

sd_storage.c:
cpp
/**
* @file sd_storage.c
* @brief microSD card mounting and JPEG photo storage.
*
* The card shares no bus with the LCD: the panel uses SPI2, so the card is
* attached to SPI3 and never reconfigures the display bus. Pictures arrive
* as finished JPEG bitstreams from the camera module and are stored with
* an EXIF orientation tag, so the file keeps the full resolution while
* viewers display it in the same orientation as the LCD.
*/
#include "sd_storage.h"
#include <dirent.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <sys/stat.h>
#include "driver/gpio.h"
#include "driver/sdspi_host.h"
#include "driver/spi_master.h"
#include "esp_log.h"
#include "esp_vfs_fat.h"
#include "sdmmc_cmd.h"
/** @brief Log tag used by this module. */
static const char *TAG = "sd_storage";
/**
* @brief APP1/EXIF block that marks the picture as rotated 90° clockwise.
*
* The camera module is mounted 90° rotated relative to the panel, so the
* JPEG pixels are stored with the scene's top pointing to the left edge.
* Rotating the bitstream itself would need a full decode (several MB),
* which the board does not have, so an Orientation tag (0x0112 = 6) is
* inserted right after the SOI marker: viewers that honour EXIF show the
* picture exactly like the preview. The JPEG data stays untouched.
*/
static const uint8_t k_exif_rotate_cw[] = {
0xFF, 0xE1, 0x00, 0x22, /* APP1 marker, payload 34 bytes */
'E', 'x', 'i', 'f', 0x00, 0x00, /* Exif identifier */
'I', 'I', 0x2A, 0x00, /* TIFF header, little-endian */
0x08, 0x00, 0x00, 0x00, /* IFD0 starts at offset 8 */
0x01, 0x00, /* one directory entry */
0x12, 0x01, /* tag 0x0112 (Orientation) */
0x03, 0x00, /* type SHORT */
0x01, 0x00, 0x00, 0x00, /* count 1 */
0x06, 0x00, 0x00, 0x00, /* value 6: rotate 90° clockwise */
0x00, 0x00, 0x00, 0x00, /* no next IFD */
};
/**
* @brief Check that a bitstream is a complete JPEG.
*
* The camera can hand over a frame that hit its buffer limit; such a
* frame has no EOI marker and cannot be opened by any viewer, so it must
* never reach the card. The marker is searched for instead of being
* required at the very end, because some sensors pad the last bytes.
*
* @param[in] data JPEG bitstream.
* @param[in] len Length of @p data in bytes.
* @return true when SOI and EOI markers are present.
*/
static bool jpeg_is_complete(const uint8_t *data, size_t len)
{
if (len < 4 || data[0] != 0xFF || data[1] != 0xD8) {
return false;
}
for (size_t i = len; i >= 2; i--) {
if (data[i - 2] == 0xFF && data[i - 1] == 0xD9) {
return true;
}
}
return false;
}
/**
* @defgroup sd_pins microSD wiring (SPI mode)
* @brief Card pins on the ikun_camera board.
*
* MISO = GPIO11, CLK = GPIO12, MOSI = GPIO13, CS = GPIO14. The card is
* driven from SPI3 while the LCD keeps SPI2.
* @{
*/
/** @brief Card data-out (MISO). */
#define SD_PIN_MISO 11
/** @brief SPI clock. */
#define SD_PIN_CLK 12
/** @brief Card data-in (MOSI). */
#define SD_PIN_MOSI 13
/** @brief Card chip select. */
#define SD_PIN_CS 14
/** @brief SPI peripheral dedicated to the card; the LCD keeps SPI2. */
#define SD_SPI_HOST SPI3_HOST
/** @brief VFS mount point exposed to the application. */
#define SD_MOUNT_POINT "/sdcard"
/** @} */
/** @brief Mounted card handle, owned by the FAT VFS layer. */
static sdmmc_card_t *s_sd_card;
/** @brief True once the SPI3 bus used by the card has been initialized. */
static bool s_bus_ready;
/** @brief True once the card is mounted and writable. */
static bool s_sd_ready;
/** @brief Index used for the next IMG_xxxx.JPG file. */
static int s_next_photo = 1;
/**
* @brief Find the next free IMG_xxxx index on the card.
*
* Existing files are scanned so that a reboot never overwrites a photo.
* The extension is ignored on purpose so old .BMP and new .JPG files
* share a single, gap-free numbering.
*
* @return First unused index, or 1 when the directory cannot be opened.
*/
static int sd_next_photo_index(void)
{
DIR *dir = opendir(SD_MOUNT_POINT);
if (!dir) {
return 1;
}
int max_idx = 0;
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
int idx;
if (sscanf(ent->d_name, "IMG_%d", &idx) == 1 && idx > max_idx) {
max_idx = idx;
}
}
closedir(dir);
return max_idx + 1;
}
/**
* @brief Mount the microSD card over SPI and scan the next file index.
*
* Safe to call again after sd_storage_unmount(): the SPI bus stays
* initialized, so a remount only has to read the FAT volume again.
*
* @return ESP_OK on success, otherwise the SPI or FAT mount error.
*/
esp_err_t sd_storage_init(void)
{
if (s_sd_ready) {
return ESP_OK;
}
if (!s_bus_ready) {
/* Initialise SPI3 for the card; DMA is used for block transfers. */
spi_bus_config_t bus_cfg = {
.mosi_io_num = SD_PIN_MOSI,
.miso_io_num = SD_PIN_MISO,
.sclk_io_num = SD_PIN_CLK,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
.max_transfer_sz = 4096,
};
esp_err_t bus_err = spi_bus_initialize(SD_SPI_HOST, &bus_cfg,
SPI_DMA_CH_AUTO);
if (bus_err != ESP_OK) {
ESP_LOGE(TAG, "SD SPI bus init failed: %s",
esp_err_to_name(bus_err));
return bus_err;
}
s_bus_ready = true;
/* In SPI mode the card drives MISO only while it is selected.
* Weak internal pull-ups keep the four lines defined between
* transfers, which makes the CMD8 identification noticeably more
* reliable on boards without external resistors. */
gpio_set_pull_mode(SD_PIN_MISO, GPIO_PULLUP_ONLY);
gpio_set_pull_mode(SD_PIN_MOSI, GPIO_PULLUP_ONLY);
gpio_set_pull_mode(SD_PIN_CLK, GPIO_PULLUP_ONLY);
gpio_set_pull_mode(SD_PIN_CS, GPIO_PULLUP_ONLY);
}
/* The card is spoken to over SPI (not native SD), capped at 20 MHz. */
sdmmc_host_t host = SDSPI_HOST_DEFAULT();
host.slot = SD_SPI_HOST;
host.max_freq_khz = 20000;
sdspi_device_config_t slot = SDSPI_DEVICE_CONFIG_DEFAULT();
slot.host_id = SD_SPI_HOST;
slot.gpio_cs = SD_PIN_CS;
/* Never format a card implicitly: an unreadable card is reported
* instead of silently destroying its contents. */
esp_vfs_fat_sdmmc_mount_config_t mount_cfg = {
.format_if_mount_failed = false,
.max_files = 4,
.allocation_unit_size = 16 * 1024,
};
esp_err_t err = esp_vfs_fat_sdspi_mount(SD_MOUNT_POINT, &host, &slot,
&mount_cfg, &s_sd_card);
if (err != ESP_OK) {
ESP_LOGE(TAG, "SD mount failed: %s (0x%x); check that a FAT32 card "
"is inserted and that TF_CS is really GPIO%d",
esp_err_to_name(err), err, SD_PIN_CS);
return err;
}
s_sd_ready = true;
s_next_photo = sd_next_photo_index();
ESP_LOGI(TAG, "SD card mounted, next photo index %d", s_next_photo);
return ESP_OK;
}
/**
* @brief Release the FAT volume and card structures.
*
* Called before a still capture so the ~100 KB held by the FAT state can be
* used by the JPEG frame buffer. The SPI bus is kept initialized so that
* sd_storage_init() can remount quickly.
*
* @return ESP_OK on success, ESP_ERR_INVALID_STATE when no card is mounted,
* otherwise the FAT unmount error.
*/
esp_err_t sd_storage_unmount(void)
{
if (!s_sd_ready || s_sd_card == NULL) {
return ESP_ERR_INVALID_STATE;
}
/* Releases the FAT volume and card structures. The SPI bus stays up so
* that a later sd_storage_init() can remount quickly. */
esp_err_t err = esp_vfs_fat_sdcard_unmount(SD_MOUNT_POINT, s_sd_card);
if (err != ESP_OK) {
ESP_LOGE(TAG, "SD unmount failed: %s", esp_err_to_name(err));
return err;
}
s_sd_card = NULL;
s_sd_ready = false;
ESP_LOGI(TAG, "SD card unmounted");
return ESP_OK;
}
/**
* @brief Write one JPEG picture to the card as IMG_<index>.JPG.
*
* The bitstream must be a complete JPEG; an EXIF orientation tag is
* inserted right after its SOI marker so viewers show the picture in the
* same orientation as the preview. After closing, the file size on the
* card is verified and a damaged file is removed.
*
* @param[in] data JPEG bitstream returned by the camera driver.
* @param[in] len Length of @p data in bytes.
*
* @return ESP_OK on success, otherwise an ESP_ERR_* code describing why
* the picture could not be stored.
*/
esp_err_t sd_storage_save_jpeg(const uint8_t *data, size_t len)
{
if (!s_sd_ready) {
/* A card may be inserted after boot; try once more before giving
* up so the user does not have to reset the board. */
ESP_LOGW(TAG, "Card not mounted, trying to mount now");
if (sd_storage_init() != ESP_OK) {
ESP_LOGE(TAG, "Save failed: no card mounted");
return ESP_ERR_INVALID_STATE;
}
}
if (data == NULL || len == 0) {
ESP_LOGE(TAG, "Save failed: empty frame");
return ESP_ERR_INVALID_ARG;
}
/* Never store a truncated bitstream: the camera hands over frames that
* hit its buffer without the EOI marker, and such a file cannot be
* opened by any viewer. */
if (!jpeg_is_complete(data, len)) {
ESP_LOGE(TAG, "Save failed: incomplete JPEG (%u bytes)",
(unsigned)len);
return ESP_ERR_INVALID_SIZE;
}
char path[32];
snprintf(path, sizeof(path), SD_MOUNT_POINT "/IMG_%04d.JPG",
s_next_photo);
FILE *f = fopen(path, "wb");
if (!f) {
ESP_LOGE(TAG, "Cannot open %s (errno %d)", path, errno);
return ESP_FAIL;
}
/* Use a stream buffer so the card sees few, large writes. */
setvbuf(f, NULL, _IOFBF, 16 * 1024);
/* Write SOI, then the orientation block, then the rest of the
* bitstream. The SOI must come first: without it no viewer accepts
* the file. */
size_t written = 0;
size_t expected = len;
if (len >= 2 && data[0] == 0xFF && data[1] == 0xD8) {
written = fwrite(data, 1, 2, f);
written += fwrite(k_exif_rotate_cw, 1, sizeof(k_exif_rotate_cw), f);
written += fwrite(data + 2, 1, len - 2, f);
expected = 2 + sizeof(k_exif_rotate_cw) + len - 2;
} else {
written = fwrite(data, 1, len, f);
}
if (fclose(f) != 0) {
ESP_LOGE(TAG, "Close failed: %s (errno %d)", path, errno);
remove(path);
return ESP_FAIL;
}
if (written != expected) {
ESP_LOGE(TAG, "Write failed: %s (%u/%u bytes)", path,
(unsigned)written, (unsigned)expected);
remove(path);
return ESP_FAIL;
}
/* Verify what actually landed on the card. A short write that only
* fails during fclose() would otherwise leave a file that no viewer
* can open. */
struct stat st;
if (stat(path, &st) != 0) {
ESP_LOGE(TAG, "Cannot stat %s (errno %d)", path, errno);
return ESP_FAIL;
}
if ((size_t)st.st_size != expected) {
ESP_LOGE(TAG, "Size mismatch: %s is %ld, expected %u; removed",
path, (long)st.st_size, (unsigned)expected);
remove(path);
return ESP_FAIL;
}
ESP_LOGI(TAG, "Saved %s (%u bytes)", path, (unsigned)expected);
s_next_photo++;
return ESP_OK;
}
3.4 Battery_ADC 代码编写
作者利用分压把 4.2 V 降到 2.8 V 以内 → ADC1_CH3 采样 32 次取平均并用校准库换算成电压 → 乘回分压比后线性映射成 0--100% 。简单、够用,精度上的短板主要在电池放电曲线的非线性,而不是 ADC 本身。额外补充:ESP32 系列的 ADC 线性度一般,官方提供两种校准方式:curve_fitting(曲线拟合)和line_fitting (线性拟合)。作者优先用曲线拟合,失败也不阻塞启动------后面会退化成线性估算。

battery.c:
cpp
/**
* @file battery.c
* @brief Battery voltage sampling and percentage mapping.
*
* Reads the ADC node of the 5.1k/10k divider on GPIO4, converts it back to
* the pack voltage and maps 3.3-4.2 V onto 0-100 %.
*/
#include "battery.h"
#include "esp_adc/adc_cali.h"
#include "esp_adc/adc_cali_scheme.h"
#include "esp_adc/adc_oneshot.h"
#include "esp_log.h"
static const char *TAG = "battery";
/**
* @defgroup battery_hw Battery divider on GPIO4 (ADC1 channel 3)
* @brief Li-ion voltage measurement.
*
* Schematic: VBAT -- R10 (5.1k) -- ADC node -- R11 (10k) -- GND, with a
* 100 nF capacitor from the ADC node to GND. Therefore:
* VBAT = V_ADC * (R10 + R11) / R11 = V_ADC * 1.51
*
* Percentage is mapped linearly from 3.3 V (empty) to 4.2 V (full).
* @{
*/
#define BATTERY_ADC_CHANNEL ADC_CHANNEL_3 /**< GPIO4 -> ADC1 channel 3 */
#define BATTERY_ADC_ATTEN ADC_ATTEN_DB_12
#define BATTERY_R_TOP_OHM 5100 /**< R10: VBAT to ADC node */
#define BATTERY_R_BOTTOM_OHM 10000 /**< R11: ADC node to GND */
#define BATTERY_EMPTY_MV 3300
#define BATTERY_FULL_MV 4200
/** @} */
static adc_oneshot_unit_handle_t s_battery_adc;
static adc_cali_handle_t s_battery_cali;
/**
* @brief Set up ADC1 channel 3 for the battery divider.
*
* The curve-fitting calibration scheme is used when available; without it
* the voltage conversion falls back to a linear estimate.
*
* @return ESP_OK on success, otherwise the ADC driver error.
*/
esp_err_t battery_init(void)
{
adc_oneshot_unit_init_cfg_t unit_cfg = {
.unit_id = ADC_UNIT_1,
.ulp_mode = ADC_ULP_MODE_DISABLE,
};
esp_err_t err = adc_oneshot_new_unit(&unit_cfg, &s_battery_adc);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Battery ADC unit init failed: %s", esp_err_to_name(err));
return err;
}
adc_oneshot_chan_cfg_t chan_cfg = {
.atten = BATTERY_ADC_ATTEN,
.bitwidth = ADC_BITWIDTH_DEFAULT,
};
err = adc_oneshot_config_channel(s_battery_adc, BATTERY_ADC_CHANNEL,
&chan_cfg);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Battery ADC channel config failed: %s",
esp_err_to_name(err));
return err;
}
adc_cali_curve_fitting_config_t cali_cfg = {
.unit_id = ADC_UNIT_1,
.chan = BATTERY_ADC_CHANNEL,
.atten = BATTERY_ADC_ATTEN,
.bitwidth = ADC_BITWIDTH_DEFAULT,
};
if (adc_cali_create_scheme_curve_fitting(&cali_cfg, &s_battery_cali)
!= ESP_OK) {
ESP_LOGW(TAG, "Battery ADC calibration unavailable, using linear estimate");
s_battery_cali = NULL;
}
return ESP_OK;
}
/**
* @brief Sample the battery once and convert it to a percentage.
*
* 32 consecutive readings are averaged to suppress noise, converted to
* millivolts and scaled back through the 5.1k/10k divider. The result is
* clamped to 0..100 % between 3.3 V and 4.2 V.
*
* @return 0-100 on success, or -1 when the ADC is not initialized or a
* conversion fails.
*/
int battery_read_level(void)
{
if (!s_battery_adc) {
return -1;
}
int64_t sum = 0;
for (int i = 0; i < 32; i++) {
int raw = 0;
if (adc_oneshot_read(s_battery_adc, BATTERY_ADC_CHANNEL, &raw)
!= ESP_OK) {
return -1;
}
sum += raw;
}
int adc_mv;
int raw = (int)(sum / 32);
if (s_battery_cali) {
if (adc_cali_raw_to_voltage(s_battery_cali, raw, &adc_mv) != ESP_OK) {
return -1;
}
} else {
adc_mv = raw * 3100 / 4095;
}
int battery_mv = adc_mv * (BATTERY_R_TOP_OHM + BATTERY_R_BOTTOM_OHM) /
BATTERY_R_BOTTOM_OHM;
if (battery_mv <= BATTERY_EMPTY_MV) {
return 0;
}
if (battery_mv >= BATTERY_FULL_MV) {
return 100;
}
return (battery_mv - BATTERY_EMPTY_MV) * 100 /
(BATTERY_FULL_MV - BATTERY_EMPTY_MV);
}
3.5 ESP32S3 的 main 核心函数代码
作者代码的 main 函数使用了裸机框架,只做了层调度,LCD/相机/SD/电池各自在独立模块里。启动流程 (L115-L154):打印 banner → LCD 初始化并显示 ikun logo 1.5 秒 → 相机初始化(失败每秒重试)→ 电池 → 按键 → SD 卡 → 打印内存;主循环 (L171-L267)每轮五件事:清 Toast → 轮询 KEY2 → 取帧并加上电池图标写屏 → 处理 KEY1 → 每 5 秒采样电池。
KEY2 暂停 :不取帧,画面定格;同时同步 KEY1 电平,防止恢复时误触发拍照。
KEY1 拍照 :卸载 SD(腾内存)→ 抓 1200×1600 JPEG → 重挂 SD → 加 EXIF 方向写卡 → 显示 "Photo Storage Success" → 恢复预览。
容错 :相机初始化、预览恢复都会无限重试;电池/预览失败只警告;取帧失败退避 10ms。

cpp
/**
* @file main.c
* @brief ikun_camera application entry: preview, photo capture, battery UI.
*
* This file only owns the top-level flow. The LCD, camera, microSD storage
* and battery handling live in their own modules (lcd_ili9341.c,
* camera_app.c, sd_storage.c, battery.c).
*/
#include <stdio.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_err.h"
#include "esp_log.h"
#include "esp_camera.h"
#include "lcd_ili9341.h"
#include "ikun_image.h"
#include "driver/gpio.h"
#include "esp_heap_caps.h"
#include "battery.h"
#include "camera_app.h"
#include "sd_storage.h"
static const char *TAG = "ikun_camera";
/**
* @defgroup battery_icon Battery icon placement
* @brief The level itself is sampled by the battery module (battery.c).
* @{
*/
#define BATTERY_ICON_X (LCD_WIDTH - 36) /**< 30 px icon, 6 px margin */
#define BATTERY_ICON_Y 6
/** @} */
/**
* @defgroup user_keys User push buttons
* @brief Both keys are active-low and use the internal pull-up.
*
* KEY1 takes a full-resolution JPEG photo on the microSD card (see
* camera_app.c and sd_storage.c); KEY2 pauses and resumes the live preview.
* @{
*/
#define KEY1_PIN 47
#define KEY2_PIN 48
/** @} */
/**
* @defgroup photo_toast Photo save confirmation
* @brief Short message shown on the frozen preview after a successful save.
* @{
*/
#define PHOTO_TOAST_TEXT "Photo Storage Success"
/** @brief Text width in pixels: 8 px per ASCII character. */
#define PHOTO_TOAST_WIDTH ((int)(sizeof(PHOTO_TOAST_TEXT) - 1) * 8)
#define PHOTO_TOAST_X ((LCD_WIDTH - PHOTO_TOAST_WIDTH) / 2)
#define PHOTO_TOAST_Y ((LCD_HEIGHT - 16) / 2)
/** @brief How long the message stays on screen, in milliseconds. */
#define PHOTO_TOAST_MS 1200
/** @} */
/**
* @brief Configure a push button as an input with the internal pull-up.
*/
static void button_init(gpio_num_t pin)
{
gpio_config_t io = {
.pin_bit_mask = 1ULL << pin,
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_ENABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE,
};
gpio_config(&io);
}
/**
* @brief Non-blocking falling-edge detection with a 300 ms lockout.
*
* @param[in] pin GPIO to poll.
* @param[in,out] last_level Previous sampled level.
* @param[in,out] last_trigger Tick of the previous accepted press.
*/
static bool button_pressed_edge(gpio_num_t pin, bool *last_level,
TickType_t *last_trigger)
{
bool level = gpio_get_level(pin) != 0;
bool pressed = false;
if (*last_level && !level) {
TickType_t now = xTaskGetTickCount();
if (now - *last_trigger > pdMS_TO_TICKS(300)) {
pressed = true;
*last_trigger = now;
}
}
*last_level = level;
return pressed;
}
/**
* @brief Application main entry point.
*
* Brings up the panel and the boot logo, starts the camera preview and the
* battery monitor, then runs one cooperative loop that:
* 1. draws the latest QVGA frame with the battery icon composited into it,
* 2. pauses and resumes the preview on KEY2,
* 3. captures a full-resolution JPEG on KEY1, saves it to the microSD card
* and shows a short confirmation, and
* 4. re-samples the battery every BATTERY_REFRESH_MS.
*
* The card is mounted at startup. Before each picture it is unmounted so
* the JPEG buffer can use the FAT memory, then remounted for the write.
*/
void app_main(void)
{
/* ikun_camera */
printf("ikun_camera!\n");
printf("author: Sneaker\n");
/* Initialize the LCD and show the ikun image centered on screen */
lcd_init();
fill_screen(0x0000); /* black background */
/* gImage_ikun_image is 120x120 (from its 8-byte Image2Lcd header):
* center on the 320x240 panel at (100, 60) */
esp_err_t err = lcd_draw_image2lcd_180(100, 60, gImage_ikun_image, 120, 120);
printf("Draw ikun image: %s\n", esp_err_to_name(err));
/* Keep the boot logo visible for a moment before starting preview */
vTaskDelay(pdMS_TO_TICKS(1500));
/* Initialize the camera; keep retrying so a loose FPC is recoverable */
while (camera_app_init() != ESP_OK) {
ESP_LOGW(TAG, "Retrying camera init...");
vTaskDelay(pdMS_TO_TICKS(1000));
}
ESP_LOGI(TAG, "Camera ready, starting preview");
if (battery_init() != ESP_OK) {
ESP_LOGW(TAG, "Battery monitor disabled");
}
button_init(KEY1_PIN);
button_init(KEY2_PIN);
if (sd_storage_init() != ESP_OK) {
ESP_LOGW(TAG, "SD card unavailable, photo capture disabled");
}
ESP_LOGI(TAG, "Internal RAM free %u KB, largest block %u KB",
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_INTERNAL |
MALLOC_CAP_8BIT) / 1024),
(unsigned)(heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL |
MALLOC_CAP_8BIT) / 1024));
/* Preview loop: rotate the camera frame to match the landscape view,
* then cover-crop it to fill the 320x240 panel. The boot image and LCD
* initialization remain unchanged. KEY2 freezes the last frame on the
* panel until it is pressed again. */
bool fb_info_logged = false;
int battery_level = 0;
TickType_t battery_next_ticks = 0;
bool paused = false;
bool toast_active = false;
TickType_t toast_until = 0;
bool key1_last = true;
TickType_t key1_last_ticks = 0;
bool key2_last = true;
TickType_t key2_last_ticks = 0;
while (1) {
if (toast_active && xTaskGetTickCount() >= toast_until) {
lcd_frame_text_hide();
toast_active = false;
}
if (button_pressed_edge(KEY2_PIN, &key2_last, &key2_last_ticks)) {
paused = !paused;
ESP_LOGI(TAG, "Preview %s", paused ? "paused" : "resumed");
}
if (paused) {
/* Keep the last frame on the panel. Track KEY1 so resuming does
* not fire a stale photo. */
key1_last = gpio_get_level(KEY1_PIN) != 0;
vTaskDelay(pdMS_TO_TICKS(20));
continue;
}
camera_fb_t *fb = esp_camera_fb_get();
if (fb) {
if (!fb_info_logged) {
ESP_LOGI(TAG, "fb %ux%u len=%u", fb->width, fb->height,
(unsigned)fb->len);
fb_info_logged = true;
}
lcd_battery_overlay_t battery = {
.x = BATTERY_ICON_X,
.y = BATTERY_ICON_Y,
.level = battery_level,
};
lcd_write_frame_upright(fb->buf, fb->len, fb->width, fb->height,
&battery, NULL);
esp_camera_fb_return(fb);
/* KEY1 takes one picture at the sensor's full resolution. The
* preview is stopped during the capture, so the preview frame
* above must be returned before the sensor is reconfigured. */
if (button_pressed_edge(KEY1_PIN, &key1_last, &key1_last_ticks)) {
ESP_LOGI(TAG, "KEY1 pressed, capturing full-resolution photo");
/* Unmount the card first: the FAT state otherwise occupies
* RAM that the JPEG frame buffer needs. It is mounted again
* right after the capture, before the file is written. */
sd_storage_unmount();
camera_fb_t *still = camera_app_capture_still();
if (still != NULL) {
esp_err_t save_err = sd_storage_init();
if (save_err == ESP_OK) {
save_err = sd_storage_save_jpeg(still->buf, still->len);
} else {
ESP_LOGE(TAG, "SD remount failed: %s",
esp_err_to_name(save_err));
}
esp_camera_fb_return(still);
if (save_err == ESP_OK) {
/* Composite the confirmation into the live preview
* frames for a short while; only the glyph pixels
* are replaced, so the text has no background. */
lcd_frame_text_show(PHOTO_TOAST_X, PHOTO_TOAST_Y,
0x07E0,
PHOTO_TOAST_TEXT);
toast_active = true;
toast_until = xTaskGetTickCount() +
pdMS_TO_TICKS(PHOTO_TOAST_MS);
} else {
ESP_LOGE(TAG, "Saving photo failed: %s",
esp_err_to_name(save_err));
}
} else {
ESP_LOGE(TAG, "Full-resolution capture failed");
}
/* Bring the QVGA RGB565 preview back. */
while (camera_app_resume_preview() != ESP_OK) {
ESP_LOGW(TAG, "Retrying preview init...");
vTaskDelay(pdMS_TO_TICKS(1000));
}
fb_info_logged = false;
}
/* Re-sample the battery at a slow, fixed interval. The icon is
* composited into every frame, so it never blinks. */
TickType_t now_ticks = xTaskGetTickCount();
if (now_ticks >= battery_next_ticks) {
int level = battery_read_level();
if (level >= 0) {
battery_level = level;
}
battery_next_ticks = now_ticks +
pdMS_TO_TICKS(BATTERY_REFRESH_MS);
}
} else {
ESP_LOGW(TAG, "Frame capture failed");
vTaskDelay(pdMS_TO_TICKS(10));
}
}
}
四、项目演示
1、ikun Camera LCD 画面:

2、ikun Camera 拍摄 SD 卡存储:

3、ikun Camera 电池电量采集:

五、代码开源
代码地址: 基于ESP32S3与OV5640的自制DIY相机项目资料资源-CSDN下载
如果积分不够的朋友,点波关注,评论区留下邮箱,作者无偿提供源码和后续问题解答。求求啦关注一波吧 !!!