update: added support for IMU and Lottie JSON

This commit is contained in:
2026-01-24 13:50:49 +05:30
parent ecf234efa5
commit 2c731c72e3
868 changed files with 318873 additions and 894 deletions

View File

@@ -1,6 +1,7 @@
idf_component_register(
SRCS "example_qspi_with_ram.c" "splash_screen.c" "animated_eyes.c" "animated_eyes_demo.c"
INCLUDE_DIRS ".")
SRCS "blink_animation.c" "lottie_player.c" "example_qspi_with_ram.c" "splash_screen.c" "animated_eyes.c" "animated_eyes_demo.c" "shake_detector.cpp"
INCLUDE_DIRS "."
REQUIRES SensorLib json)
set_source_files_properties(
${LV_DEMOS_SOURCES}

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,12 @@
/**
* @file animated_eyes.h
* @brief Animated expressive eyes for LVGL displays
*
*
* Ported from esp32-eyes (https://github.com/playfultechnology/esp32-eyes)
* Original Copyright (c) 2020 Luis Llamas, 2023 Alastair Aitchison
* LVGL port for ESP-IDF
*
* This program is free software: you can redistribute it and/or modify it
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License.
*/
@@ -25,143 +25,197 @@ extern "C" {
* @brief Available emotions for the animated face
*/
typedef enum {
EMOTION_NORMAL = 0,
EMOTION_ANGRY,
EMOTION_GLEE,
EMOTION_HAPPY,
EMOTION_SAD,
EMOTION_WORRIED,
EMOTION_FOCUSED,
EMOTION_ANNOYED,
EMOTION_SURPRISED,
EMOTION_SKEPTIC,
EMOTION_FRUSTRATED,
EMOTION_UNIMPRESSED,
EMOTION_SLEEPY,
EMOTION_SUSPICIOUS,
EMOTION_SQUINT,
EMOTION_FURIOUS,
EMOTION_SCARED,
EMOTION_AWE,
EMOTION_COUNT
EMOTION_NORMAL = 0,
EMOTION_ANGRY,
EMOTION_GLEE,
EMOTION_HAPPY,
EMOTION_SAD,
EMOTION_WORRIED,
EMOTION_FOCUSED,
EMOTION_ANNOYED,
EMOTION_SURPRISED,
EMOTION_SKEPTIC,
EMOTION_FRUSTRATED,
EMOTION_UNIMPRESSED,
EMOTION_SLEEPY,
EMOTION_SUSPICIOUS,
EMOTION_SQUINT,
EMOTION_FURIOUS,
EMOTION_SCARED,
EMOTION_AWE,
EMOTION_COUNT
} animated_eyes_emotion_t;
/**
* @brief Configuration for animated eyes
*/
typedef struct {
uint16_t screen_width; /**< Screen width in pixels */
uint16_t screen_height; /**< Screen height in pixels */
uint16_t eye_size; /**< Base eye size (will be scaled) */
uint16_t eye_spacing; /**< Distance between eyes */
lv_color_t eye_color; /**< Color of the eyes */
lv_color_t bg_color; /**< Background color */
bool random_behavior; /**< Enable random emotion changes */
bool random_look; /**< Enable random look-around */
bool random_blink; /**< Enable random blinking */
uint32_t behavior_interval; /**< Interval for behavior changes (ms) */
uint32_t look_interval; /**< Interval for look changes (ms) */
uint32_t blink_interval; /**< Interval for blinking (ms) */
uint16_t screen_width; /**< Screen width in pixels */
uint16_t screen_height; /**< Screen height in pixels */
uint16_t eye_size; /**< Base eye size (will be scaled) */
uint16_t eye_spacing; /**< Distance between eyes */
lv_color_t eye_color; /**< Color of the eyes */
lv_color_t bg_color; /**< Background color */
bool random_behavior; /**< Enable random emotion changes */
bool random_look; /**< Enable random look-around */
bool random_blink; /**< Enable random blinking */
uint32_t behavior_interval; /**< Interval for behavior changes (ms) */
uint32_t look_interval; /**< Interval for look changes (ms) */
uint32_t blink_interval; /**< Interval for blinking (ms) */
} animated_eyes_config_t;
/**
* @brief Handle for animated eyes instance
*/
typedef struct animated_eyes_t* animated_eyes_handle_t;
typedef struct animated_eyes_t *animated_eyes_handle_t;
/**
* @brief Default configuration macro
*/
#define ANIMATED_EYES_DEFAULT_CONFIG() { \
.screen_width = 368, \
.screen_height = 448, \
.eye_size = 120, \
.eye_spacing = 20, \
.eye_color = lv_color_white(), \
.bg_color = lv_color_black(), \
.random_behavior = true, \
.random_look = true, \
.random_blink = true, \
.behavior_interval = 5000, \
.look_interval = 4000, \
.blink_interval = 3500 \
}
#define ANIMATED_EYES_DEFAULT_CONFIG() \
{.screen_width = 368, \
.screen_height = 448, \
.eye_size = 120, \
.eye_spacing = 20, \
.eye_color = lv_color_white(), \
.bg_color = lv_color_black(), \
.random_behavior = true, \
.random_look = true, \
.random_blink = true, \
.behavior_interval = 5000, \
.look_interval = 4000, \
.blink_interval = 3500}
/**
* @brief Create animated eyes on a parent LVGL object
*
*
* @param parent Parent LVGL object to attach eyes to
* @param config Configuration for the eyes
* @return Handle to the animated eyes instance, or NULL on failure
*/
animated_eyes_handle_t animated_eyes_create(lv_obj_t *parent, const animated_eyes_config_t *config);
animated_eyes_handle_t
animated_eyes_create(lv_obj_t *parent, const animated_eyes_config_t *config);
/**
* @brief Delete animated eyes and free resources
*
*
* @param handle Handle to the animated eyes instance
*/
void animated_eyes_delete(animated_eyes_handle_t handle);
/**
* @brief Update the animated eyes (call this regularly, e.g., every frame)
*
*
* @param handle Handle to the animated eyes instance
*/
void animated_eyes_update(animated_eyes_handle_t handle);
/**
* @brief Trigger a blink animation
*
*
* @param handle Handle to the animated eyes instance
*/
void animated_eyes_blink(animated_eyes_handle_t handle);
/**
* @brief Set the current emotion
*
*
* @param handle Handle to the animated eyes instance
* @param emotion The emotion to set
*/
void animated_eyes_set_emotion(animated_eyes_handle_t handle, animated_eyes_emotion_t emotion);
void animated_eyes_set_emotion(animated_eyes_handle_t handle,
animated_eyes_emotion_t emotion);
/**
* @brief Set a temporary emotion that reverts after a duration
*
* @param handle Handle to the animated eyes instance
* @param emotion The temporary emotion to set
* @param duration_ms Duration in milliseconds before reverting
*/
void animated_eyes_set_temporary_emotion(animated_eyes_handle_t handle,
animated_eyes_emotion_t emotion,
uint32_t duration_ms);
/**
* @brief Get the current emotion
*
*
* @param handle Handle to the animated eyes instance
* @return Current emotion
*/
animated_eyes_emotion_t animated_eyes_get_emotion(animated_eyes_handle_t handle);
animated_eyes_emotion_t
animated_eyes_get_emotion(animated_eyes_handle_t handle);
/**
* @brief Set the emotion probability weight
*
* @brief Set a temporary emotion that reverts after a duration
*
* @param handle Handle to the animated eyes instance
* @param emotion The emotion to set weight for
* @param weight Weight value (0.0 to disable, higher = more likely)
* @param emotion The temporary emotion to set
* @param duration_ms Duration in milliseconds before reverting
*/
void animated_eyes_set_emotion_weight(animated_eyes_handle_t handle, animated_eyes_emotion_t emotion, float weight);
void animated_eyes_set_temporary_emotion(animated_eyes_handle_t handle,
animated_eyes_emotion_t emotion,
uint32_t duration_ms);
/**
* @brief Make the eyes look in a specific direction
*
* @param handle Handle to the animated eyes instance
* @param x Horizontal direction (-1.0 = left, 0.0 = center, 1.0 = right)
* @param y Vertical direction (-1.0 = down, 0.0 = center, 1.0 = up)
* @brief Apply an inertia-based offset
* to the eyes
*
* @param handle Handle to the animated
* eyes instance
* @param intensity_x Intensity of the
* shake X component (G-force)
* @param intensity_y Intensity of the
* shake Y component (G-force)
*/
void animated_eyes_shake_inertia(animated_eyes_handle_t handle,
float intensity_x, float intensity_y);
/**
* @brief Set the emotion probability
* weight
*
* @param handle Handle to the animated
* eyes instance
* @param emotion The emotion to set
* weight for
* @param weight Weight value (0.0 to
* disable, higher = more likely)
*/
void animated_eyes_set_emotion_weight(animated_eyes_handle_t handle,
animated_eyes_emotion_t emotion,
float weight);
/**
* @brief Make the eyes look in a
* specific direction
*
* @param handle Handle to the animated
* eyes instance
* @param x Horizontal direction (-1.0
* = left, 0.0 = center, 1.0 = right)
* @param y Vertical direction (-1.0 =
* down, 0.0 = center, 1.0 = up)
*/
void animated_eyes_look_at(animated_eyes_handle_t handle, float x, float y);
/**
* @brief Make the eyes look at a screen position
*
* @param handle Handle to the animated eyes instance
* @param screen_x X coordinate on screen
* @param screen_y Y coordinate on screen
* @brief Make the eyes look at a
* screen position
*
* @param handle Handle to the animated
* eyes instance
* @param screen_x X coordinate on
* screen
* @param screen_y Y coordinate on
* screen
*/
void animated_eyes_look_at_point(animated_eyes_handle_t handle, int16_t screen_x, int16_t screen_y);
void animated_eyes_look_at_point(animated_eyes_handle_t handle,
int16_t screen_x, int16_t screen_y);
/**
* @brief Convenience methods for common look directions
* @brief Convenience methods for
* common look directions
*/
void animated_eyes_look_left(animated_eyes_handle_t handle);
void animated_eyes_look_right(animated_eyes_handle_t handle);
@@ -170,30 +224,38 @@ void animated_eyes_look_down(animated_eyes_handle_t handle);
void animated_eyes_look_center(animated_eyes_handle_t handle);
/**
* @brief Enable or disable random behaviors
*
* @param handle Handle to the animated eyes instance
* @param behavior Enable random emotion changes
* @param look Enable random looking around
* @brief Enable or disable random
* behaviors
*
* @param handle Handle to the animated
* eyes instance
* @param behavior Enable random
* emotion changes
* @param look Enable random looking
* around
* @param blink Enable random blinking
*/
void animated_eyes_set_random(animated_eyes_handle_t handle, bool behavior, bool look, bool blink);
void animated_eyes_set_random(animated_eyes_handle_t handle, bool behavior,
bool look, bool blink);
/**
* @brief Set the eye color
*
* @param handle Handle to the animated eyes instance
*
* @param handle Handle to the animated
* eyes instance
* @param color New eye color
*/
void animated_eyes_set_color(animated_eyes_handle_t handle, lv_color_t color);
/**
* @brief Set the background color
*
* @param handle Handle to the animated eyes instance
*
* @param handle Handle to the animated
* eyes instance
* @param color New background color
*/
void animated_eyes_set_bg_color(animated_eyes_handle_t handle, lv_color_t color);
void animated_eyes_set_bg_color(animated_eyes_handle_t handle,
lv_color_t color);
#ifdef __cplusplus
}

View File

