add remote source code (#12)

Co-authored-by: jyy <jiangyeying@m5stack.com>
This commit is contained in:
Jiangyy
2026-04-20 16:27:57 +08:00
committed by GitHub
parent dd34f9e0ec
commit 0cb413697b
29 changed files with 10886 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
# StackChan-RemoteControl-ESPNow
This repository is designed to remotely control StackChan servo movements via the `ESPNow` protocol.
+164
View File
@@ -0,0 +1,164 @@
BasedOnStyle: Google
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveMacros: true
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: false
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 120
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: true
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
SortPriority: 0
- Regex: '^<.*\.h>'
Priority: 1
SortPriority: 0
- Regex: '^<.*'
Priority: 2
SortPriority: 0
- Regex: '.*'
Priority: 3
SortPriority: 0
IncludeIsMainRegex: '([-_](test|unittest))?$'
IncludeIsMainSourceRegex: ''
IndentCaseLabels: true
IndentGotoLabels: true
IndentPPDirectives: None
IndentWidth: 4
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Never
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
RawStringFormats:
- Language: Cpp
Delimiters:
- cc
- CC
- cpp
- Cpp
- CPP
- 'c++'
- 'C++'
CanonicalDelimiter: ''
BasedOnStyle: google
- Language: TextProto
Delimiters:
- pb
- PB
- proto
- PROTO
EnclosingFunctions:
- EqualsProto
- EquivToProto
- PARSE_PARTIAL_TEXT_PROTO
- PARSE_TEST_PROTO
- PARSE_TEXT_PROTO
- ParseTextOrDie
- ParseTextProtoOrDie
CanonicalDelimiter: ''
BasedOnStyle: google
ReflowComments: true
SortIncludes: false
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
Standard: Auto
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 4
UseCRLF: false
UseTab: Never
+4
View File
@@ -0,0 +1,4 @@
managed_components
build
.vscode
.cache
+6
View File
@@ -0,0 +1,6 @@
# The following five lines of boilerplate have to be in your project's
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(StackChan-RemoteControl-ESPNow)
+23
View File
@@ -0,0 +1,23 @@
# StackChan-RemoteControl-ESPNow
This repository is designed to remotely control StackChan servo movements via the `ESPNow` protocol.
## Applicable Devices
* StickC-Plus + Hat Mini JoyC
## Compilation Environment
* IDFESP-IDF v5.4.2
* Device Typeesp32
## Compilation and Flashing
1. Before compilation, globally search the project for `__has_include(<driver/i2c_master.h>)` in `M5GFX` and replace all occurrences with `0`.
2. When flashing, specify the baud rate as `1500000`.
## Package Firmware
```
esptool.py --chip esp32 merge_bin -o StackChan-RemoteControl-ESPNow-jyy-20251231_0x0.bin 0x1000 build\bootloader\bootloader.bin 0x8000 build\partition_table\partition-table.bin 0x10000 build\StackChan-RemoteControl-ESPNow.bin
```
+77
View File
@@ -0,0 +1,77 @@
dependencies:
espressif/cmake_utilities:
component_hash: 351350613ceafba240b761b4ea991e0f231ac7a9f59a9ee901f751bddc0bb18f
dependencies:
- name: idf
require: private
version: '>=4.1'
source:
registry_url: https://components.espressif.com
type: service
version: 0.5.3
espressif/esp-now:
component_hash: 56f902e978ec0b70528ad30a45265b56bf2b91653d13e0badc78159f39f41ece
dependencies:
- name: espressif/cmake_utilities
registry_url: https://components.espressif.com
require: private
version: 0.*
- name: idf
require: private
version: '>=4.4'
source:
registry_url: https://components.espressif.com/
type: service
version: 2.5.2
espressif/i2c_bus:
component_hash: 4e990dc11734316186b489b362c61d41f23f79d58bc169795cec215e528cba14
dependencies:
- name: espressif/cmake_utilities
registry_url: https://components.espressif.com
require: private
version: '*'
- name: idf
require: private
version: '>=4.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 1.5.0
idf:
source:
type: idf
version: 5.4.2
lvgl/lvgl:
component_hash: d7c1ac037ae6e85d94897f807d6e7ba0946a83e720074fc95a4f6241da9f9f53
dependencies: []
source:
registry_url: https://components.espressif.com/
type: service
version: 8.4.0
m5stack/m5gfx:
component_hash: 4c420c89ae7bfe33231dab80b784f4508591279b2a3a935ac849dddb1942d0d5
dependencies: []
source:
registry_url: https://components.espressif.com
type: service
version: 0.2.17
m5stack/m5unified:
component_hash: 1c75bb80654da6c7fcdd11ef7a1cb9b7d6db2e98f96612a4babf12b5e9bc7196
dependencies:
- name: m5stack/m5gfx
registry_url: https://components.espressif.com
require: private
version: ^0.2.17
source:
registry_url: https://components.espressif.com/
type: service
version: 0.2.11
direct_dependencies:
- espressif/esp-now
- espressif/i2c_bus
- idf
- lvgl/lvgl
- m5stack/m5unified
manifest_hash: 1a633f7edf3e64c57d1f921f15913b2bf6deda0e71113957a364b6552fa37e9b
target: esp32
version: 2.0.0
+19
View File
@@ -0,0 +1,19 @@
set(SOURCES
esp_now/esp_now_init.c
joystick/joystick_handle.c
ui/ui_running_screen.c
ui/ui_setup_screen.c
ui/ui_imu_screen.c
ui/ui.c
ui/updown_img.c
lvgl_port.cpp
StackChan-RemoteControl-ESPNow.cpp
)
idf_component_register(SRCS ${SOURCES}
INCLUDE_DIRS
"."
esp_now
joystick
ui
)
@@ -0,0 +1,113 @@
#include "M5Unified.h"
extern "C" {
#include <stdio.h>
#include "esp_log.h"
#include "string.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "lvgl.h"
#include "ui.h"
#include "esp_now_init.h"
#include "joystick_handle.h"
#include "lvgl_port.h"
using namespace m5;
joystick_data_t joystick_data;
// extern void lvgl_port_init(M5GFX &gfx);
/**
* @brief Handle Button Press.
* 1. Press BtnA to switch setup_mode UI and running_mode UI.
* 2. Press BtnB to switch espnow-channel or id on setup_mode;
* 3. Press BtnB to send btnB_status to remote on running_mode.
*/
void handle_button_press()
{
static uint8_t screen_mode = MODE_SETUP;
// check if BtnA is pressed
if (M5.BtnA.wasPressed()) {
// use BtnA to switch mode
screen_mode = (screen_mode + 1) % 3;
if (screen_mode == MODE_SETUP) {
// in setup mode, press A to enter running mode
joystick_data.screen_mode = MODE_SETUP;
switch_screen(joystick_data.screen_mode);
} else if (screen_mode == MODE_RUNNING) {
// in running mode, press A to enter IMU mode
wifi_espnow_reinit(joystick_data.channel);
joystick_data.screen_mode = MODE_RUNNING;
switch_screen(joystick_data.screen_mode);
} else if (screen_mode == MODE_IMU) {
// in IMU mode, press A to return to setup mode
joystick_data.screen_mode = MODE_IMU;
switch_screen(joystick_data.screen_mode);
}
}
if (M5.BtnB.wasPressed()) {
if (joystick_data.screen_mode == MODE_SETUP) {
joystick_data.select_mode = !joystick_data.select_mode;
} else if ((joystick_data.screen_mode == MODE_RUNNING) || (joystick_data.screen_mode == MODE_IMU)) {
joystick_data.btnB_status = !joystick_data.btnB_status;
}
}
}
void app_main(void)
{
imu_data_t imu_data;
// Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
M5.begin();
M5.Imu.init(&M5.In_I2C); // init IMU with internal I2C port
printf("IN_I2C port: %d\n", M5.In_I2C.getPort());
printf("M5 Display width: %ld, height: %ld\n", M5.Display.width(), M5.Display.height());
joystick_data = joystick_init(); // init joystick
lvgl_port_init(); // init LVGL
ui_init(); // init UI
// init WiFi and ESP-NOW
wifi_espnow_init(joystick_data.channel);
xTaskCreate(handle_setup_screen, "handle_setup_screen", 8192, &joystick_data, 5, NULL); // handle setup mode
xTaskCreate(handle_running_screen, "handle_running_screen", 8192, &joystick_data, 5, NULL); // handle running mode
xTaskCreate(handle_imu_screen, "handle_imu_screen", 8192, &joystick_data, 5, NULL);
while (1) {
M5.update();
// Handle button press
handle_button_press();
joystick_data.bat = (M5.Power.Axp192.getBatteryLevel()); // updata battery level
joystick_data.bat = (joystick_data.bat > 100) ? 100 : joystick_data.bat;
joystick_data.bat = (joystick_data.bat < 0) ? 0 : joystick_data.bat;
M5.Imu.update(); // update IMU data
imu_data = M5.Imu.getImuData(); // get IMU data
joystick_data.accel_x = imu_data.accel.x;
joystick_data.accel_y = imu_data.accel.y;
joystick_data.accel_z = imu_data.accel.z;
#if 0
printf("Accel: (%.2f, %.2f, %.2f), Gyro: (%.2f, %.2f, %.2f)\n",
joystick_data.accel_x, joystick_data.accel_y, joystick_data.accel_z,
joystick_data.gyro_x, joystick_data.gyro_y, joystick_data.gyro_z);
#endif
vTaskDelay(20 / portTICK_PERIOD_MS);
}
}
}
+123
View File
@@ -0,0 +1,123 @@
#include "esp_now_init.h"
/**
* @brief Initialize WiFi in STA mode and ESP-NOW with the specified channel
* @param channel The WiFi channel to use (1-13)
* @note This function initializes both WiFi subsystem in Station mode and ESP-NOW for communication
* @details
* 1. Initializes network interface
* 2. Creates default event loop
* 3. Initializes WiFi with default configuration
* 4. Sets WiFi storage to RAM only
* 5. Configures WiFi mode to Station (STA)
* 6. Starts WiFi
* 7. Sets the specified WiFi channel
* 8. Optionally enables long range protocol if CONFIG_ESPNOW_ENABLE_LONG_RANGE is defined
* 9. Configures ESP-NOW with forwarding disabled, 5 retry attempts, and receive disabled
* 10. Initializes ESP-NOW with the configured parameters
* 11. Reads and logs the device MAC address
* @warning This function combines both WiFi and ESP-NOW initialization in a single call
*/
void wifi_espnow_init(uint8_t channel)
{
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_ERROR_CHECK(esp_wifi_set_channel(channel, WIFI_SECOND_CHAN_NONE));
#if CONFIG_ESPNOW_ENABLE_LONG_RANGE
ESP_ERROR_CHECK(esp_wifi_set_protocol(
ESPNOW_WIFI_IF, WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N | WIFI_PROTOCOL_LR));
#endif
espnow_config_t espnow_config = ESPNOW_INIT_CONFIG_DEFAULT();
espnow_config.forward_enable = false;
espnow_config.forward_switch_channel = false;
espnow_config.send_retry_num = 5;
espnow_config.receive_enable.forward = false;
espnow_config.receive_enable.data = false;
espnow_init(&espnow_config);
uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_EFUSE_FACTORY);
ESP_LOGI("espnow_init", "ESP-NOW initialized with MAC: %02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2],
mac[3], mac[4], mac[5]);
}
/**
* @brief Reinitialize WiFi and ESP-NOW with a new channel
* @param new_channel The new WiFi channel to use (1-13)
* @return uint8_t The actual channel that was set
* @note This function properly deinitializes and reinitializes both WiFi and ESP-NOW
* @details
* 1. Checks if the new channel is different from current channel
* 2. Deinitializes ESP-NOW
* 3. Stops WiFi
* 4. Restarts WiFi and sets the new channel
* 5. Reinitializes ESP-NOW with the same configuration
* 6. Logs the MAC address and current channel
* @warning This function will temporarily interrupt ESP-NOW communication during reinitialization
*/
int wifi_espnow_reinit(uint8_t new_channel)
{
uint8_t channel = 0;
if (new_channel == channel) {
ESP_LOGI("wifi reinit", "New Channel is same as current channel, no need to reinitialize");
return channel;
}
// ESP_LOGI("reinit", "Reinitializing WiFi and ESP-NOW with channel: %d", new_channel);
// 1. Deinitialize ESP-NOW
espnow_deinit();
// 2. Stop WiFi
ESP_ERROR_CHECK(esp_wifi_stop());
// 3. Restart WiFi and set new channel
ESP_ERROR_CHECK(esp_wifi_start());
ESP_ERROR_CHECK(esp_wifi_set_channel(new_channel, WIFI_SECOND_CHAN_NONE));
// ESP_LOGI("reinit", "WiFi channel set to: %d", new_channel);
// 4. Reinitialize ESP-NOW
espnow_config_t espnow_config = ESPNOW_INIT_CONFIG_DEFAULT();
espnow_config.forward_enable = false;
espnow_config.forward_switch_channel = false;
espnow_config.send_retry_num = 5;
espnow_config.receive_enable.forward = false;
espnow_config.receive_enable.data = false;
espnow_init(&espnow_config);
uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_EFUSE_FACTORY);
ESP_LOGI("reinit", "ESP-NOW reinitialized with MAC: %02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3],
mac[4], mac[5]);
wifi_second_chan_t second;
esp_wifi_get_channel(&channel, &second);
ESP_LOGI("WiFi", "Current channel: %d", channel);
return channel;
}
/**
* @brief Send data packet via ESP-NOW broadcast
* @param pkt Pointer to the data packet to send
* @param len Length of the data packet in bytes
* @note This function sends data using ESP-NOW broadcast address
* @details
* 1. Creates default ESP-NOW frame header
* 2. Sends data using ESPNOW_DATA_TYPE_DATA type
* 3. Uses broadcast address to send to all devices on the same channel
* 4. Blocks until transmission completes (portMAX_DELAY timeout)
*/
void espnow_send_data(uint8_t *pkt, size_t len)
{
espnow_frame_head_t frame_head = ESPNOW_FRAME_CONFIG_DEFAULT();
ESP_ERROR_CHECK(espnow_send(ESPNOW_DATA_TYPE_DATA, ESPNOW_ADDR_BROADCAST, pkt, len, &frame_head, portMAX_DELAY));
}
+23
View File
@@ -0,0 +1,23 @@
#ifndef __ESP_NOW_INIT_H__
#define __ESP_NOW_INIT_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "esp_err.h"
#include <esp_mac.h>
#include <espnow.h>
#include <espnow_storage.h>
#include <espnow_utils.h>
#include "esp_wifi.h"
void wifi_espnow_init(uint8_t channel);
int wifi_espnow_reinit(uint8_t new_channel);
void espnow_send_data(uint8_t *pkt, size_t len);
#ifdef __cplusplus
}
#endif
#endif
+20
View File
@@ -0,0 +1,20 @@
## IDF Component Manager Manifest File
dependencies:
## Required IDF version
idf:
version: '>=4.1.0'
# # Put list of dependencies here
# # For components maintained by Espressif:
# component: "~1.0.0"
# # For 3rd party components:
# username/component: ">=1.0.0,<2.0.0"
# username2/component2:
# version: "~1.0.0"
# # For transient dependencies `public` flag can be set.
# # `public` flag doesn't have an effect dependencies of the `main` component.
# # All dependencies of `main` are public by default.
# public: true
m5stack/m5unified: ^0.2.11
espressif/esp-now: =*
espressif/i2c_bus: ^1.5.0
lvgl/lvgl: ^8.4.0
@@ -0,0 +1,29 @@
#ifndef _JOYSTICK_BASIC_H_
#define _JOYSTICK_BASIC_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int channel;
int id;
int8_t bat;
uint16_t joyX;
uint16_t joyY;
uint8_t screen_mode;
uint8_t select_mode;
bool btnB_status;
float accel_x;
float accel_y;
float accel_z;
} joystick_data_t;
extern joystick_data_t joystick_data;
#ifdef __cplusplus
}
#endif
#endif
+279
View File
@@ -0,0 +1,279 @@
#include "joystick_handle.h"
i2c_bus_device_handle_t i2c_device1; // i2c device handle
/**
* @brief Initialize joystick via I2C interface
* @note This is an internal static function that configures I2C_NUM_0 as master with SDA on GPIO0 and SCL on GPIO26
* @details
* 1. Configures I2C master mode with 100kHz clock speed
* 2. Creates I2C bus handle using I2C_NUM_0
* 3. Scans the I2C bus to detect connected devices and logs their addresses
* 4. Creates device handle for joystick at I2C address 0x54
* 5. Assigns the device handle to global variable [i2c_device1]
* @warning This function assumes the joystick device is at I2C address 0x54
*/
static void joystick_i2c_init()
{
i2c_config_t conf;
{
conf.mode = I2C_MODE_MASTER;
conf.sda_io_num = 0;
conf.scl_io_num = 26;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = 100000;
conf.clk_flags = 0;
};
i2c_bus_handle_t i2c0_bus = i2c_bus_create(I2C_NUM_0, &conf);
uint8_t buf[128];
memset(buf, 0, sizeof(buf));
i2c_bus_scan(i2c0_bus, buf, sizeof(buf));
for (size_t i = 0; i < sizeof(buf); i++) {
if (buf[i] != 0) {
ESP_LOGI("I2C Scanner", "Found device at address 0x%02X", buf[i]);
}
}
i2c_device1 = i2c_bus_device_create(i2c0_bus, 0x54, 0);
}
/**
* @brief Read X and Y axis values from the joystick via I2C
* @param joyX Pointer to store X-axis value (16-bit unsigned integer)
* @param joyY Pointer to store Y-axis value (16-bit unsigned integer)
* @return void
* @details
* 1. Reads 2 bytes from register address 0x00 (X-axis low/high bytes)
* 2. Waits 10ms to ensure data stability
* 3. Reads 2 bytes from register address 0x02 (Y-axis low/high bytes)
* 4. Combines high and low bytes for both X and Y axes using bit shifting
* 5. Stores the combined values in the provided pointers
* @warning This function assumes the joystick provides 16-bit data in little-endian format
*/
static void joystick_read_xy(uint16_t *joyX, uint16_t *joyY)
{
uint8_t data[4];
esp_err_t ret = i2c_bus_read_bytes(i2c_device1, 0x00, 2, data);
vTaskDelay(20 / portTICK_PERIOD_MS);
ret |= i2c_bus_read_bytes(i2c_device1, 0x02, 2, &data[2]);
if (ret == ESP_OK) {
*joyX = (data[1] << 8) | data[0];
*joyY = (data[3] << 8) | data[2];
} else {
// ESP_LOGE("I2C Joystick", "Failed to read joystick data");
}
}
/**
* @brief Public interface to initialize the joystick and return default configuration
* @return joystick_data_t Structure containing initialized joystick parameters
* @note This is the main initialization function exposed to users
* @details
* 1. Calls internal device_joystick_init()
* 2. Initializes all fields of 'joystick_data_t'
* - channel: 1 (default communication channel)
* - id: 0 (default target ID)
* - bat: 0 (battery level, to be updated later)
* - joyX, joyY: 0 (initial joystick positions)
* - screen_mode: MODE_SETUP (start in setup mode)
* - select_mode: CHANNEL_SELECT (default selection mode)
* @return joystick_data_t
*/
joystick_data_t joystick_init()
{
joystick_i2c_init();
joystick_data_t tmp;
tmp.channel = 1;
tmp.id = 0;
tmp.bat = 0;
tmp.joyX = 0;
tmp.joyY = 0;
tmp.accel_x = 0.0f;
tmp.accel_y = 0.0f;
tmp.accel_z = 0.0f;
tmp.screen_mode = MODE_SETUP;
tmp.select_mode = CHANNEL_SELECT;
tmp.btnB_status = false;
return tmp;
}
/**
* @brief Task to handle joystick setup screen
* @param pvParam Pointer to joystick data, pointing to joystick_data_t structure
* @note This function runs an infinite loop that continuously reads joystick XY coordinates
* and updates the setup screen when the screen mode is MODE_SETUP
* @details Reads raw joystick data and then calls update_setup_screen function to update screen display
* Each loop iteration has a 50ms delay to ensure interface responsiveness
*/
void handle_setup_screen(void *pvParam)
{
joystick_data_t *joystick_data = (joystick_data_t *)pvParam;
while (1) {
if (joystick_data->screen_mode == MODE_SETUP) {
joystick_read_xy(&joystick_data->joyX, &joystick_data->joyY);
update_setup_screen(joystick_data);
vTaskDelay(50 / portTICK_PERIOD_MS);
} else {
vTaskDelay(200 / portTICK_PERIOD_MS);
}
}
}
/**
* @brief Task to handle joystick running screen, responsible for reading joystick data and sending ESP-NOW control
* packets
* @param pvParam Pointer to joystick data, pointing to joystick_data_t structure
* @note This function runs an infinite loop that reads joystick input, processes data, and sends control packets in
* running mode
* @details
* 1. Reads raw X/Y values from the joystick via I2C
* 2. Updates the running screen display with current values
* 3. Applies deadzone correction to center the joystick values
* 4. Maps raw values to yaw/pitch angle ranges (-1280 to 1280 for yaw, 0 to 900 for pitch)
* 5. Only sends data when changes exceed threshold (5 units) to reduce network traffic
* 6. Constructs and sends ESP-NOW packet containing target ID, yaw, pitch, speed and button status
* 7. Each loop iteration has a 30ms delay when in running mode
*/
void handle_running_screen(void *pvParam)
{
joystick_data_t *joystick_data = (joystick_data_t *)pvParam;
// communicate packet
uint8_t pkt[8];
pkt[0] = joystick_data->id; // id: 0 for broadcast
int16_t yaw_angle = 0;
int16_t pitch_angle = 0;
int16_t last_yaw = 0;
int16_t last_pitch = 0;
int16_t speed_val = 600;
while (1) {
// update screen and send packet when in running mode
if (joystick_data->screen_mode == MODE_RUNNING) {
joystick_read_xy(&joystick_data->joyX, &joystick_data->joyY);
if (running_screen != NULL && lv_obj_is_valid(running_screen)) {
update_running_screen(joystick_data->joyX, joystick_data->joyY, joystick_data->channel,
joystick_data->id, joystick_data->bat);
}
// handle data from joystick
if ((joystick_data->joyX < X_CENTER + DEAD_ZONE) && (joystick_data->joyX > X_CENTER - DEAD_ZONE)) {
joystick_data->joyX = X_CENTER;
}
if ((joystick_data->joyY < Y_CENTER + DEAD_ZONE) && (joystick_data->joyY > Y_CENTER - DEAD_ZONE)) {
joystick_data->joyY = Y_CENTER;
}
yaw_angle = (int16_t)map(joystick_data->joyX, X_MIN, X_MAX, 1280, -1280);
pitch_angle = (int16_t)map(joystick_data->joyY, Y_MIN, Y_MAX, 0, 900);
// send pitch_angle and yaw_angle only when changes exceed threshold
if (abs(yaw_angle - last_yaw) < 5 && abs(pitch_angle - last_pitch) < 5) {
if (pkt[7] != joystick_data->btnB_status) {
pkt[7] = joystick_data->btnB_status;
espnow_send_data(pkt, sizeof(pkt));
}
vTaskDelay(30 / portTICK_PERIOD_MS);
continue;
}
pkt[0] = joystick_data->id;
memcpy(&pkt[1], &yaw_angle, sizeof(int16_t));
memcpy(&pkt[3], &pitch_angle, sizeof(int16_t));
memcpy(&pkt[5], &speed_val, sizeof(int16_t));
pkt[7] = joystick_data->btnB_status;
#if 0
ESP_LOGI("handle_running_screen", "Yaw: %d, Pitch: %d, Speed: %d, id: %u, Button: %u",
yaw_angle, pitch_angle, speed_val, joystick_data->id, joystick_data->btnB_status);
#endif
last_yaw = yaw_angle;
last_pitch = pitch_angle;
espnow_send_data(pkt, sizeof(pkt));
vTaskDelay(30 / portTICK_PERIOD_MS);
} else {
vTaskDelay(200 / portTICK_PERIOD_MS);
}
}
}
/**
* @brief Task to handle joystick IMU screen functionality, processing IMU sensor data and sending ESP-NOW control
* packets
*
* This function runs an infinite loop that reads IMU sensor data (accelerometer and gyroscope),
* updates the IMU visualization screen, processes the angle data to control remote devices,
* and sends ESP-NOW packets with the processed control information.
* The function maps the IMU pitch and roll angles to yaw and pitch values for remote control,
* applies filtering to reduce unnecessary transmissions, and sends control packets at regular intervals.
*
* @param pvParam Pointer to joystick data structure containing IMU sensor values, battery level,
* device ID, communication channel, and other control parameters
* @details
* 1. Continuously reads IMU data (acceleration and gyro values) from the joystick_data structure
* 2. Updates the IMU screen visualization with current sensor values
* 3. Limits roll values to range [-1.5, 1.5] and pitch values to range [0, 1.5]
* 4. Maps limited angle values to appropriate yaw/pitch ranges for remote control (-1280 to 1280 for yaw, 900 to 0
* for pitch)
* 5. Only sends control packets when changes exceed threshold (10 units) to minimize network traffic
* 6. Constructs and transmits ESP-NOW packet with device ID, yaw, pitch, speed, and button status
* 7. Includes a 50ms delay between iterations when in IMU mode, 200ms otherwise
*/
void handle_imu_screen(void *pvParam)
{
joystick_data_t *joystick_data = (joystick_data_t *)pvParam;
static IMU_Angle_t last_imu_angle = {0.0f, 0.0f};
// communicate packet
uint8_t pkt[8];
pkt[0] = joystick_data->id; // id: 0 for broadcast
int16_t yaw_angle = 0;
int16_t pitch_angle = 0;
int16_t last_yaw = 0;
int16_t last_pitch = 0;
int16_t speed_val = 600;
while (1) {
// update screen and send packet when in running mode
if (joystick_data->screen_mode == MODE_IMU) {
IMU_Angle_t imu_angle =
update_imu_screen(joystick_data->accel_x, joystick_data->accel_y, joystick_data->accel_z,
joystick_data->bat, joystick_data->id, joystick_data->channel);
// Limit the roll value to the range of -1.5 to 1.5
float limited_roll = fmaxf(-1.5f, fminf(1.5f, imu_angle.roll));
// Limit the pitch value to the range of 0 to 1.5
float limited_pitch = fmaxf(0.0f, fminf(1.5f, imu_angle.pitch));
yaw_angle = (int16_t)map(limited_roll, -1.5, 1.5, -1280, 1280);
pitch_angle = (int16_t)map(limited_pitch, 0, 1.5, 900, 0);
if (abs(yaw_angle - last_yaw) < 10 && abs(last_pitch - pitch_angle) < 10) {
vTaskDelay(30 / portTICK_PERIOD_MS);
continue;
}
last_yaw = yaw_angle;
last_pitch = pitch_angle;
pkt[0] = joystick_data->id;
memcpy(&pkt[1], &yaw_angle, sizeof(int16_t));
memcpy(&pkt[3], &pitch_angle, sizeof(int16_t));
memcpy(&pkt[5], &speed_val, sizeof(int16_t));
pkt[7] = joystick_data->btnB_status;
espnow_send_data(pkt, sizeof(pkt));
#if 0
// ESP_LOGI("handle_imu_screen", "yaw_angle: %.2f, pitch_angle:%.2f, yaw: %d, pitch: %d\n",
imu_angle.roll, imu_angle.pitch, yaw_angle, pitch_angle);
#endif
vTaskDelay(30 / portTICK_PERIOD_MS);
} else {
vTaskDelay(200 / portTICK_PERIOD_MS);
}
}
}
@@ -0,0 +1,28 @@
#ifndef __JOYSTICK_HANDLE_H__
#define __JOYSTICK_HANDLE_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "driver/i2c.h"
#include "i2c_bus.h"
#include "hal/i2c_types.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "../esp_now/esp_now_init.h"
#include "../ui/ui_setup_screen.h"
#include "../ui/ui_running_screen.h"
#include "../ui/ui_imu_screen.h"
#include "joystick_basic.h"
joystick_data_t joystick_init();
void handle_setup_screen(void *pvParam);
void handle_running_screen(void *pvParam);
void handle_imu_screen(void *pvParam);
#ifdef __cplusplus
}
#endif
#endif
+117
View File
@@ -0,0 +1,117 @@
#include "lvgl_port.h"
#include <M5Unified.h>
#include "M5GFX.h"
extern "C" {
#define LV_BUFFER_LINE 40
static SemaphoreHandle_t xGuiSemaphore;
static void lvgl_tick_timer(void *arg)
{
(void)arg;
lv_tick_inc(10);
}
static void lvgl_rtos_task(void *pvParameter)
{
(void)pvParameter;
while (1) {
if (pdTRUE == xSemaphoreTake(xGuiSemaphore, portMAX_DELAY)) {
lv_timer_handler();
xSemaphoreGive(xGuiSemaphore);
}
vTaskDelay(pdMS_TO_TICKS(10));
}
}
static lv_disp_draw_buf_t draw_buf;
static void lvgl_flush_cb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p)
{
M5GFX &gfx = *(M5GFX *)disp->user_data;
int w = (area->x2 - area->x1 + 1);
int h = (area->y2 - area->y1 + 1);
uint32_t pixels = w * h;
M5.Display.startWrite();
M5.Display.setAddrWindow(area->x1, area->y1, w, h);
// Critical fix: Use safe pixel writing method to avoid M5GFX SIMD optimizations
// Break large transfers into small chunks to avoid problematic copy_rgb_fast function
const uint32_t SAFE_CHUNK_SIZE = 8192; // 8K pixels per chunk, suitable for small buffer settings
if (pixels > SAFE_CHUNK_SIZE) {
// Chunked transmission for large data
const lgfx::rgb565_t *src = (const lgfx::rgb565_t *)color_p;
uint32_t remaining = pixels;
uint32_t offset = 0;
while (remaining > 0) {
uint32_t chunk_size = (remaining > SAFE_CHUNK_SIZE) ? SAFE_CHUNK_SIZE : remaining;
M5.Display.writePixels(src + offset, chunk_size);
offset += chunk_size;
remaining -= chunk_size;
}
} else {
// Direct transmission for small data
M5.Display.writePixels((lgfx::rgb565_t *)color_p, pixels);
}
M5.Display.endWrite();
lv_disp_flush_ready(disp);
}
// BtnA / BtnB
static void lvgl_read_cb(lv_indev_drv_t *indev_driver, lv_indev_data_t *data)
{
}
void lvgl_port_init(void)
{
lv_init();
size_t buffer_size = M5.Display.width() * LV_BUFFER_LINE * sizeof(lv_color_t);
static lv_color_t *buf1 = (lv_color_t *)heap_caps_malloc(buffer_size, MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL);
if (buf1 == NULL) {
ESP_LOGE("LVGL", "Failed to allocate display buffer!");
return;
}
lv_disp_draw_buf_init(&draw_buf, buf1, NULL, M5.Display.width() * LV_BUFFER_LINE);
static lv_disp_drv_t disp_drv;
lv_disp_drv_init(&disp_drv);
disp_drv.hor_res = M5.Display.width();
disp_drv.ver_res = M5.Display.height();
disp_drv.flush_cb = lvgl_flush_cb;
disp_drv.draw_buf = &draw_buf;
disp_drv.user_data = &M5.Display;
lv_disp_drv_register(&disp_drv);
static lv_indev_drv_t indev_drv;
lv_indev_drv_init(&indev_drv);
indev_drv.type = LV_INDEV_TYPE_BUTTON;
indev_drv.read_cb = lvgl_read_cb;
// indev_drv.user_data = &gfx;
indev_drv.user_data = &M5.Display;
lv_indev_t *indev = lv_indev_drv_register(&indev_drv);
xGuiSemaphore = xSemaphoreCreateMutex();
const esp_timer_create_args_t periodic_timer_args = {.callback = &lvgl_tick_timer, .name = "lvgl_tick_timer"};
esp_timer_handle_t periodic_timer;
ESP_ERROR_CHECK(esp_timer_create(&periodic_timer_args, &periodic_timer));
ESP_ERROR_CHECK(esp_timer_start_periodic(periodic_timer, 10 * 1000));
xTaskCreate(lvgl_rtos_task, "lvgl_rtos_task", 4096, NULL, 1, NULL);
}
bool lvgl_port_lock(void)
{
return xSemaphoreTake(xGuiSemaphore, portMAX_DELAY) == pdTRUE ? true : false;
}
void lvgl_port_unlock(void)
{
xSemaphoreGive(xGuiSemaphore);
}
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef LVGL_PORT_H
#define LVGL_PORT_H
#include "lvgl.h"
#include "esp_log.h"
#ifdef __cplusplus
extern "C" {
#endif
void lvgl_port_init(void);
bool lvgl_port_lock(void);
void lvgl_port_unlock(void);
#ifdef __cplusplus
}
#endif
#endif // LVGL_PORT_H
File diff suppressed because it is too large Load Diff
+93
View File
@@ -0,0 +1,93 @@
#include "ui.h"
/**
* @brief Switches between different UI screens based on the provided screen ID
*
* This function manages the display of different UI screens (setup, running, IMU)
* by checking if the requested screen exists, creating it if necessary, validating
* the screen object, and then loading it with a slide-left animation effect.
*
* The function implements error handling by destroying and recreating invalid screens
* using goto statements for retry logic. Each screen type has its own creation
* and validation flow.
*
* @param screen_id An integer representing the target screen mode:
* - MODE_SETUP: Configuration/setup screen
* - MODE_RUNNING: Main operational screen
* - MODE_IMU: IMU data visualization screen
* - Any other value: Logs an error message
*
* @note The function uses LVGL's animation API to provide smooth screen transitions
* with a 200ms left slide animation. Thread safety should be considered when
* calling this function from different tasks.
*
* @warning This function relies on external screen objects and creation/destruction
* functions that must be implemented in other UI modules. The use of goto
* statements may affect code maintainability.
*/
void switch_screen(int screen_id)
{
if (screen_id == MODE_SETUP) {
setup_create:
if (setup_screen == NULL) {
create_setup_screen();
ESP_LOGI("UI", "Setup screen created");
}
// Load only if object is valid
if (setup_screen != NULL && lv_obj_is_valid(setup_screen)) {
ESP_LOGI("UI", "Setup screen loaded");
lv_scr_load_anim(setup_screen, LV_SCR_LOAD_ANIM_MOVE_LEFT, 200, 0, false);
} else {
ESP_LOGE("UI", "Setup screen is NULL or invalid!");
ui_setup_screen_destory();
goto setup_create;
}
} else if (screen_id == MODE_RUNNING) {
running_create:
if (running_screen == NULL) {
create_running_screen();
ESP_LOGI("UI", "Running screen created");
}
// Load only if object is valid
if (running_screen != NULL && lv_obj_is_valid(running_screen)) {
ESP_LOGI("UI", "Running screen loaded");
lv_scr_load_anim(running_screen, LV_SCR_LOAD_ANIM_MOVE_LEFT, 200, 0, false);
} else {
ESP_LOGE("UI", "Running screen is NULL or invalid!");
ui_running_screen_destory();
goto running_create;
}
} else if (screen_id == MODE_IMU) {
imu_create:
if (imu_screen == NULL) {
create_imu_screen();
ESP_LOGI("UI", "IMU screen created");
}
// Load only if object is valid
if (imu_screen != NULL && lv_obj_is_valid(imu_screen)) {
ESP_LOGI("UI", "IMU screen loaded");
lv_scr_load_anim(imu_screen, LV_SCR_LOAD_ANIM_MOVE_LEFT, 200, 0, false);
} else {
ESP_LOGE("UI", "Running screen is NULL or invalid!");
ui_imu_screen_destory();
goto imu_create;
}
} else {
ESP_LOGE("UI", "Invalid screen mode!");
}
}
/**
* @brief Initialize the UI system by creating and loading the initial setup screen
* @note This function serves as the entry point for UI initialization
* @details
* 1. Creates the setup screen using create_setup_screen()
* 2. Immediately loads the setup screen as the current display
* 3. Sets up the initial UI state for user interaction
* @warning This function should only be called once during application startup
*/
void ui_init()
{
create_setup_screen();
lv_disp_load_scr(setup_screen);
}
+15
View File
@@ -0,0 +1,15 @@
#ifndef UI_H
#define UI_H
#include "esp_log.h"
#include "lvgl.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "ui_setup_screen.h"
#include "ui_running_screen.h"
#include "ui_imu_screen.h"
void ui_init();
void switch_screen(int screen_id);
#endif

Some files were not shown because too many files have changed in this diff Show More