@@ -10,101 +10,75 @@
static const char *TAG = "eyes_demo";
static lv_timer_t *update_timer = NULL;
static lv_timer_t *emotion_timer = NULL;
static animated_eyes_handle_t eyes_handle = NULL;
static int current_emotion_idx = 0;
static const char *emotion_names[] = {
"NORMAL", "ANGRY", "GLEE", "HAPPY", "SAD", "WORRIED",
"FOCUSED", "ANNOYED", "SURPRISED", "SKEPTIC", "FRUSTRATED",
"UNIMPRESSED", "SLEEPY", "SUSPICIOUS", "SQUINT", "FURIOUS",
"SCARED", "AWE"
};
// Timer callback for updating eyes
static void update_timer_callback(lv_timer_t *timer) {
if (eyes_handle) {
animated_eyes_update(eyes_handle);
}
}
// Timer callback for cycling emotions
static void emotion_timer_callback(lv_timer_t *timer) {
if (eyes_handle) {
current_emotion_idx = (current_emotion_idx + 1) % EMOTION_COUNT;
animated_eyes_emotion_t next_emotion = (animated_eyes_emotion_t)current_emotion_idx;
ESP_LOGI(TAG, "Switching emotion to: %s", emotion_names[next_emotion]);
animated_eyes_set_emotion(eyes_handle, next_emotion);
}
if (eyes_handle) {
animated_eyes_update(eyes_handle);
}
}
animated_eyes_handle_t animated_eyes_demo_start(void) {
ESP_LOGI(TAG, "Starting animated eyes demo");
// Get the active screen
lv_obj_t *scr = lv_scr_act();
// Set black background
lv_obj_set_style_bg_color(scr, lv_color_black(), 0);
lv_obj_set_style_bg_opa(scr, LV_OPA_COVER, 0);
// Configure and create animated eyes
animated_eyes_config_t config = ANIMATED_EYES_DEFAULT_CONFIG();
// Customize for your screen (368x448)
config.screen_width = 368;
config.screen_height = 448;
config.eye_size = 120; // Larger eyes to fill the screen better
config.eye_spacing = 20; // Closer together
config.eye_color = lv_color_white();
config.bg_color = lv_color_black();
// Disable random movements for stability
config.random_behavior = false;
config.random_look = false;
config.random_blink = true; // Keep blinking for life
// Timing settings (unused when random features disabled, but kept for reference)
config.behavior_interval = 6000;
config.look_interval = 3000;
config.blink_interval = 4000;
eyes_handle = animated_eyes_create(scr, &config);
if (!eyes_handle) {
ESP_LOGE(TAG, "Failed to create animated eyes");
return NULL;
}
// Reset emotion index
current_emotion_idx = 0;
// Create timers
// 1. Update timer: 33ms (approx 30 FPS) for smooth animation
update_timer = lv_timer_create(update_timer_callback, 33, NULL);
// 2. Emotion cycle timer: 4000ms (4 seconds) to switch emotions
emotion_timer = lv_timer_create(emotion_timer_callback, 4000, NULL);
ESP_LOGI(TAG, "Animated eyes started successfully");
return eyes_handle;
ESP_LOGI(TAG, "Starting animated eyes demo");
// Get the active screen
lv_obj_t *scr = lv_scr_act();
// Set black background
lv_obj_set_style_bg_color(scr, lv_color_black(), 0);
lv_obj_set_style_bg_opa(scr, LV_OPA_COVER, 0);
// Configure and create animated eyes
animated_eyes_config_t config = ANIMATED_EYES_DEFAULT_CONFIG();
// Customize for your screen (368x448)
config.screen_width = 368;
config.screen_height = 448;
config.eye_size = 120; // Larger eyes to fill the screen better
config.eye_spacing = 20; // Closer together
config.eye_color = lv_color_white();
config.bg_color = lv_color_black();
// Disable random movements for stability
config.random_behavior = false;
config.random_look = false;
config.random_blink = true; // Keep blinking for life
// Timing settings (unused when random features disabled, but kept for
// reference)
config.behavior_interval = 6000;
config.look_interval = 3000;
config.blink_interval = 4000;
eyes_handle = animated_eyes_create(scr, &config);
if (!eyes_handle) {
ESP_LOGE(TAG, "Failed to create animated eyes");
return NULL;
}
// Create timers
// 1. Update timer: 33ms (approx 30 FPS) for smooth animation
update_timer = lv_timer_create(update_timer_callback, 33, NULL);
ESP_LOGI(TAG, "Animated eyes started successfully");
return eyes_handle;
}
animated_eyes_handle_t animated_eyes_demo_get_handle(void) {
return eyes_handle;
}
void animated_eyes_demo_stop(animated_eyes_handle_t handle) {
if (update_timer) {
lv_timer_del(update_timer);
update_timer = NULL;
}
if (emotion_timer) {
lv_timer_del(emotion_timer);
emotion_timer = NULL;
}
if (handle) {
animated_eyes_delete(handle);
eyes_handle = NULL;
}
ESP_LOGI(TAG, "Animated eyes demo stopped");
if (update_timer) {
lv_timer_del(update_timer);
update_timer = NULL;
}
if (handle) {
animated_eyes_delete(handle);
eyes_handle = NULL;
}
ESP_LOGI(TAG, "Animated eyes demo stopped");
}

View File

@@ -14,17 +14,24 @@ extern "C" {
/**
* @brief Start the animated eyes demo
*
*
* Creates animated eyes on the current screen and starts
* the animation. Call animated_eyes_demo_stop() to clean up.
*
*
* @return Handle to the animated eyes, or NULL on failure
*/
animated_eyes_handle_t animated_eyes_demo_start(void);
/**
* @brief Get the current animated eyes handle
*
* @return animated_eyes_handle_t Handle or NULL if not started
*/
animated_eyes_handle_t animated_eyes_demo_get_handle(void);
/**
* @brief Stop the animated eyes demo and clean up
*
*
* @param handle Handle returned by animated_eyes_demo_start()
*/
void animated_eyes_demo_stop(animated_eyes_handle_t handle);

173
main/blink_animation.c Normal file
View File

@@ -0,0 +1,173 @@
/**
* @file blink_animation.c
* @brief Embedded blink Lottie animation data
*
* This file contains the blink.json Lottie animation stored as a C string.
* The animation shows two eyes blinking on a 368x448 display at 60fps.
*/
#include <stdint.h>
// Lottie JSON animation data stored in flash
const char blink_animation_data[] =
"{\"fr\":60,\"h\":448,\"ip\":0,\"layers\":["
"{\"ind\":3,\"ty\":4,\"parent\":2,\"ks\":{},\"ip\":0,\"op\":37,\"st\":0,"
"\"shapes\":["
"{\"ty\":\"rc\",\"p\":{\"a\":1,\"k\":["
"{\"t\":0,\"s\":[48.5,68],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":2.952,\"s\":[48.5,13.753],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":5.898,\"s\":[48.5,-2.831],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":11.802,\"s\":[48.5,0.118],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":17.76,\"s\":[48.5,-0.005],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":18,\"s\":[48.5,-0.005],\"h\":1},"
"{\"t\":18,\"s\":[48.5,0],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":20.952,\"s\":[48.5,54.247],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":23.898,\"s\":[48.5,70.831],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":29.802,\"s\":[48.5,67.882],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":35.76,\"s\":[48.5,68.005],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":36,\"s\":[48.5,68.005],\"h\":1}"
"]},\"r\":{\"a\":0,\"k\":20},\"s\":{\"a\":1,\"k\":["
"{\"t\":0,\"s\":[97,136],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":2.952,\"s\":[97,27.505],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":5.898,\"s\":[97,-5.662],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":11.802,\"s\":[97,0.236],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":17.76,\"s\":[97,-0.01],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":18,\"s\":[97,-0.01],\"h\":1},"
"{\"t\":18,\"s\":[97,0],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":20.952,\"s\":[97,108.495],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":23.898,\"s\":[97,141.662],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":29.802,\"s\":[97,135.764],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":35.76,\"s\":[97,136.01],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":36,\"s\":[97,136.01],\"h\":1}"
"]}},"
"{\"ty\":\"fl\",\"c\":{\"a\":0,\"k\":[1,1,1]},\"o\":{\"a\":0,\"k\":100}}"
"]},"
"{\"ind\":2,\"ty\":3,\"parent\":1,\"ks\":{\"p\":{\"a\":1,\"k\":["
"{\"t\":0,\"s\":[211,88],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":2.952,\"s\":[211,142.247],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":5.898,\"s\":[211,158.831],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":11.802,\"s\":[211,155.882],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":17.76,\"s\":[211,156.005],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":18,\"s\":[211,156.005],\"h\":1},"
"{\"t\":18,\"s\":[211,156],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":20.952,\"s\":[211,101.753],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":23.898,\"s\":[211,85.169],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":29.802,\"s\":[211,88.118],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":35.76,\"s\":[211,87.995],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":36,\"s\":[211,87.995],\"h\":1}"
"]}},\"ip\":0,\"op\":37,\"st\":0},"
"{\"ind\":5,\"ty\":4,\"parent\":4,\"ks\":{},\"ip\":0,\"op\":37,\"st\":0,"
"\"shapes\":["
"{\"ty\":\"rc\",\"p\":{\"a\":1,\"k\":["
"{\"t\":0,\"s\":[48.5,66],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":2.952,\"s\":[48.5,13.348],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":5.898,\"s\":[48.5,-2.748],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":11.802,\"s\":[48.5,0.114],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":17.76,\"s\":[48.5,-0.005],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":18,\"s\":[48.5,-0.005],\"h\":1},"
"{\"t\":18,\"s\":[48.5,0],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":20.952,\"s\":[48.5,54.247],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":23.898,\"s\":[48.5,70.831],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":29.802,\"s\":[48.5,67.882],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":35.76,\"s\":[48.5,68.005],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":36,\"s\":[48.5,68.005],\"h\":1}"
"]},\"r\":{\"a\":0,\"k\":20},\"s\":{\"a\":1,\"k\":["
"{\"t\":0,\"s\":[97,132],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":2.952,\"s\":[97,26.696],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":5.898,\"s\":[97,-5.496],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":11.802,\"s\":[97,0.229],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":17.76,\"s\":[97,-0.01],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":18,\"s\":[97,-0.009],\"h\":1},"
"{\"t\":18,\"s\":[97,0],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":20.952,\"s\":[97,108.495],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":23.898,\"s\":[97,141.662],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":29.802,\"s\":[97,135.764],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":35.76,\"s\":[97,136.01],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":36,\"s\":[97,136.01],\"h\":1}"
"]}},"
"{\"ty\":\"fl\",\"c\":{\"a\":0,\"k\":[1,1,1]},\"o\":{\"a\":0,\"k\":100}}"
"]},"
"{\"ind\":4,\"ty\":3,\"parent\":1,\"ks\":{\"a\":{\"a\":1,\"k\":["
"{\"t\":0,\"s\":[48.5,66],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":2.952,\"s\":[48.5,13.348],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":5.898,\"s\":[48.5,-2.748],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":11.802,\"s\":[48.5,0.114],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":17.76,\"s\":[48.5,-0.005],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":18,\"s\":[48.5,-0.005],\"h\":1},"
"{\"t\":18,\"s\":[48.5,0],\"i\":{\"x\":[1,0.537],\"y\":[1,0.625]},\"o\":{"
"\"x\":[0,0.283],\"y\":[0,0.035]}},"
"{\"t\":20.952,\"s\":[48.5,54.247],\"i\":{\"x\":[1,0.69],\"y\":[1,0.998]},"
"\"o\":{\"x\":[0,0.343],\"y\":[0,0.908]}},"
"{\"t\":23.898,\"s\":[48.5,70.831],\"i\":{\"x\":[1,0.282],\"y\":[1,0.996]},"
"\"o\":{\"x\":[0,0.262],\"y\":[0,0.033]}},"
"{\"t\":29.802,\"s\":[48.5,67.882],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":35.76,\"s\":[48.5,68.005],\"i\":{\"x\":[1,1],\"y\":[1,1]},\"o\":{"
"\"x\":[0,0],\"y\":[0,0]}},"
"{\"t\":36,\"s\":[48.5,68.005],\"h\":1}"
"]},\"p\":{\"a\":0,\"k\":[108.5,157]}},\"ip\":0,\"op\":37,\"st\":0},"
"{\"ind\":1,\"ty\":3,\"parent\":0,\"ks\":{},\"ip\":0,\"op\":37,\"st\":0},"
"{\"ind\":6,\"ty\":4,\"parent\":0,\"ks\":{},\"ip\":0,\"op\":37,\"st\":0,"
"\"shapes\":["
"{\"ty\":\"rc\",\"p\":{\"a\":0,\"k\":[184,224]},\"r\":{\"a\":0,\"k\":0},"
"\"s\":{\"a\":0,\"k\":[368,448]}},"
"{\"ty\":\"fl\",\"c\":{\"a\":0,\"k\":[0,0,0]},\"o\":{\"a\":0,\"k\":100}}"
"]},"
"{\"ind\":0,\"ty\":3,\"ks\":{},\"ip\":0,\"op\":37,\"st\":0}"
"],\"meta\":{\"g\":\"https://"
"jitter.video\"},\"op\":36,\"v\":\"5.7.4\",\"w\":368}";

View File

@@ -1,24 +1,27 @@
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "driver/i2c.h"
#include "driver/spi_master.h"
#include "esp_timer.h"
#include "esp_lcd_panel_io.h"
#include "esp_lcd_panel_vendor.h"
#include "esp_lcd_panel_ops.h"
#include "esp_err.h"
#include "esp_lcd_panel_io.h"
#include "esp_lcd_panel_ops.h"
#include "esp_lcd_panel_vendor.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <math.h>
#include "lvgl.h"
#include "animated_eyes_demo.h"
#include "esp_lcd_sh8601.h"
#include "esp_lcd_touch_ft5x06.h"
#include "lottie_player.h"
#include "lvgl.h"
#include "esp_io_expander_tca9554.h"
#include "shake_detector.h"
#include "splash_screen.h"
static const char *TAG = "example";
@@ -34,7 +37,8 @@ static SemaphoreHandle_t lvgl_mux = NULL;
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// Please update the following configuration according to your LCD spec //////////////////////////////
//////////////////// Please update the following configuration according to your
/// LCD spec //////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define EXAMPLE_LCD_BK_LIGHT_ON_LEVEL 1
#define EXAMPLE_LCD_BK_LIGHT_OFF_LEVEL !EXAMPLE_LCD_BK_LIGHT_ON_LEVEL
@@ -81,331 +85,353 @@ static const sh8601_lcd_init_cmd_t lcd_init_cmds[] = {
{0x51, (uint8_t[]){0xFF}, 1, 0},
};
static bool example_notify_lvgl_flush_ready(esp_lcd_panel_io_handle_t panel_io, esp_lcd_panel_io_event_data_t *edata, void *user_ctx)
{
lv_disp_drv_t *disp_driver = (lv_disp_drv_t *)user_ctx;
lv_disp_flush_ready(disp_driver);
return false;
static bool
example_notify_lvgl_flush_ready(esp_lcd_panel_io_handle_t panel_io,
esp_lcd_panel_io_event_data_t *edata,
void *user_ctx) {
lv_disp_drv_t *disp_driver = (lv_disp_drv_t *)user_ctx;
lv_disp_flush_ready(disp_driver);
return false;
}
static void example_lvgl_flush_cb(lv_disp_drv_t *drv, const lv_area_t *area, lv_color_t *color_map)
{
esp_lcd_panel_handle_t panel_handle = (esp_lcd_panel_handle_t)drv->user_data;
const int offsetx1 = area->x1;
const int offsetx2 = area->x2;
const int offsety1 = area->y1;
const int offsety2 = area->y2;
static void example_lvgl_flush_cb(lv_disp_drv_t *drv, const lv_area_t *area,
lv_color_t *color_map) {
esp_lcd_panel_handle_t panel_handle = (esp_lcd_panel_handle_t)drv->user_data;
const int offsetx1 = area->x1;
const int offsetx2 = area->x2;
const int offsety1 = area->y1;
const int offsety2 = area->y2;
#if LCD_BIT_PER_PIXEL == 24
uint8_t *to = (uint8_t *)color_map;
uint8_t temp = 0;
uint16_t pixel_num = (offsetx2 - offsetx1 + 1) * (offsety2 - offsety1 + 1);
uint8_t *to = (uint8_t *)color_map;
uint8_t temp = 0;
uint16_t pixel_num = (offsetx2 - offsetx1 + 1) * (offsety2 - offsety1 + 1);
// Special dealing for first pixel
temp = color_map[0].ch.blue;
*to++ = color_map[0].ch.red;
*to++ = color_map[0].ch.green;
*to++ = temp;
// Normal dealing for other pixels
for (int i = 1; i < pixel_num; i++)
{
*to++ = color_map[i].ch.red;
*to++ = color_map[i].ch.green;
*to++ = color_map[i].ch.blue;
}
// Special dealing for first pixel
temp = color_map[0].ch.blue;
*to++ = color_map[0].ch.red;
*to++ = color_map[0].ch.green;
*to++ = temp;
// Normal dealing for other pixels
for (int i = 1; i < pixel_num; i++) {
*to++ = color_map[i].ch.red;
*to++ = color_map[i].ch.green;
*to++ = color_map[i].ch.blue;
}
#endif
// copy a buffer's content to a specific area of the display
esp_lcd_panel_draw_bitmap(panel_handle, offsetx1, offsety1, offsetx2 + 1, offsety2 + 1, color_map);
// copy a buffer's content to a specific area of the display
esp_lcd_panel_draw_bitmap(panel_handle, offsetx1, offsety1, offsetx2 + 1,
offsety2 + 1, color_map);
}
/* Rotate display and touch, when rotated screen in LVGL. Called when driver parameters are updated. */
static void example_lvgl_update_cb(lv_disp_drv_t *drv)
{
esp_lcd_panel_handle_t panel_handle = (esp_lcd_panel_handle_t)drv->user_data;
/* Rotate display and touch, when rotated screen in LVGL. Called when driver
* parameters are updated. */
static void example_lvgl_update_cb(lv_disp_drv_t *drv) {
esp_lcd_panel_handle_t panel_handle = (esp_lcd_panel_handle_t)drv->user_data;
switch (drv->rotated)
{
case LV_DISP_ROT_NONE:
// Rotate LCD display
esp_lcd_panel_swap_xy(panel_handle, false);
esp_lcd_panel_mirror(panel_handle, true, false);
break;
case LV_DISP_ROT_90:
// Rotate LCD display
esp_lcd_panel_swap_xy(panel_handle, true);
esp_lcd_panel_mirror(panel_handle, true, true);
break;
case LV_DISP_ROT_180:
// Rotate LCD display
esp_lcd_panel_swap_xy(panel_handle, false);
esp_lcd_panel_mirror(panel_handle, false, true);
break;
case LV_DISP_ROT_270:
// Rotate LCD display
esp_lcd_panel_swap_xy(panel_handle, true);
esp_lcd_panel_mirror(panel_handle, false, false);
break;
}
switch (drv->rotated) {
case LV_DISP_ROT_NONE:
// Rotate LCD display
esp_lcd_panel_swap_xy(panel_handle, false);
esp_lcd_panel_mirror(panel_handle, true, false);
break;
case LV_DISP_ROT_90:
// Rotate LCD display
esp_lcd_panel_swap_xy(panel_handle, true);
esp_lcd_panel_mirror(panel_handle, true, true);
break;
case LV_DISP_ROT_180:
// Rotate LCD display
esp_lcd_panel_swap_xy(panel_handle, false);
esp_lcd_panel_mirror(panel_handle, false, true);
break;
case LV_DISP_ROT_270:
// Rotate LCD display
esp_lcd_panel_swap_xy(panel_handle, true);
esp_lcd_panel_mirror(panel_handle, false, false);
break;
}
}
void example_lvgl_rounder_cb(struct _lv_disp_drv_t *disp_drv, lv_area_t *area)
{
uint16_t x1 = area->x1;
uint16_t x2 = area->x2;
void example_lvgl_rounder_cb(struct _lv_disp_drv_t *disp_drv, lv_area_t *area) {
uint16_t x1 = area->x1;
uint16_t x2 = area->x2;
uint16_t y1 = area->y1;
uint16_t y2 = area->y2;
uint16_t y1 = area->y1;
uint16_t y2 = area->y2;
// round the start of coordinate down to the nearest 2M number
area->x1 = (x1 >> 1) << 1;
area->y1 = (y1 >> 1) << 1;
// round the end of coordinate up to the nearest 2N+1 number
area->x2 = ((x2 >> 1) << 1) + 1;
area->y2 = ((y2 >> 1) << 1) + 1;
// round the start of coordinate down to the nearest 2M number
area->x1 = (x1 >> 1) << 1;
area->y1 = (y1 >> 1) << 1;
// round the end of coordinate up to the nearest 2N+1 number
area->x2 = ((x2 >> 1) << 1) + 1;
area->y2 = ((y2 >> 1) << 1) + 1;
}
#if EXAMPLE_USE_TOUCH
static void example_lvgl_touch_cb(lv_indev_drv_t *drv, lv_indev_data_t *data)
{
esp_lcd_touch_handle_t tp = (esp_lcd_touch_handle_t)drv->user_data;
assert(tp);
static void example_lvgl_touch_cb(lv_indev_drv_t *drv, lv_indev_data_t *data) {
esp_lcd_touch_handle_t tp = (esp_lcd_touch_handle_t)drv->user_data;
assert(tp);
uint16_t tp_x;
uint16_t tp_y;
uint8_t tp_cnt = 0;
/* Read data from touch controller into memory */
esp_lcd_touch_read_data(tp);
/* Read data from touch controller */
bool tp_pressed = esp_lcd_touch_get_coordinates(tp, &tp_x, &tp_y, NULL, &tp_cnt, 1);
if (tp_pressed && tp_cnt > 0)
{
data->point.x = tp_x;
data->point.y = tp_y;
data->state = LV_INDEV_STATE_PRESSED;
ESP_LOGD(TAG, "Touch position: %d,%d", tp_x, tp_y);
}
else
{
data->state = LV_INDEV_STATE_RELEASED;
}
uint16_t tp_x;
uint16_t tp_y;
uint8_t tp_cnt = 0;
/* Read data from touch controller into memory */
esp_lcd_touch_read_data(tp);
/* Read data from touch controller */
bool tp_pressed =
esp_lcd_touch_get_coordinates(tp, &tp_x, &tp_y, NULL, &tp_cnt, 1);
if (tp_pressed && tp_cnt > 0) {
data->point.x = tp_x;
data->point.y = tp_y;
data->state = LV_INDEV_STATE_PRESSED;
ESP_LOGD(TAG, "Touch position: %d,%d", tp_x, tp_y);
} else {
data->state = LV_INDEV_STATE_RELEASED;
}
}
#endif
static void example_increase_lvgl_tick(void *arg)
{
/* Tell LVGL how many milliseconds has elapsed */
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
static void example_increase_lvgl_tick(void *arg) {
/* Tell LVGL how many milliseconds has elapsed */
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
}
static bool example_lvgl_lock(int timeout_ms)
{
assert(lvgl_mux && "bsp_display_start must be called first");
static bool example_lvgl_lock(int timeout_ms) {
assert(lvgl_mux && "bsp_display_start must be called first");
const TickType_t timeout_ticks = (timeout_ms == -1) ? portMAX_DELAY : pdMS_TO_TICKS(timeout_ms);
return xSemaphoreTake(lvgl_mux, timeout_ticks) == pdTRUE;
const TickType_t timeout_ticks =
(timeout_ms == -1) ? portMAX_DELAY : pdMS_TO_TICKS(timeout_ms);
return xSemaphoreTake(lvgl_mux, timeout_ticks) == pdTRUE;
}
static void example_lvgl_unlock(void)
{
assert(lvgl_mux && "bsp_display_start must be called first");
xSemaphoreGive(lvgl_mux);
static void example_lvgl_unlock(void) {
assert(lvgl_mux && "bsp_display_start must be called first");
xSemaphoreGive(lvgl_mux);
}
static void example_lvgl_port_task(void *arg)
{
ESP_LOGI(TAG, "Starting LVGL task");
uint32_t task_delay_ms = EXAMPLE_LVGL_TASK_MAX_DELAY_MS;
while (1)
{
// Lock the mutex due to the LVGL APIs are not thread-safe
if (example_lvgl_lock(-1))
{
task_delay_ms = lv_timer_handler();
// Release the mutex
example_lvgl_unlock();
}
if (task_delay_ms > EXAMPLE_LVGL_TASK_MAX_DELAY_MS)
{
task_delay_ms = EXAMPLE_LVGL_TASK_MAX_DELAY_MS;
}
else if (task_delay_ms < EXAMPLE_LVGL_TASK_MIN_DELAY_MS)
{
task_delay_ms = EXAMPLE_LVGL_TASK_MIN_DELAY_MS;
}
vTaskDelay(pdMS_TO_TICKS(task_delay_ms));
static void example_lvgl_port_task(void *arg) {
ESP_LOGI(TAG, "Starting LVGL task");
uint32_t task_delay_ms = EXAMPLE_LVGL_TASK_MAX_DELAY_MS;
while (1) {
// Lock the mutex due to the LVGL APIs being not thread-safe
if (example_lvgl_lock(-1)) {
task_delay_ms = lv_timer_handler();
example_lvgl_unlock();
}
if (task_delay_ms > EXAMPLE_LVGL_TASK_MAX_DELAY_MS) {
task_delay_ms = EXAMPLE_LVGL_TASK_MAX_DELAY_MS;
} else if (task_delay_ms < EXAMPLE_LVGL_TASK_MIN_DELAY_MS) {
task_delay_ms = EXAMPLE_LVGL_TASK_MIN_DELAY_MS;
}
vTaskDelay(pdMS_TO_TICKS(task_delay_ms));
}
}
void app_main(void)
{
esp_log_level_set("lcd_panel.io.i2c", ESP_LOG_NONE);
esp_log_level_set("FT5x06", ESP_LOG_NONE);
static lv_disp_draw_buf_t disp_buf; // contains internal graphic buffer(s) called draw buffer(s)
static lv_disp_drv_t disp_drv; // contains callback functions
static void shake_task(void *arg) {
ESP_LOGI(TAG, "Shake task idle");
while (1) {
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
ESP_LOGI(TAG, "Initialize I2C bus");
const i2c_config_t i2c_conf = {
.mode = I2C_MODE_MASTER,
.sda_io_num = EXAMPLE_PIN_NUM_TOUCH_SDA,
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_io_num = EXAMPLE_PIN_NUM_TOUCH_SCL,
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.master.clk_speed = 200 * 1000,
};
ESP_ERROR_CHECK(i2c_param_config(TOUCH_HOST, &i2c_conf));
ESP_ERROR_CHECK(i2c_driver_install(TOUCH_HOST, i2c_conf.mode, 0, 0, 0));
void app_main(void) {
esp_log_level_set("lcd_panel.io.i2c", ESP_LOG_NONE);
esp_log_level_set("FT5x06", ESP_LOG_NONE);
static lv_disp_draw_buf_t
disp_buf; // contains internal graphic buffer(s) called draw buffer(s)
static lv_disp_drv_t disp_drv; // contains callback functions
esp_io_expander_handle_t io_expander = NULL;
esp_io_expander_new_i2c_tca9554(TOUCH_HOST, ESP_IO_EXPANDER_I2C_TCA9554_ADDRESS_000, &io_expander);
ESP_LOGI(TAG, "Initialize I2C bus");
const i2c_config_t i2c_conf = {
.mode = I2C_MODE_MASTER,
.sda_io_num = EXAMPLE_PIN_NUM_TOUCH_SDA,
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_io_num = EXAMPLE_PIN_NUM_TOUCH_SCL,
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.master.clk_speed = 200 * 1000,
};
ESP_ERROR_CHECK(i2c_param_config(TOUCH_HOST, &i2c_conf));
ESP_ERROR_CHECK(i2c_driver_install(TOUCH_HOST, i2c_conf.mode, 0, 0, 0));
ESP_ERROR_CHECK(esp_io_expander_new_i2c_tca9554(TOUCH_HOST, ESP_IO_EXPANDER_I2C_TCA9554_ADDRESS_000, &io_expander));
esp_io_expander_handle_t io_expander = NULL;
esp_io_expander_new_i2c_tca9554(
TOUCH_HOST, ESP_IO_EXPANDER_I2C_TCA9554_ADDRESS_000, &io_expander);
esp_io_expander_set_dir(io_expander, IO_EXPANDER_PIN_NUM_0 | IO_EXPANDER_PIN_NUM_1 | IO_EXPANDER_PIN_NUM_2, IO_EXPANDER_OUTPUT);
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_0, 0);
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_1, 0);
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_2, 0);
vTaskDelay(pdMS_TO_TICKS(200));
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_0, 1);
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_1, 1);
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_2, 1);
ESP_ERROR_CHECK(esp_io_expander_new_i2c_tca9554(
TOUCH_HOST, ESP_IO_EXPANDER_I2C_TCA9554_ADDRESS_000, &io_expander));
esp_io_expander_set_dir(io_expander,
IO_EXPANDER_PIN_NUM_0 | IO_EXPANDER_PIN_NUM_1 |
IO_EXPANDER_PIN_NUM_2,
IO_EXPANDER_OUTPUT);
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_0, 0);
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_1, 0);
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_2, 0);
vTaskDelay(pdMS_TO_TICKS(200));
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_0, 1);
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_1, 1);
esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_2, 1);
#if EXAMPLE_PIN_NUM_BK_LIGHT >= 0
ESP_LOGI(TAG, "Turn off LCD backlight");
gpio_config_t bk_gpio_config = {
.mode = GPIO_MODE_OUTPUT,
.pin_bit_mask = 1ULL << EXAMPLE_PIN_NUM_BK_LIGHT};
ESP_ERROR_CHECK(gpio_config(&bk_gpio_config));
ESP_LOGI(TAG, "Turn off LCD backlight");
gpio_config_t bk_gpio_config = {.mode = GPIO_MODE_OUTPUT,
.pin_bit_mask = 1ULL
<< EXAMPLE_PIN_NUM_BK_LIGHT};
ESP_ERROR_CHECK(gpio_config(&bk_gpio_config));
#endif
ESP_LOGI(TAG, "Initialize SPI bus");
const spi_bus_config_t buscfg = SH8601_PANEL_BUS_QSPI_CONFIG(EXAMPLE_PIN_NUM_LCD_PCLK,
EXAMPLE_PIN_NUM_LCD_DATA0,
EXAMPLE_PIN_NUM_LCD_DATA1,
EXAMPLE_PIN_NUM_LCD_DATA2,
EXAMPLE_PIN_NUM_LCD_DATA3,
EXAMPLE_LCD_H_RES * EXAMPLE_LCD_V_RES * LCD_BIT_PER_PIXEL / 8);
ESP_ERROR_CHECK(spi_bus_initialize(LCD_HOST, &buscfg, SPI_DMA_CH_AUTO));
ESP_LOGI(TAG, "Initialize SPI bus");
const spi_bus_config_t buscfg = SH8601_PANEL_BUS_QSPI_CONFIG(
EXAMPLE_PIN_NUM_LCD_PCLK, EXAMPLE_PIN_NUM_LCD_DATA0,
EXAMPLE_PIN_NUM_LCD_DATA1, EXAMPLE_PIN_NUM_LCD_DATA2,
EXAMPLE_PIN_NUM_LCD_DATA3,
EXAMPLE_LCD_H_RES * EXAMPLE_LCD_V_RES * LCD_BIT_PER_PIXEL / 8);
ESP_ERROR_CHECK(spi_bus_initialize(LCD_HOST, &buscfg, SPI_DMA_CH_AUTO));
ESP_LOGI(TAG, "Install panel IO");
esp_lcd_panel_io_handle_t io_handle = NULL;
const esp_lcd_panel_io_spi_config_t io_config = SH8601_PANEL_IO_QSPI_CONFIG(EXAMPLE_PIN_NUM_LCD_CS,
example_notify_lvgl_flush_ready,
&disp_drv);
sh8601_vendor_config_t vendor_config = {
.init_cmds = lcd_init_cmds,
.init_cmds_size = sizeof(lcd_init_cmds) / sizeof(lcd_init_cmds[0]),
.flags = {
.use_qspi_interface = 1,
},
};
// Attach the LCD to the SPI bus
ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)LCD_HOST, &io_config, &io_handle));
ESP_LOGI(TAG, "Install panel IO");
esp_lcd_panel_io_handle_t io_handle = NULL;
const esp_lcd_panel_io_spi_config_t io_config = SH8601_PANEL_IO_QSPI_CONFIG(
EXAMPLE_PIN_NUM_LCD_CS, example_notify_lvgl_flush_ready, &disp_drv);
sh8601_vendor_config_t vendor_config = {
.init_cmds = lcd_init_cmds,
.init_cmds_size = sizeof(lcd_init_cmds) / sizeof(lcd_init_cmds[0]),
.flags =
{
.use_qspi_interface = 1,
},
};
// Attach the LCD to the SPI bus
ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)LCD_HOST,
&io_config, &io_handle));
esp_lcd_panel_handle_t panel_handle = NULL;
const esp_lcd_panel_dev_config_t panel_config = {
.reset_gpio_num = EXAMPLE_PIN_NUM_LCD_RST,
.rgb_ele_order = LCD_RGB_ELEMENT_ORDER_RGB,
.bits_per_pixel = LCD_BIT_PER_PIXEL,
.vendor_config = &vendor_config,
};
ESP_LOGI(TAG, "Install SH8601 panel driver");
ESP_ERROR_CHECK(esp_lcd_new_panel_sh8601(io_handle, &panel_config, &panel_handle));
ESP_ERROR_CHECK(esp_lcd_panel_reset(panel_handle));
ESP_ERROR_CHECK(esp_lcd_panel_init(panel_handle));
// user can flush pre-defined pattern to the screen before we turn on the screen or backlight
ESP_ERROR_CHECK(esp_lcd_panel_disp_on_off(panel_handle, true));
esp_lcd_panel_handle_t panel_handle = NULL;
const esp_lcd_panel_dev_config_t panel_config = {
.reset_gpio_num = EXAMPLE_PIN_NUM_LCD_RST,
.rgb_ele_order = LCD_RGB_ELEMENT_ORDER_RGB,
.bits_per_pixel = LCD_BIT_PER_PIXEL,
.vendor_config = &vendor_config,
};
ESP_LOGI(TAG, "Install SH8601 panel driver");
ESP_ERROR_CHECK(
esp_lcd_new_panel_sh8601(io_handle, &panel_config, &panel_handle));
ESP_ERROR_CHECK(esp_lcd_panel_reset(panel_handle));
ESP_ERROR_CHECK(esp_lcd_panel_init(panel_handle));
// user can flush pre-defined pattern to the screen before we turn on the
// screen or backlight
ESP_ERROR_CHECK(esp_lcd_panel_disp_on_off(panel_handle, true));
#if EXAMPLE_USE_TOUCH
esp_lcd_panel_io_handle_t tp_io_handle = NULL;
const esp_lcd_panel_io_i2c_config_t tp_io_config = ESP_LCD_TOUCH_IO_I2C_FT5x06_CONFIG();
// Attach the TOUCH to the I2C bus
ESP_ERROR_CHECK(esp_lcd_new_panel_io_i2c((esp_lcd_i2c_bus_handle_t)TOUCH_HOST, &tp_io_config, &tp_io_handle));
esp_lcd_panel_io_handle_t tp_io_handle = NULL;
const esp_lcd_panel_io_i2c_config_t tp_io_config =
ESP_LCD_TOUCH_IO_I2C_FT5x06_CONFIG();
// Attach the TOUCH to the I2C bus
ESP_ERROR_CHECK(esp_lcd_new_panel_io_i2c((esp_lcd_i2c_bus_handle_t)TOUCH_HOST,
&tp_io_config, &tp_io_handle));
const esp_lcd_touch_config_t tp_cfg = {
.x_max = EXAMPLE_LCD_H_RES,
.y_max = EXAMPLE_LCD_V_RES,
.rst_gpio_num = EXAMPLE_PIN_NUM_TOUCH_RST,
.int_gpio_num = EXAMPLE_PIN_NUM_TOUCH_INT,
.levels = {
.reset = 0,
.interrupt = 0,
},
.flags = {
.swap_xy = 0,
.mirror_x = 0,
.mirror_y = 0,
},
};
const esp_lcd_touch_config_t tp_cfg = {
.x_max = EXAMPLE_LCD_H_RES,
.y_max = EXAMPLE_LCD_V_RES,
.rst_gpio_num = EXAMPLE_PIN_NUM_TOUCH_RST,
.int_gpio_num = EXAMPLE_PIN_NUM_TOUCH_INT,
.levels =
{
.reset = 0,
.interrupt = 0,
},
.flags =
{
.swap_xy = 0,
.mirror_x = 0,
.mirror_y = 0,
},
};
ESP_LOGI(TAG, "Initialize touch controller");
ESP_ERROR_CHECK(esp_lcd_touch_new_i2c_ft5x06(tp_io_handle, &tp_cfg, &tp));
ESP_LOGI(TAG, "Initialize touch controller");
ESP_ERROR_CHECK(esp_lcd_touch_new_i2c_ft5x06(tp_io_handle, &tp_cfg, &tp));
#endif
#if EXAMPLE_PIN_NUM_BK_LIGHT >= 0
ESP_LOGI(TAG, "Turn on LCD backlight");
gpio_set_level(EXAMPLE_PIN_NUM_BK_LIGHT, EXAMPLE_LCD_BK_LIGHT_ON_LEVEL);
ESP_LOGI(TAG, "Turn on LCD backlight");
gpio_set_level(EXAMPLE_PIN_NUM_BK_LIGHT, EXAMPLE_LCD_BK_LIGHT_ON_LEVEL);
#endif
ESP_LOGI(TAG, "Initialize LVGL library");
lv_init();
// alloc draw buffers used by LVGL
// it's recommended to choose the size of the draw buffer(s) to be at least 1/10 screen sized
lv_color_t *buf1 = heap_caps_malloc(EXAMPLE_LCD_H_RES * EXAMPLE_LVGL_BUF_HEIGHT * sizeof(lv_color_t), MALLOC_CAP_DMA);
assert(buf1);
lv_color_t *buf2 = heap_caps_malloc(EXAMPLE_LCD_H_RES * EXAMPLE_LVGL_BUF_HEIGHT * sizeof(lv_color_t), MALLOC_CAP_DMA);
assert(buf2);
// initialize LVGL draw buffers
lv_disp_draw_buf_init(&disp_buf, buf1, buf2, EXAMPLE_LCD_H_RES * EXAMPLE_LVGL_BUF_HEIGHT);
ESP_LOGI(TAG, "Initialize LVGL library");
lv_init();
// alloc draw buffers used by LVGL
// it's recommended to choose the size of the draw buffer(s) to be at least
// 1/10 screen sized
lv_color_t *buf1 = heap_caps_malloc(
EXAMPLE_LCD_H_RES * EXAMPLE_LVGL_BUF_HEIGHT * sizeof(lv_color_t),
MALLOC_CAP_DMA);
assert(buf1);
lv_color_t *buf2 = heap_caps_malloc(
EXAMPLE_LCD_H_RES * EXAMPLE_LVGL_BUF_HEIGHT * sizeof(lv_color_t),
MALLOC_CAP_DMA);
assert(buf2);
// initialize LVGL draw buffers
lv_disp_draw_buf_init(&disp_buf, buf1, buf2,
EXAMPLE_LCD_H_RES * EXAMPLE_LVGL_BUF_HEIGHT);
ESP_LOGI(TAG, "Register display driver to LVGL");
lv_disp_drv_init(&disp_drv);
disp_drv.hor_res = EXAMPLE_LCD_H_RES;
disp_drv.ver_res = EXAMPLE_LCD_V_RES;
disp_drv.flush_cb = example_lvgl_flush_cb;
disp_drv.rounder_cb = example_lvgl_rounder_cb;
disp_drv.drv_update_cb = example_lvgl_update_cb;
disp_drv.draw_buf = &disp_buf;
disp_drv.user_data = panel_handle;
lv_disp_t *disp = lv_disp_drv_register(&disp_drv);
ESP_LOGI(TAG, "Register display driver to LVGL");
lv_disp_drv_init(&disp_drv);
disp_drv.hor_res = EXAMPLE_LCD_H_RES;
disp_drv.ver_res = EXAMPLE_LCD_V_RES;
disp_drv.flush_cb = example_lvgl_flush_cb;
disp_drv.rounder_cb = example_lvgl_rounder_cb;
disp_drv.drv_update_cb = example_lvgl_update_cb;
disp_drv.draw_buf = &disp_buf;
disp_drv.user_data = panel_handle;
lv_disp_t *disp = lv_disp_drv_register(&disp_drv);
ESP_LOGI(TAG, "Install LVGL tick timer");
// Tick interface for LVGL (using esp_timer to generate 2ms periodic event)
const esp_timer_create_args_t lvgl_tick_timer_args = {
.callback = &example_increase_lvgl_tick,
.name = "lvgl_tick"};
esp_timer_handle_t lvgl_tick_timer = NULL;
ESP_ERROR_CHECK(esp_timer_create(&lvgl_tick_timer_args, &lvgl_tick_timer));
ESP_ERROR_CHECK(esp_timer_start_periodic(lvgl_tick_timer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000));
ESP_LOGI(TAG, "Install LVGL tick timer");
// Tick interface for LVGL (using esp_timer to generate 2ms periodic event)
const esp_timer_create_args_t lvgl_tick_timer_args = {
.callback = &example_increase_lvgl_tick, .name = "lvgl_tick"};
esp_timer_handle_t lvgl_tick_timer = NULL;
ESP_ERROR_CHECK(esp_timer_create(&lvgl_tick_timer_args, &lvgl_tick_timer));
ESP_ERROR_CHECK(esp_timer_start_periodic(lvgl_tick_timer,
EXAMPLE_LVGL_TICK_PERIOD_MS * 1000));
#if EXAMPLE_USE_TOUCH
static lv_indev_drv_t indev_drv; // Input device driver (Touch)
lv_indev_drv_init(&indev_drv);
indev_drv.type = LV_INDEV_TYPE_POINTER;
indev_drv.disp = disp;
indev_drv.read_cb = example_lvgl_touch_cb;
indev_drv.user_data = tp;
lv_indev_drv_register(&indev_drv);
static lv_indev_drv_t indev_drv; // Input device driver (Touch)
lv_indev_drv_init(&indev_drv);
indev_drv.type = LV_INDEV_TYPE_POINTER;
indev_drv.disp = disp;
indev_drv.read_cb = example_lvgl_touch_cb;
indev_drv.user_data = tp;
lv_indev_drv_register(&indev_drv);
#endif
lvgl_mux = xSemaphoreCreateMutex();
assert(lvgl_mux);
xTaskCreate(example_lvgl_port_task, "LVGL", EXAMPLE_LVGL_TASK_STACK_SIZE, NULL, EXAMPLE_LVGL_TASK_PRIORITY, NULL);
lvgl_mux = xSemaphoreCreateMutex();
assert(lvgl_mux);
xTaskCreate(example_lvgl_port_task, "LVGL", EXAMPLE_LVGL_TASK_STACK_SIZE,
NULL, EXAMPLE_LVGL_TASK_PRIORITY, NULL);
// Lock the mutex due to the LVGL APIs are not thread-safe
if (example_lvgl_lock(-1))
{
// Show splash screen first
ESP_LOGI(TAG, "Showing splash screen");
splash_screen_show();
// Lock the mutex due to the LVGL APIs are not thread-safe
if (example_lvgl_lock(-1)) {
// Show splash screen first
ESP_LOGI(TAG, "Showing splash screen");
splash_screen_show();
// Start animated eyes demo
ESP_LOGI(TAG, "Starting animated eyes");
animated_eyes_demo_start();
// Start blink animation loop
ESP_LOGI(TAG, "Starting blink animation");
extern const char blink_animation_data[];
lottie_create_from_data(lv_scr_act(), blink_animation_data);
// Release the mutex
example_lvgl_unlock();
// Release the mutex
example_lvgl_unlock();
// Initialize Shake Detector
if (shake_detector_init()) {
// Create a task to poll the shake detector
xTaskCreate(shake_task, "shake_task", 4096, NULL, 5, NULL);
}
}
}

985
main/lottie_player.c Normal file
View File

@@ -0,0 +1,985 @@
/**
* @file lottie_player.c
* @brief Lightweight Lottie animation player implementation for LVGL on ESP32
*
* This implementation provides a minimal Lottie JSON parser and renderer
* optimized for simple shape-based animations. It supports:
* - Rounded rectangle shapes
* - Position, size, and corner radius animation
* - Keyframe interpolation with bezier easing
* - Solid color fills
*
* The parser extracts only the data needed for rendering, minimizing memory
* usage on resource-constrained embedded systems.
*/
#include "lottie_player.h"
#include "cJSON.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "esp_random.h"
#include "esp_timer.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
static const char *TAG = "lottie_player";
// Maximum supported keyframes per property (memory optimization)
#define MAX_KEYFRAMES 16
// Maximum supported layers in animation
#define MAX_LAYERS 8
// Maximum supported shapes per layer
#define MAX_SHAPES 4
/**
* Keyframe data structure for animated properties
*/
typedef struct {
float time; // Frame time
float value[2]; // Value at this keyframe (x, y or single value)
float in_tangent[2]; // Bezier in-tangent
float out_tangent[2]; // Bezier out-tangent
bool hold; // If true, hold value until next keyframe
} lottie_keyframe_t;
/**
* Animated property that can have keyframes or static value
*/
typedef struct {
bool animated;
float static_value[2];
lottie_keyframe_t keyframes[MAX_KEYFRAMES];
uint8_t keyframe_count;
} lottie_property_t;
/**
* Rounded rectangle shape definition
*/
typedef struct {
lottie_property_t position; // Center position
lottie_property_t size; // Width and height
lottie_property_t corner_radius; // Corner radius
lv_color_t fill_color; // Fill color
uint8_t fill_opacity; // Fill opacity (0-100)
bool valid;
} lottie_rounded_rect_t;
/**
* Layer in the animation
*/
typedef struct {
int index; // Layer index
int parent; // Parent layer index (-1 if none)
int type; // Layer type (3=null, 4=shape)
lottie_property_t position; // Transform position
lottie_property_t anchor; // Anchor point
lottie_rounded_rect_t shapes[MAX_SHAPES];
uint8_t shape_count;
bool valid;
} lottie_layer_t;
/**
* Main player state structure
*/
struct lottie_player_t {
// Animation metadata
uint16_t width;
uint16_t height;
float framerate;
uint32_t total_frames;
uint32_t in_point; // Start frame
uint32_t out_point; // End frame
// Layers
lottie_layer_t layers[MAX_LAYERS];
uint8_t layer_count;
// Playback state
float current_frame;
bool playing;
bool loop;
int64_t start_time_us; // Animation start time in microseconds
// Natural blink mode
bool natural_blink_mode; // If true, shows idle state with random blinks
lv_timer_t *blink_timer; // Timer for triggering random blinks
// LVGL objects
lv_obj_t *canvas;
lv_color_t *canvas_buf;
lv_timer_t *timer;
};
// Forward declarations
static void lottie_parse_animation(lottie_player_handle_t handle,
const cJSON *root);
static void lottie_parse_layers(lottie_player_handle_t handle,
const cJSON *layers);
static void lottie_parse_layer(lottie_layer_t *layer, const cJSON *json);
static void lottie_parse_shapes(lottie_layer_t *layer, const cJSON *shapes);
static void lottie_parse_property(lottie_property_t *prop, const cJSON *json);
static float lottie_interpolate_property(const lottie_property_t *prop,
float frame, int index);
static void lottie_render_frame(lottie_player_handle_t handle);
static void lottie_timer_cb(lv_timer_t *timer);
static void lottie_blink_timer_cb(lv_timer_t *timer);
static void lottie_schedule_next_blink(lottie_player_handle_t handle);
static float lottie_bezier_interpolate(float t, float p0, float p1, float p2,
float p3);
/**
* Create a Lottie player from JSON data
*/
lottie_player_handle_t lottie_create_from_data(lv_obj_t *parent,
const char *json_data) {
if (!parent || !json_data) {
ESP_LOGE(TAG, "Invalid parameters");
return NULL;
}
// Parse JSON
cJSON *root = cJSON_Parse(json_data);
if (!root) {
ESP_LOGE(TAG, "Failed to parse JSON: %s", cJSON_GetErrorPtr());
return NULL;
}
// Allocate player structure
lottie_player_handle_t handle = calloc(1, sizeof(struct lottie_player_t));
if (!handle) {
ESP_LOGE(TAG, "Failed to allocate player");
cJSON_Delete(root);
return NULL;
}
// Set defaults
handle->playing = false;
handle->loop = true;
handle->current_frame = 0;
// Parse animation data
lottie_parse_animation(handle, root);
// Cleanup JSON (we've extracted what we need)
cJSON_Delete(root);
// Validate parsed data
if (handle->width == 0 || handle->height == 0 || handle->total_frames == 0) {
ESP_LOGE(TAG, "Invalid animation data");
free(handle);
return NULL;
}
ESP_LOGI(TAG, "Parsed animation: %dx%d, %lu frames at %.1f fps",
handle->width, handle->height, (unsigned long)handle->total_frames,
handle->framerate);
ESP_LOGI(TAG, "Loaded %d layers", handle->layer_count);
// Allocate canvas buffer
size_t buf_size = handle->width * handle->height * sizeof(lv_color_t);
handle->canvas_buf =
heap_caps_malloc(buf_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (!handle->canvas_buf) {
// Try regular RAM if SPIRAM not available
handle->canvas_buf = malloc(buf_size);
}
if (!handle->canvas_buf) {
ESP_LOGE(TAG, "Failed to allocate canvas buffer (%u bytes)",
(unsigned)buf_size);
free(handle);
return NULL;
}
// Create LVGL canvas
handle->canvas = lv_canvas_create(parent);
lv_canvas_set_buffer(handle->canvas, handle->canvas_buf, handle->width,
handle->height, LV_IMG_CF_TRUE_COLOR);
lv_obj_center(handle->canvas);
// Speed up animation for snappier blinks (2x speed)
// The canvas rendering is slow (~110ms per frame), so we need faster playback
handle->framerate *= 2.0f;
// Create timer for animation playback (use faster period for responsiveness)
uint32_t period_ms = 16; // ~60Hz refresh attempts
handle->timer = lv_timer_create(lottie_timer_cb, period_ms, handle);
lv_timer_pause(handle->timer);
// Enable natural blink mode by default
handle->natural_blink_mode = true;
handle->loop = false; // Don't loop in natural mode
// Show idle state (last frame = eyes open)
handle->current_frame = handle->total_frames - 1;
lottie_render_frame(handle);
// Create blink timer with random initial delay (2-5 seconds)
uint32_t initial_delay = 2000 + (esp_random() % 3000);
handle->blink_timer =
lv_timer_create(lottie_blink_timer_cb, initial_delay, handle);
lv_timer_set_repeat_count(handle->blink_timer,
1); // One-shot, will be recreated
ESP_LOGI(TAG, "Natural blink mode enabled, first blink in %lu ms",
(unsigned long)initial_delay);
return handle;
}
/**
* Parse top-level animation properties
*/
static void lottie_parse_animation(lottie_player_handle_t handle,
const cJSON *root) {
cJSON *item;
// Width
item = cJSON_GetObjectItem(root, "w");
if (item && cJSON_IsNumber(item)) {
handle->width = (uint16_t)item->valueint;
}
// Height
item = cJSON_GetObjectItem(root, "h");
if (item && cJSON_IsNumber(item)) {
handle->height = (uint16_t)item->valueint;
}
// Framerate
item = cJSON_GetObjectItem(root, "fr");
if (item && cJSON_IsNumber(item)) {
handle->framerate = (float)item->valuedouble;
}
// In point (start frame)
item = cJSON_GetObjectItem(root, "ip");
if (item && cJSON_IsNumber(item)) {
handle->in_point = (uint32_t)item->valueint;
}
// Out point (end frame)
item = cJSON_GetObjectItem(root, "op");
if (item && cJSON_IsNumber(item)) {
handle->out_point = (uint32_t)item->valueint;
}
handle->total_frames = handle->out_point - handle->in_point;
// Parse layers
item = cJSON_GetObjectItem(root, "layers");
if (item && cJSON_IsArray(item)) {
lottie_parse_layers(handle, item);
}
}
/**
* Parse layers array
*/
static void lottie_parse_layers(lottie_player_handle_t handle,
const cJSON *layers) {
int count = cJSON_GetArraySize(layers);
if (count > MAX_LAYERS) {
ESP_LOGW(TAG, "Truncating %d layers to %d", count, MAX_LAYERS);
count = MAX_LAYERS;
}
handle->layer_count = 0;
for (int i = 0; i < count; i++) {
cJSON *layer_json = cJSON_GetArrayItem(layers, i);
if (layer_json) {
lottie_layer_t *layer = &handle->layers[handle->layer_count];
memset(layer, 0, sizeof(lottie_layer_t));
layer->parent = -1;
lottie_parse_layer(layer, layer_json);
if (layer->valid) {
handle->layer_count++;
}
}
}
}
/**
* Parse a single layer
*/
static void lottie_parse_layer(lottie_layer_t *layer, const cJSON *json) {
cJSON *item;
// Layer index
item = cJSON_GetObjectItem(json, "ind");
if (item && cJSON_IsNumber(item)) {
layer->index = item->valueint;
}
// Layer type
item = cJSON_GetObjectItem(json, "ty");
if (item && cJSON_IsNumber(item)) {
layer->type = item->valueint;
}
// Parent index
item = cJSON_GetObjectItem(json, "parent");
if (item && cJSON_IsNumber(item)) {
layer->parent = item->valueint;
}
// Transform (ks)
cJSON *ks = cJSON_GetObjectItem(json, "ks");
if (ks) {
// Position
item = cJSON_GetObjectItem(ks, "p");
if (item) {
lottie_parse_property(&layer->position, item);
}
// Anchor point
item = cJSON_GetObjectItem(ks, "a");
if (item) {
lottie_parse_property(&layer->anchor, item);
}
}
// Shapes (for shape layers, type 4)
if (layer->type == 4) {
item = cJSON_GetObjectItem(json, "shapes");
if (item && cJSON_IsArray(item)) {
lottie_parse_shapes(layer, item);
}
}
layer->valid = true;
}
/**
* Parse shapes array for a layer
* Uses two-pass approach: first find fill color, then parse shapes
*/
static void lottie_parse_shapes(lottie_layer_t *layer, const cJSON *shapes) {
int count = cJSON_GetArraySize(shapes);
layer->shape_count = 0;
// PASS 1: Find fill color (it may come before or after shapes in the array)
lv_color_t fill_color = lv_color_white();
uint8_t fill_opacity = 100;
bool fill_found = false;
for (int i = 0; i < count; i++) {
cJSON *shape = cJSON_GetArrayItem(shapes, i);
if (!shape)
continue;
cJSON *ty = cJSON_GetObjectItem(shape, "ty");
if (!ty || !cJSON_IsString(ty))
continue;
const char *type = ty->valuestring;
// Fill color
if (strcmp(type, "fl") == 0) {
cJSON *c = cJSON_GetObjectItem(shape, "c");
if (c) {
cJSON *k = cJSON_GetObjectItem(c, "k");
if (k && cJSON_IsArray(k) && cJSON_GetArraySize(k) >= 3) {
float r = (float)cJSON_GetArrayItem(k, 0)->valuedouble;
float g = (float)cJSON_GetArrayItem(k, 1)->valuedouble;
float b = (float)cJSON_GetArrayItem(k, 2)->valuedouble;
fill_color = lv_color_make((uint8_t)(r * 255), (uint8_t)(g * 255),
(uint8_t)(b * 255));
fill_found = true;
ESP_LOGI(TAG, "Found fill: RGB(%.2f,%.2f,%.2f) -> (%d,%d,%d)", r, g,
b, (int)(r * 255), (int)(g * 255), (int)(b * 255));
}
}
cJSON *o = cJSON_GetObjectItem(shape, "o");
if (o) {
cJSON *k = cJSON_GetObjectItem(o, "k");
if (k && cJSON_IsNumber(k)) {
fill_opacity = (uint8_t)k->valueint;
}
}
break; // Found fill, stop searching
}
}
if (!fill_found) {
ESP_LOGW(TAG, "No fill found for layer, using default white");
}
// PASS 2: Parse shapes and apply the found fill color
for (int i = 0; i < count && layer->shape_count < MAX_SHAPES; i++) {
cJSON *shape = cJSON_GetArrayItem(shapes, i);
if (!shape)
continue;
cJSON *ty = cJSON_GetObjectItem(shape, "ty");
if (!ty || !cJSON_IsString(ty))
continue;
const char *type = ty->valuestring;
// Rounded rectangle
if (strcmp(type, "rc") == 0) {
lottie_rounded_rect_t *rect = &layer->shapes[layer->shape_count];
memset(rect, 0, sizeof(lottie_rounded_rect_t));
// Position
cJSON *p = cJSON_GetObjectItem(shape, "p");
if (p) {
lottie_parse_property(&rect->position, p);
}
// Size
cJSON *s = cJSON_GetObjectItem(shape, "s");
if (s) {
lottie_parse_property(&rect->size, s);
}
// Corner radius
cJSON *r = cJSON_GetObjectItem(shape, "r");
if (r) {
lottie_parse_property(&rect->corner_radius, r);
}
rect->fill_color = fill_color;
rect->fill_opacity = fill_opacity;
rect->valid = true;
layer->shape_count++;
}
}
}
/**
* Parse an animated or static property
*/
static void lottie_parse_property(lottie_property_t *prop, const cJSON *json) {
memset(prop, 0, sizeof(lottie_property_t));
cJSON *a = cJSON_GetObjectItem(json, "a");
cJSON *k = cJSON_GetObjectItem(json, "k");
if (!k)
return;
// Check if animated
if (a && cJSON_IsNumber(a) && a->valueint == 1) {
prop->animated = true;
// Parse keyframes
if (cJSON_IsArray(k)) {
int count = cJSON_GetArraySize(k);
if (count > MAX_KEYFRAMES) {
count = MAX_KEYFRAMES;
}
for (int i = 0; i < count; i++) {
cJSON *kf = cJSON_GetArrayItem(k, i);
if (!kf)
continue;
lottie_keyframe_t *keyframe = &prop->keyframes[prop->keyframe_count];
// Time
cJSON *t = cJSON_GetObjectItem(kf, "t");
if (t && cJSON_IsNumber(t)) {
keyframe->time = (float)t->valuedouble;
}
// Hold
cJSON *h = cJSON_GetObjectItem(kf, "h");
if (h && cJSON_IsNumber(h)) {
keyframe->hold = h->valueint == 1;
}
// Start value (s)
cJSON *s = cJSON_GetObjectItem(kf, "s");
if (s && cJSON_IsArray(s)) {
int vcount = cJSON_GetArraySize(s);
for (int v = 0; v < vcount && v < 2; v++) {
cJSON *val = cJSON_GetArrayItem(s, v);
if (val && cJSON_IsNumber(val)) {
keyframe->value[v] = (float)val->valuedouble;
}
}
}
// In tangent (i)
cJSON *in_tan = cJSON_GetObjectItem(kf, "i");
if (in_tan) {
cJSON *x = cJSON_GetObjectItem(in_tan, "x");
cJSON *y = cJSON_GetObjectItem(in_tan, "y");
if (x && cJSON_IsArray(x) && cJSON_GetArraySize(x) > 0) {
keyframe->in_tangent[0] =
(float)cJSON_GetArrayItem(x, 0)->valuedouble;
} else if (x && cJSON_IsNumber(x)) {
keyframe->in_tangent[0] = (float)x->valuedouble;
}
if (y && cJSON_IsArray(y) && cJSON_GetArraySize(y) > 0) {
keyframe->in_tangent[1] =
(float)cJSON_GetArrayItem(y, 0)->valuedouble;
} else if (y && cJSON_IsNumber(y)) {
keyframe->in_tangent[1] = (float)y->valuedouble;
}
}
// Out tangent (o)
cJSON *out_tan = cJSON_GetObjectItem(kf, "o");
if (out_tan) {
cJSON *x = cJSON_GetObjectItem(out_tan, "x");
cJSON *y = cJSON_GetObjectItem(out_tan, "y");
if (x && cJSON_IsArray(x) && cJSON_GetArraySize(x) > 0) {
keyframe->out_tangent[0] =
(float)cJSON_GetArrayItem(x, 0)->valuedouble;
} else if (x && cJSON_IsNumber(x)) {
keyframe->out_tangent[0] = (float)x->valuedouble;
}
if (y && cJSON_IsArray(y) && cJSON_GetArraySize(y) > 0) {
keyframe->out_tangent[1] =
(float)cJSON_GetArrayItem(y, 0)->valuedouble;
} else if (y && cJSON_IsNumber(y)) {
keyframe->out_tangent[1] = (float)y->valuedouble;
}
}
prop->keyframe_count++;
}
}
} else {
// Static value
prop->animated = false;
if (cJSON_IsArray(k)) {
int count = cJSON_GetArraySize(k);
for (int i = 0; i < count && i < 2; i++) {
cJSON *val = cJSON_GetArrayItem(k, i);
if (val && cJSON_IsNumber(val)) {
prop->static_value[i] = (float)val->valuedouble;
}
}
} else if (cJSON_IsNumber(k)) {
prop->static_value[0] = (float)k->valuedouble;
}
}
}
/**
* Cubic bezier interpolation
*/
static float lottie_bezier_interpolate(float t, float p0, float p1, float p2,
float p3) {
float u = 1.0f - t;
float tt = t * t;
float uu = u * u;
float uuu = uu * u;
float ttt = tt * t;
float result = uuu * p0;
result += 3.0f * uu * t * p1;
result += 3.0f * u * tt * p2;
result += ttt * p3;
return result;
}
/**
* Interpolate a property value at a given frame
*/
static float lottie_interpolate_property(const lottie_property_t *prop,
float frame, int index) {
if (!prop->animated) {
return prop->static_value[index];
}
if (prop->keyframe_count == 0) {
return 0.0f;
}
// Find surrounding keyframes
const lottie_keyframe_t *prev = NULL;
const lottie_keyframe_t *next = NULL;
for (int i = 0; i < prop->keyframe_count; i++) {
if (prop->keyframes[i].time <= frame) {
prev = &prop->keyframes[i];
}
if (prop->keyframes[i].time >= frame && next == NULL) {
next = &prop->keyframes[i];
}
}
// Clamp to boundaries
if (!prev) {
return prop->keyframes[0].value[index];
}
if (!next || prev == next) {
return prev->value[index];
}
// Check for hold keyframe
if (prev->hold) {
return prev->value[index];
}
// Calculate interpolation factor
float duration = next->time - prev->time;
if (duration <= 0) {
return prev->value[index];
}
float t = (frame - prev->time) / duration;
// Apply bezier easing if tangents are present
if (prev->out_tangent[0] != 0 || prev->out_tangent[1] != 0 ||
next->in_tangent[0] != 0 || next->in_tangent[1] != 0) {
// Approximate bezier curve for timing
t = lottie_bezier_interpolate(t, 0.0f, prev->out_tangent[1],
next->in_tangent[1], 1.0f);
t = fmaxf(0.0f, fminf(1.0f, t));
}
// Linear interpolation between values
return prev->value[index] + t * (next->value[index] - prev->value[index]);
}
/**
* Get layer by index
*/
static lottie_layer_t *lottie_get_layer_by_index(lottie_player_handle_t handle,
int index) {
for (int i = 0; i < handle->layer_count; i++) {
if (handle->layers[i].index == index) {
return &handle->layers[i];
}
}
return NULL;
}
/**
* Calculate cumulative transform for a layer (following parent chain)
* In Lottie, transform = position - anchor for each layer in the hierarchy
*/
static void lottie_get_layer_transform(lottie_player_handle_t handle,
lottie_layer_t *layer, float frame,
float *offset_x, float *offset_y) {
*offset_x = 0;
*offset_y = 0;
lottie_layer_t *current = layer;
while (current) {
// Add this layer's position and subtract anchor
float pos_x = lottie_interpolate_property(&current->position, frame, 0);
float pos_y = lottie_interpolate_property(&current->position, frame, 1);
float anc_x = lottie_interpolate_property(&current->anchor, frame, 0);
float anc_y = lottie_interpolate_property(&current->anchor, frame, 1);
*offset_x += pos_x - anc_x;
*offset_y += pos_y - anc_y;
// Follow parent chain
if (current->parent >= 0) {
current = lottie_get_layer_by_index(handle, current->parent);
} else {
current = NULL;
}
}
}
/**
* Draw a rounded rectangle on the canvas
*/
static void lottie_draw_rounded_rect(lottie_player_handle_t handle,
lv_coord_t x, lv_coord_t y, lv_coord_t w,
lv_coord_t h, lv_coord_t radius,
lv_color_t color) {
lv_draw_rect_dsc_t rect_dsc;
lv_draw_rect_dsc_init(&rect_dsc);
rect_dsc.bg_color = color;
rect_dsc.bg_opa = LV_OPA_COVER;
rect_dsc.radius = radius;
rect_dsc.border_width = 0;
lv_area_t area;
area.x1 = x - w / 2;
area.y1 = y - h / 2;
area.x2 = area.x1 + w - 1;
area.y2 = area.y1 + h - 1;
lv_canvas_draw_rect(handle->canvas, area.x1, area.y1, w, h, &rect_dsc);
}
/**
* Render current frame to canvas
*/
static void lottie_render_frame(lottie_player_handle_t handle) {
static bool first_frame_logged = false;
// Clear canvas to black
lv_canvas_fill_bg(handle->canvas, lv_color_black(), LV_OPA_COVER);
float frame = handle->current_frame + handle->in_point;
// Render layers in reverse order (last layer = bottom)
for (int i = handle->layer_count - 1; i >= 0; i--) {
lottie_layer_t *layer = &handle->layers[i];
if (!layer->valid || layer->type != 4) {
continue;
}
// Get cumulative transform
float offset_x = 0, offset_y = 0;
lottie_get_layer_transform(handle, layer, frame, &offset_x, &offset_y);
// Render shapes
for (int s = 0; s < layer->shape_count; s++) {
lottie_rounded_rect_t *rect = &layer->shapes[s];
if (!rect->valid) {
continue;
}
// Get animated properties
float px = lottie_interpolate_property(&rect->position, frame, 0);
float py = lottie_interpolate_property(&rect->position, frame, 1);
float w = lottie_interpolate_property(&rect->size, frame, 0);
float h = lottie_interpolate_property(&rect->size, frame, 1);
float r = lottie_interpolate_property(&rect->corner_radius, frame, 0);
// Apply layer offset
px += offset_x;
py += offset_y;
// Debug logging for first frame
if (!first_frame_logged) {
ESP_LOGI(TAG,
"Layer %d shape %d: pos=(%.1f,%.1f) size=(%.1f,%.1f) "
"radius=%.1f offset=(%.1f,%.1f)",
layer->index, s, px - offset_x, py - offset_y, w, h, r,
offset_x, offset_y);
}
// Only draw if visible
if (w > 0 && h > 0) {
lottie_draw_rounded_rect(handle, (lv_coord_t)px, (lv_coord_t)py,
(lv_coord_t)w, (lv_coord_t)h, (lv_coord_t)r,
rect->fill_color);
}
}
}
if (!first_frame_logged) {
first_frame_logged = true;
}
// Invalidate canvas to trigger redraw
lv_obj_invalidate(handle->canvas);
}
/**
* Timer callback for animation playback
* Uses time-based animation for accurate playback speed
*/
static void lottie_timer_cb(lv_timer_t *timer) {
lottie_player_handle_t handle = (lottie_player_handle_t)timer->user_data;
if (!handle || !handle->playing) {
return;
}
// Calculate current frame based on elapsed time
int64_t now_us = esp_timer_get_time();
int64_t elapsed_us = now_us - handle->start_time_us;
float elapsed_sec = (float)elapsed_us / 1000000.0f;
float frame = elapsed_sec * handle->framerate;
// Debug: log first few frames
static int frame_log_count = 0;
if (frame_log_count < 5) {
ESP_LOGI(TAG, "Frame calc: elapsed=%.3fs, frame=%.1f/%lu", elapsed_sec,
frame, (unsigned long)handle->total_frames);
frame_log_count++;
}
// Handle end of animation
if (frame >= handle->total_frames) {
if (handle->loop) {
// Reset start time for smooth looping
float cycles = frame / handle->total_frames;
int full_cycles = (int)cycles;
handle->start_time_us += (int64_t)(full_cycles * handle->total_frames /
handle->framerate * 1000000.0f);
frame = frame - (full_cycles * handle->total_frames);
} else {
// Animation complete - return to idle state
ESP_LOGI(TAG, "Blink animation complete after %.3fs", elapsed_sec);
frame_log_count = 0; // Reset for next blink
handle->playing = false;
lv_timer_pause(handle->timer);
handle->current_frame = handle->total_frames - 1; // Eyes open
lottie_render_frame(handle);
// Schedule next blink if in natural mode
if (handle->natural_blink_mode) {
lottie_schedule_next_blink(handle);
}
return;
}
}
handle->current_frame = frame;
// Render the new frame
lottie_render_frame(handle);
}
/**
* Schedule next random blink
*/
static void lottie_schedule_next_blink(lottie_player_handle_t handle) {
if (!handle || !handle->natural_blink_mode) {
return;
}
// Random delay between 3-6 seconds for natural feel
uint32_t delay_ms = 3000 + (esp_random() % 3000);
// Create new timer (old one was already deleted or is NULL)
handle->blink_timer =
lv_timer_create(lottie_blink_timer_cb, delay_ms, handle);
lv_timer_set_repeat_count(handle->blink_timer, 1);
}
/**
* Blink timer callback - triggers a blink animation
*/
static void lottie_blink_timer_cb(lv_timer_t *timer) {
lottie_player_handle_t handle = (lottie_player_handle_t)timer->user_data;
// Mark timer as gone (one-shot timers auto-delete after callback returns)
if (handle) {
handle->blink_timer = NULL;
}
if (!handle || !handle->natural_blink_mode) {
return;
}
// Start blink animation from frame 0
ESP_LOGI(TAG, "Blink triggered! Starting animation from frame 0");
handle->current_frame = 0;
lottie_play(handle);
}
/**
* Start/resume playback
*/
void lottie_play(lottie_player_handle_t handle) {
if (!handle)
return;
// Set start time for time-based animation
// Adjust for current frame position if resuming
int64_t frame_offset_us =
(int64_t)(handle->current_frame / handle->framerate * 1000000.0f);
handle->start_time_us = esp_timer_get_time() - frame_offset_us;
handle->playing = true;
lv_timer_resume(handle->timer);
}
/**
* Pause playback
*/
void lottie_pause(lottie_player_handle_t handle) {
if (!handle)
return;
handle->playing = false;
lv_timer_pause(handle->timer);
}
/**
* Stop playback and reset to first frame
*/
void lottie_stop(lottie_player_handle_t handle) {
if (!handle)
return;
handle->playing = false;
handle->current_frame = 0;
lv_timer_pause(handle->timer);
lottie_render_frame(handle);
}
/**
* Set loop mode
*/
void lottie_set_loop(lottie_player_handle_t handle, bool loop) {
if (!handle)
return;
handle->loop = loop;
}
/**
* Check if playing
*/
bool lottie_is_playing(lottie_player_handle_t handle) {
if (!handle)
return false;
return handle->playing;
}
/**
* Get current frame number
*/
uint32_t lottie_get_current_frame(lottie_player_handle_t handle) {
if (!handle)
return 0;
return (uint32_t)handle->current_frame;
}
/**
* Get total frame count
*/
uint32_t lottie_get_total_frames(lottie_player_handle_t handle) {
if (!handle)
return 0;
return handle->total_frames;
}
/**
* Set current frame
*/
void lottie_set_frame(lottie_player_handle_t handle, uint32_t frame) {
if (!handle)
return;
if (frame >= handle->total_frames) {
frame = handle->total_frames - 1;
}
handle->current_frame = (float)frame;
lottie_render_frame(handle);
}
/**
* Destroy player and free resources
*/
void lottie_destroy(lottie_player_handle_t handle) {
if (!handle)
return;
// Stop timer
if (handle->timer) {
lv_timer_del(handle->timer);
}
// Delete canvas
if (handle->canvas) {
lv_obj_del(handle->canvas);
}
// Free canvas buffer
if (handle->canvas_buf) {
free(handle->canvas_buf);
}
// Free player structure
free(handle);
ESP_LOGI(TAG, "Lottie player destroyed");
}

113
main/lottie_player.h Normal file
View File

@@ -0,0 +1,113 @@
/**
* @file lottie_player.h
* @brief Lightweight Lottie animation player for LVGL on ESP32
*
* This module provides a minimal Lottie JSON animation player optimized for
* embedded systems. It supports basic shape types (rounded rectangles) with
* keyframe animation and bezier curve interpolation.
*
* Designed for simple animations like blinking eyes on resource-constrained
* devices. Does not support the full Lottie specification.
*/
#ifndef LOTTIE_PLAYER_H
#define LOTTIE_PLAYER_H
#include "lvgl.h"
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// Forward declaration of internal structure
typedef struct lottie_player_t *lottie_player_handle_t;
/**
* @brief Create a Lottie animation player from embedded JSON data
*
* Parses the Lottie JSON and creates an LVGL object hierarchy for rendering.
* The animation starts in paused state - call lottie_play() to begin playback.
*
* @param parent Parent LVGL object to attach the animation to
* @param json_data Pointer to null-terminated JSON string in flash
* @return Handle to the player instance, or NULL on failure
*/
lottie_player_handle_t lottie_create_from_data(lv_obj_t *parent,
const char *json_data);
/**
* @brief Start or resume animation playback
*
* @param handle Handle to the Lottie player instance
*/
void lottie_play(lottie_player_handle_t handle);
/**
* @brief Pause animation playback
*
* @param handle Handle to the Lottie player instance
*/
void lottie_pause(lottie_player_handle_t handle);
/**
* @brief Stop animation and reset to first frame
*
* @param handle Handle to the Lottie player instance
*/
void lottie_stop(lottie_player_handle_t handle);
/**
* @brief Set whether the animation should loop
*
* @param handle Handle to the Lottie player instance
* @param loop True to enable looping, false for single playthrough
*/
void lottie_set_loop(lottie_player_handle_t handle, bool loop);
/**
* @brief Check if animation is currently playing
*
* @param handle Handle to the Lottie player instance
* @return True if playing, false if paused or stopped
*/
bool lottie_is_playing(lottie_player_handle_t handle);
/**
* @brief Get the current frame number
*
* @param handle Handle to the Lottie player instance
* @return Current frame number (0-indexed)
*/
uint32_t lottie_get_current_frame(lottie_player_handle_t handle);
/**
* @brief Get total number of frames in the animation
*
* @param handle Handle to the Lottie player instance
* @return Total frame count
*/
uint32_t lottie_get_total_frames(lottie_player_handle_t handle);
/**
* @brief Set the current frame manually
*
* @param handle Handle to the Lottie player instance
* @param frame Frame number to seek to (clamped to valid range)
*/
void lottie_set_frame(lottie_player_handle_t handle, uint32_t frame);
/**
* @brief Destroy the Lottie player and free all resources
*
* @param handle Handle to the Lottie player instance
*/
void lottie_destroy(lottie_player_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif /* LOTTIE_PLAYER_H */

213
main/shake_detector.cpp Normal file
View File

@@ -0,0 +1,213 @@
/**
* @file shake_detector.cpp
* @brief Shake detection implementation using SensorLib QMI8658
*/
#include "shake_detector.h"
#include "SensorQMI8658.hpp"
#include "esp_log.h"
#include "esp_timer.h"
#include <math.h>
static const char *TAG = "shake_detector";
// Sensor instance
static SensorQMI8658 qmi;
// I2C Pins (Matches example_qspi_with_ram.c)
#define I2C_MASTER_SCL 14
#define I2C_MASTER_SDA 15
#define I2C_MASTER_NUM I2C_NUM_0
#define QMI8658_ADDR 0x6B
// Shake detection thresholds
#define SHAKE_ACCEL_THRESHOLD 0.5f // 0.5G deviation from baseline
#define SHAKE_DEBOUNCE_MS 2000 // Debounce time between detections
#define BASELINE_SAMPLES 10 // Number of samples to average for baseline
static uint32_t last_trigger_time = 0;
// Store latest readings and baseline
static float last_acc_x = 0, last_acc_y = 0, last_acc_z = 0;
static float baseline_x = 0, baseline_y = 0, baseline_z = 0;
static bool baseline_ready = false;
static uint32_t get_millis() { return (uint32_t)(esp_timer_get_time() / 1000); }
extern "C" bool shake_detector_init(void) {
ESP_LOGI(TAG, "Initializing Shake Detector (QMI8658)");
// Initialize sensor (I2C driver already installed by main app)
if (!qmi.begin(I2C_MASTER_NUM, QMI8658_ADDR, I2C_MASTER_SDA,
I2C_MASTER_SCL)) {
ESP_LOGE(TAG, "Failed to initialize QMI8658!");
return false;
}
uint8_t chip_id = qmi.getChipID();
ESP_LOGI(TAG, "✓ Sensor initialized. Chip ID: 0x%02x", chip_id);
// Configure accelerometer (match vendor demo settings exactly)
ESP_LOGI(TAG, "Configuring accelerometer (4G, 1000Hz, LPF_MODE_0)...");
int ret_accel = qmi.configAccelerometer(SensorQMI8658::ACC_RANGE_4G,
SensorQMI8658::ACC_ODR_1000Hz,
SensorQMI8658::LPF_MODE_0, true);
if (ret_accel != 0) {
ESP_LOGE(TAG, "Failed to configure accelerometer: %d", ret_accel);
return false;
}
ESP_LOGI(TAG, "✓ Accelerometer configured");
// Configure gyroscope (match vendor demo settings)
ESP_LOGI(TAG, "Configuring gyroscope (64DPS, 896.8Hz, LPF_MODE_3)...");
int ret_gyro = qmi.configGyroscope(SensorQMI8658::GYR_RANGE_64DPS,
SensorQMI8658::GYR_ODR_896_8Hz,
SensorQMI8658::LPF_MODE_3, true);
if (ret_gyro != 0) {
ESP_LOGW(TAG, "Gyroscope config failed: %d (will continue)", ret_gyro);
} else {
ESP_LOGI(TAG, "✓ Gyroscope configured");
}
// Enable sensors (gyro first, then accel - as in vendor demo)
// Enable sensors (vendor demo doesn't check return values - they're buggy in SensorLib)
// The SensorLib enable functions have backwards logic: they return bool but compare to DEV_WIRE_NONE (0)
// This causes them to always appear to fail even when they succeed
qmi.enableGyroscope();
qmi.enableAccelerometer();
ESP_LOGI(TAG, "✓ Gyroscope enabled");
ESP_LOGI(TAG, "✓ Accelerometer enabled");
// Test reading
vTaskDelay(pdMS_TO_TICKS(50));
if (qmi.getDataReady()) {
float test_x, test_y, test_z;
if (qmi.getAccelerometer(test_x, test_y, test_z)) {
ESP_LOGI(TAG, "✓ First reading OK: x=%.3f y=%.3f z=%.3f", test_x, test_y, test_z);
} else {
ESP_LOGW(TAG, "Data ready but read failed");
}
} else {
ESP_LOGW(TAG, "Sensor not ready for first read");
}
baseline_ready = false;
ESP_LOGI(TAG, "Shake Detector ready. Calibrating baseline...");
return true;
}
extern "C" shake_event_t shake_detector_update(void) {
uint32_t now = get_millis();
if (!qmi.getDataReady()) {
// Log occasionally if data is not ready, to see if sensor is stuck
static uint32_t last_not_ready_time = 0;
if (now - last_not_ready_time > 3000) {
ESP_LOGW(TAG, "QMI8658 Data Not Ready - sensor may be unresponsive");
last_not_ready_time = now;
}
return SHAKE_NONE;
}
float x, y, z;
if (!qmi.getAccelerometer(x, y, z)) {
static uint32_t last_read_fail_time = 0;
if (now - last_read_fail_time > 3000) {
ESP_LOGW(TAG, "Failed to read accelerometer data");
last_read_fail_time = now;
}
return SHAKE_NONE;
}
last_acc_x = x;
last_acc_y = y;
last_acc_z = z;
// Baseline calibration: collect first N samples to establish device orientation
if (!baseline_ready) {
static uint32_t baseline_count = 0;
static float baseline_sum_x = 0, baseline_sum_y = 0, baseline_sum_z = 0;
baseline_sum_x += x;
baseline_sum_y += y;
baseline_sum_z += z;
baseline_count++;
ESP_LOGI(TAG, "[%2d/10] x=%+.3f y=%+.3f z=%+.3f",
baseline_count, x, y, z);
if (baseline_count >= BASELINE_SAMPLES) {
baseline_x = baseline_sum_x / BASELINE_SAMPLES;
baseline_y = baseline_sum_y / BASELINE_SAMPLES;
baseline_z = baseline_sum_z / BASELINE_SAMPLES;
baseline_ready = true;
baseline_count = 0;
baseline_sum_x = baseline_sum_y = baseline_sum_z = 0;
ESP_LOGI(TAG, "✓ Baseline: x=%+.3f y=%+.3f z=%+.3f (magnitude: %.3f)",
baseline_x, baseline_y, baseline_z,
sqrtf(baseline_x*baseline_x + baseline_y*baseline_y + baseline_z*baseline_z));
}
return SHAKE_NONE;
}
// Calculate deviation from baseline
float delta_x = x - baseline_x;
float delta_y = y - baseline_y;
float delta_z = z - baseline_z;
float deviation = sqrtf(delta_x * delta_x + delta_y * delta_y + delta_z * delta_z);
// Log raw values every 1 second for monitoring
static uint32_t last_log_time = 0;
if (now - last_log_time > 1000) {
ESP_LOGI(TAG, "ACCEL: x=%+.3f y=%+.3f z=%+.3f | Δ=%+.3f",
x, y, z, deviation);
last_log_time = now;
}
// Debounce: ignore if we just triggered a shake
if (now - last_trigger_time < SHAKE_DEBOUNCE_MS) {
return SHAKE_NONE;
}
// Detect shake: acceleration deviation exceeds threshold
if (deviation > SHAKE_ACCEL_THRESHOLD) {
ESP_LOGI(TAG, "SHAKE! Δ=%.3f > Thr=%.3f | accel:[%+.2f,%+.2f,%+.2f]",
deviation, SHAKE_ACCEL_THRESHOLD, x, y, z);
last_trigger_time = now;
// Pick a random emotion for the shake
int r = rand() % 3;
switch (r) {
case 0:
ESP_LOGI(TAG, "→ Emotion: SURPRISED");
return SHAKE_SURPRISED;
case 1:
ESP_LOGI(TAG, "→ Emotion: SAD");
return SHAKE_SAD;
case 2:
ESP_LOGI(TAG, "→ Emotion: ANGRY");
return SHAKE_ANGRY;
default:
return SHAKE_SURPRISED;
}
}
return SHAKE_NONE;
}
extern "C" bool shake_detector_get_raw_accel(float *x, float *y, float *z) {
if (!qmi.getDataReady()) {
return false;
}
if (!qmi.getAccelerometer(*x, *y, *z)) {
return false;
}
last_acc_x = *x;
last_acc_y = *y;
last_acc_z = *z;
return true;
}

50
main/shake_detector.h Normal file
View File

@@ -0,0 +1,50 @@
/**
* @file shake_detector.h
* @brief Shake detection using QMI8658 sensor
*/
#ifndef SHAKE_DETECTOR_H
#define SHAKE_DETECTOR_H
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// Configuration types of shakes
typedef enum {
SHAKE_NONE = 0,
SHAKE_SURPRISED,
SHAKE_SAD,
SHAKE_ANGRY,
SHAKE_COUNT
} shake_event_t;
/**
* @brief Initialize the shake detector and QMI8658 sensor
* @return true on success, false on failure
*/
bool shake_detector_init(void);
/**
* @brief Check for shake events. Call this loop periodically.
* @return Detected shake event, or SHAKE_NONE
*/
shake_event_t shake_detector_update(void);
/**
* @brief Get the latest raw accelerometer reading
* @param x Pointer to store X acceleration
* @param y Pointer to store Y acceleration
* @param z Pointer to store Z acceleration
* @return true if data is available
*/
bool shake_detector_get_raw_accel(float *x, float *y, float *z);
#ifdef __cplusplus
}
#endif
#endif // SHAKE_DETECTOR_H