From 572723a9d462eb4ace481839dcd21756d2f3c250 Mon Sep 17 00:00:00 2001 From: step305 Date: Thu, 15 Oct 2026 21:54:16 +0300 Subject: [PATCH] Initial commit with submodules --- .gitignore | 2 + .gitmodules | 6 + .vscode/c_cpp_properties.json | 22 ++ .vscode/cmake-kits.json | 15 ++ .vscode/extensions.json | 9 + .vscode/launch.json | 52 +++++ .vscode/settings.json | 46 +++++ .vscode/tasks.json | 102 ++++++++++ CMakeLists.txt | 107 ++++++++++ FreeRTOS_Kernel_import.cmake | 91 +++++++++ freertos_sources/FreeRTOS-Kernel | 1 + freertos_sources/RPIPico2-Exp | 1 + pico_sdk_import.cmake | 121 +++++++++++ port/FreeRTOS-Kernel/FreeRTOSConfig.h | 167 +++++++++++++++ port/FreeRTOS-Kernel/IdleMemory.c | 77 +++++++ port/FreeRTOS-Kernel/cppMemory.cpp | 28 +++ port/FreeRTOS-Kernel/freertos_config.cmake | 18 ++ port/FreeRTOS-Kernel/freertos_unit.cmake | 18 ++ port/FreeRTOS-Kernel/logging_levels.h | 105 ++++++++++ port/FreeRTOS-Kernel/logging_stack.h | 180 +++++++++++++++++ .../port/FreeRTOS-Kernel/FreeRTOSConfig.h | 167 +++++++++++++++ .../port/FreeRTOS-Kernel/IdleMemory.c | 77 +++++++ .../port/FreeRTOS-Kernel/cppMemory.cpp | 28 +++ .../FreeRTOS-Kernel/freertos_config.cmake | 18 ++ .../port/FreeRTOS-Kernel/freertos_unit.cmake | 18 ++ .../port/FreeRTOS-Kernel/logging_levels.h | 105 ++++++++++ .../port/FreeRTOS-Kernel/logging_stack.h | 180 +++++++++++++++++ readme.md | 10 + readme_en.md | 61 ++++++ readme_ru.md | 62 ++++++ rtos_sample.cpp | 190 ++++++++++++++++++ testmaybeFreeRTOSConfig.h.txt | 167 +++++++++++++++ 32 files changed, 2251 insertions(+) create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 .vscode/c_cpp_properties.json create mode 100644 .vscode/cmake-kits.json create mode 100644 .vscode/extensions.json create mode 100644 .vscode/launch.json create mode 100644 .vscode/settings.json create mode 100644 .vscode/tasks.json create mode 100644 CMakeLists.txt create mode 100644 FreeRTOS_Kernel_import.cmake create mode 160000 freertos_sources/FreeRTOS-Kernel create mode 160000 freertos_sources/RPIPico2-Exp create mode 100644 pico_sdk_import.cmake create mode 100644 port/FreeRTOS-Kernel/FreeRTOSConfig.h create mode 100644 port/FreeRTOS-Kernel/IdleMemory.c create mode 100644 port/FreeRTOS-Kernel/cppMemory.cpp create mode 100644 port/FreeRTOS-Kernel/freertos_config.cmake create mode 100644 port/FreeRTOS-Kernel/freertos_unit.cmake create mode 100644 port/FreeRTOS-Kernel/logging_levels.h create mode 100644 port/FreeRTOS-Kernel/logging_stack.h create mode 100644 port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/FreeRTOSConfig.h create mode 100644 port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/IdleMemory.c create mode 100644 port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/cppMemory.cpp create mode 100644 port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/freertos_config.cmake create mode 100644 port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/freertos_unit.cmake create mode 100644 port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/logging_levels.h create mode 100644 port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/logging_stack.h create mode 100644 readme.md create mode 100644 readme_en.md create mode 100644 readme_ru.md create mode 100644 rtos_sample.cpp create mode 100644 testmaybeFreeRTOSConfig.h.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2435c20 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +build +!.vscode/* diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..3f7080b --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "freertos_sources/FreeRTOS-Kernel"] + path = freertos_sources/FreeRTOS-Kernel + url = https://github.com/step305/FreeRTOS-Kernel +[submodule "freertos_sources/RPIPico2-Exp"] + path = freertos_sources/RPIPico2-Exp + url = https://github.com/step305/RPIPico2-Exp diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..613c996 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,22 @@ +{ + "configurations": [ + { + "name": "Pico", + "includePath": [ + "${workspaceFolder}/**", + "${userHome}/.pico-sdk/sdk/2.3.1/**" + ], + "forcedInclude": [ + "${workspaceFolder}/build/generated/pico_base/pico/config_autogen.h", + "${userHome}/.pico-sdk/sdk/2.3.1/src/common/pico_base_headers/include/pico.h" + ], + "defines": [], + "compilerPath": "${userHome}/.pico-sdk/toolchain/15_2_Rel1/bin/arm-none-eabi-gcc.exe", + "compileCommands": "${workspaceFolder}/build/compile_commands.json", + "cStandard": "c17", + "cppStandard": "c++14", + "intelliSenseMode": "linux-gcc-arm" + } + ], + "version": 4 +} diff --git a/.vscode/cmake-kits.json b/.vscode/cmake-kits.json new file mode 100644 index 0000000..b0f3815 --- /dev/null +++ b/.vscode/cmake-kits.json @@ -0,0 +1,15 @@ +[ + { + "name": "Pico", + "compilers": { + "C": "${command:raspberry-pi-pico.getCompilerPath}", + "CXX": "${command:raspberry-pi-pico.getCxxCompilerPath}" + }, + "environmentVariables": { + "PATH": "${command:raspberry-pi-pico.getEnvPath};${env:PATH}" + }, + "cmakeSettings": { + "Python3_EXECUTABLE": "${command:raspberry-pi-pico.getPythonPath}" + } + } +] \ No newline at end of file diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..a940d7c --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,9 @@ +{ + "recommendations": [ + "marus25.cortex-debug", + "ms-vscode.cpptools", + "ms-vscode.cpptools-extension-pack", + "ms-vscode.vscode-serial-monitor", + "raspberry-pi.raspberry-pi-pico" + ] +} \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..451b846 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,52 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Pico Debug (Cortex-Debug)", + "cwd": "${userHome}/.pico-sdk/openocd/0.12.0+dev/scripts", + "executable": "${command:raspberry-pi-pico.launchTargetPath}", + "request": "launch", + "type": "cortex-debug", + "servertype": "openocd", + "serverpath": "${userHome}/.pico-sdk/openocd/0.12.0+dev/openocd.exe", + "gdbPath": "${command:raspberry-pi-pico.getGDBPath}", + "debuggerArgs": ["-ex", "set debug-file-directory /debug"], + "device": "${command:raspberry-pi-pico.getChipUppercase}", + "configFiles": [ + "interface/cmsis-dap.cfg", + "target/${command:raspberry-pi-pico.getTarget}.cfg" + ], + "svdFile": "${userHome}/.pico-sdk/sdk/2.3.1/src/${command:raspberry-pi-pico.getChip}/hardware_regs/${command:raspberry-pi-pico.getChipUppercase}.svd", + "runToEntryPoint": "main", + // Fix for no_flash binaries, where monitor reset halt doesn't do what is expected + // Also works fine for flash binaries + "overrideLaunchCommands": [ + "monitor reset init", + "load \"${command:raspberry-pi-pico.launchTargetPath}\"" + ], + "openOCDLaunchCommands": [ + "adapter speed 5000" + ] + }, + { + "name": "Pico Debug (Cortex-Debug with external OpenOCD)", + "cwd": "${workspaceRoot}", + "executable": "${command:raspberry-pi-pico.launchTargetPath}", + "request": "launch", + "type": "cortex-debug", + "servertype": "external", + "gdbTarget": "localhost:3333", + "gdbPath": "${command:raspberry-pi-pico.getGDBPath}", + "debuggerArgs": ["-ex", "set debug-file-directory /debug"], + "device": "${command:raspberry-pi-pico.getChipUppercase}", + "svdFile": "${userHome}/.pico-sdk/sdk/2.3.1/src/${command:raspberry-pi-pico.getChip}/hardware_regs/${command:raspberry-pi-pico.getChipUppercase}.svd", + "runToEntryPoint": "main", + // Fix for no_flash binaries, where monitor reset halt doesn't do what is expected + // Also works fine for flash binaries + "overrideLaunchCommands": [ + "monitor reset init", + "load \"${command:raspberry-pi-pico.launchTargetPath}\"" + ] + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..5b883ba --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,46 @@ +{ + "cmake.showSystemKits": false, + "cmake.options.statusBarVisibility": "hidden", + "cmake.options.advanced": { + "build": { + "statusBarVisibility": "hidden" + }, + "launch": { + "statusBarVisibility": "hidden" + }, + "debug": { + "statusBarVisibility": "hidden" + }, + "variant": { + "statusBarVisibility": "hidden" + }, + "buildTarget": { + "statusBarVisibility": "hidden" + } + }, + "cmake.configureOnEdit": false, + "cmake.automaticReconfigure": false, + "cmake.configureOnOpen": false, + "cmake.generator": "Ninja", + "cmake.cmakePath": "${userHome}/.pico-sdk/cmake/v4.3.4/bin/cmake", + "C_Cpp.debugShortcut": false, + "terminal.integrated.env.windows": { + "PICO_SDK_PATH": "${env:USERPROFILE}/.pico-sdk/sdk/2.3.1", + "PICO_TOOLCHAIN_PATH": "${env:USERPROFILE}/.pico-sdk/toolchain/15_2_Rel1", + "Path": "${env:USERPROFILE}/.pico-sdk/toolchain/15_2_Rel1/bin;${env:USERPROFILE}/.pico-sdk/picotool/2.3.1/picotool;${env:USERPROFILE}/.pico-sdk/cmake/v4.3.4/bin;${env:USERPROFILE}/.pico-sdk/ninja/v1.13.2;${env:PATH}" + }, + "terminal.integrated.env.osx": { + "PICO_SDK_PATH": "${env:HOME}/.pico-sdk/sdk/2.3.1", + "PICO_TOOLCHAIN_PATH": "${env:HOME}/.pico-sdk/toolchain/15_2_Rel1", + "PATH": "${env:HOME}/.pico-sdk/toolchain/15_2_Rel1/bin:${env:HOME}/.pico-sdk/picotool/2.3.1/picotool:${env:HOME}/.pico-sdk/cmake/v4.3.4/bin:${env:HOME}/.pico-sdk/ninja/v1.13.2:${env:PATH}" + }, + "terminal.integrated.env.linux": { + "PICO_SDK_PATH": "${env:HOME}/.pico-sdk/sdk/2.3.1", + "PICO_TOOLCHAIN_PATH": "${env:HOME}/.pico-sdk/toolchain/15_2_Rel1", + "PATH": "${env:HOME}/.pico-sdk/toolchain/15_2_Rel1/bin:${env:HOME}/.pico-sdk/picotool/2.3.1/picotool:${env:HOME}/.pico-sdk/cmake/v4.3.4/bin:${env:HOME}/.pico-sdk/ninja/v1.13.2:${env:PATH}" + }, + "raspberry-pi-pico.cmakeAutoConfigure": true, + "raspberry-pi-pico.useCmakeTools": false, + "raspberry-pi-pico.cmakePath": "${HOME}/.pico-sdk/cmake/v4.3.4/bin/cmake", + "raspberry-pi-pico.ninjaPath": "${HOME}/.pico-sdk/ninja/v1.13.2/ninja" +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..2f07d94 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,102 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "Compile Project", + "type": "process", + "isBuildCommand": true, + "command": "${userHome}/.pico-sdk/ninja/v1.13.2/ninja", + "args": ["-C", "${workspaceFolder}/build"], + "group": "build", + "presentation": { + "reveal": "always", + "panel": "dedicated" + }, + "problemMatcher": "$gcc", + "windows": { + "command": "${env:USERPROFILE}/.pico-sdk/ninja/v1.13.2/ninja.exe" + } + }, + { + "label": "Run Project", + "type": "process", + "command": "${env:HOME}/.pico-sdk/picotool/2.3.1/picotool/picotool", + "args": [ + "load", + "${command:raspberry-pi-pico.launchTargetPath}", + "-fx" + ], + "presentation": { + "reveal": "always", + "panel": "dedicated" + }, + "problemMatcher": [], + "windows": { + "command": "${env:USERPROFILE}/.pico-sdk/picotool/2.3.1/picotool/picotool.exe" + } + }, + { + "label": "Flash", + "type": "process", + "command": "${userHome}/.pico-sdk/openocd/0.12.0+dev/openocd.exe", + "args": [ + "-s", + "${userHome}/.pico-sdk/openocd/0.12.0+dev/scripts", + "-f", + "interface/cmsis-dap.cfg", + "-f", + "target/${command:raspberry-pi-pico.getTarget}.cfg", + "-c", + "adapter speed 5000; program \"${command:raspberry-pi-pico.launchTargetPath}\" verify reset exit" + ], + "problemMatcher": [], + "windows": { + "command": "${env:USERPROFILE}/.pico-sdk/openocd/0.12.0+dev/openocd.exe" + } + }, + { + "label": "Rescue Reset", + "type": "process", + "command": "${userHome}/.pico-sdk/openocd/0.12.0+dev/openocd.exe", + "args": [ + "-s", + "${userHome}/.pico-sdk/openocd/0.12.0+dev/scripts", + "-f", + "interface/cmsis-dap.cfg", + "-f", + "target/${command:raspberry-pi-pico.getChip}-rescue.cfg", + "-c", + "adapter speed 5000; reset halt; exit" + ], + "problemMatcher": [], + "windows": { + "command": "${env:USERPROFILE}/.pico-sdk/openocd/0.12.0+dev/openocd.exe" + } + }, + { + "label": "RISC-V Reset (RP2350)", + "type": "process", + "command": "${userHome}/.pico-sdk/openocd/0.12.0+dev/openocd.exe", + "args": [ + "-s", + "${userHome}/.pico-sdk/openocd/0.12.0+dev/scripts", + "-c", + "set USE_CORE { rv0 rv1 cm0 cm1 }", + "-f", + "interface/cmsis-dap.cfg", + "-f", + "target/rp2350.cfg", + "-c", + "adapter speed 5000; init;", + "-c", + "write_memory 0x40120158 8 { 0x3 }; echo [format \"Info : ARCHSEL 0x%02x\" [read_memory 0x40120158 8 1]];", + "-c", + "reset halt; targets rp2350.rv0; echo [format \"Info : ARCHSEL_STATUS 0x%02x\" [read_memory 0x4012015C 8 1]]; exit" + ], + "problemMatcher": [], + "windows": { + "command": "${env:USERPROFILE}/.pico-sdk/openocd/0.12.0+dev/openocd.exe" + } + } + ] +} diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..7496710 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,107 @@ +# Generated Cmake Pico project file +# Сгенерированный файл проекта CMake для Pico + +cmake_minimum_required(VERSION 3.13) + +# Set standard versions for C and C++ +# Установка стандартов языков C и C++ +set(CMAKE_C_STANDARD 11) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +# Initialise pico_sdk from installed location +# Инициализация pico_sdk из установленного местоположения +# (note this can come from environment, CMake cache etc) + +# == DO NOT EDIT THE FOLLOWING LINES for the Raspberry Pi Pico VS Code Extension to work == +# == НЕ РЕДАКТИРУЙТЕ СЛЕДУЮЩИЕ СТРОКИ для корректной работы расширения VS Code для Raspberry Pi Pico == +if(WIN32) + set(USERHOME $ENV{USERPROFILE}) +else() + set(USERHOME $ENV{HOME}) +endif() +set(sdkVersion 2.3.1) +set(toolchainVersion 15_2_Rel1) +set(picotoolVersion 2.3.1) +set(picoVscode ${USERHOME}/.pico-sdk/cmake/pico-vscode.cmake) +if (EXISTS ${picoVscode}) + include(${picoVscode}) +endif() +# ==================================================================================== + +# Define the target board as Pico 2 (RP2350) +# Определение целевой платы как Pico 2 (RP2350) +set(PICO_BOARD pico2 CACHE STRING "Board type") + +# Path to the FreeRTOS Kernel sources +# Путь к исходным кодам ядра FreeRTOS +set(PICO_FREERTOS "${CMAKE_CURRENT_LIST_DIR}/freertos_sources/FreeRTOS-Kernel") +message(STATUS "FreeRTOS Path: ${PICO_FREERTOS}") +message(STATUS "Путь к FreeRTOS: ${PICO_FREERTOS}") + +# Pull in Raspberry Pi Pico SDK (must be before project) +# Подключение Raspberry Pi Pico SDK (должно быть выполнено до определения проекта) +include(pico_sdk_import.cmake) + +project(rtos_sample C CXX ASM) + +# Disable standard Pico SDK C++ operator overrides to avoid conflicts with FreeRTOS heap management +# Отключаем стандартные переопределения операторов C++ в Pico SDK, чтобы избежать конфликтов с управлением кучей FreeRTOS +# For Pico SDK 2.x+ the target pico_cxx_options is used +# Для Pico SDK 2.x+ используется таргет pico_cxx_options +add_compile_definitions(PICO_CXX_ENABLE_NEW_DELETE_OVERRIDES=0) + +# Initialise the Raspberry Pi Pico SDK +# Инициализация Raspberry Pi Pico SDK +pico_sdk_init() + +# Configure FreeRTOS Kernel paths and configuration file location +# Настройка путей ядра FreeRTOS и расположения файла конфигурации +SET(FREERTOS_KERNEL_PATH "${PICO_FREERTOS}" CACHE STRING "MyFreeRTOStutorial") +SET(FREERTOS_CONFIG_FILE_DIRECTORY "${CMAKE_CURRENT_LIST_DIR}/port/FreeRTOS-Kernel" CACHE STRING "Local Config") + +# Include FreeRTOS configuration and kernel import scripts +# Подключение конфигурации FreeRTOS и скриптов импорта ядра +include("${FREERTOS_CONFIG_FILE_DIRECTORY}/freertos_config.cmake") +include(FreeRTOS_Kernel_import.cmake) + +# Add the main executable +# Добавление основного исполняемого файла +add_executable(rtos_sample rtos_sample.cpp ) + +# Set program name and version for the binary +# Установка имени и версии программы для бинарного файла +pico_set_program_name(rtos_sample "rtos_sample") +pico_set_program_version(rtos_sample "0.1") + +# Configure standard I/O: Disable UART, Enable USB +# Настройка стандартного ввода-вывода: Отключить UART, Включить USB +pico_enable_stdio_uart(rtos_sample 0) +pico_enable_stdio_usb(rtos_sample 1) + +# Link required libraries: FreeRTOS Kernel (Heap 4), config, and Pico stdlib +# Привязка необходимых библиотек: Ядро FreeRTOS (Heap 4), конфигурация и стандартная библиотека Pico +target_link_libraries(rtos_sample + FreeRTOS-Kernel-Heap4 + freertos_config + pico_stdlib) + +# EXPLICITLY tell Pico SDK not to use its own new_delete.cpp +# ЯВНО ГОВОРИМ PICO SDK НЕ ИСПОЛЬЗОВАТЬ СВОЙ new_delete.cpp +# This line must come AFTER pico_sdk_init() +# Эта строка должна идти ПОСЛЕ pico_sdk_init() +set_target_properties(pico_cxx_options PROPERTIES PICO_CXX_ENABLE_NEW_DELETE_OVERRIDES 0) + +# Allow multiple definitions (linker will take the first one found) +# Разрешает множественные определения (линкер возьмет первую попавшуюся функцию) +target_link_options(rtos_sample PRIVATE "-Wl,--allow-multiple-definition") + +# Add project root to include directories +# Добавление корня проекта в директории поиска заголовочных файлов +target_include_directories(rtos_sample PRIVATE + ${CMAKE_CURRENT_LIST_DIR} +) + +# Generate extra output files (e.g., .bin, .hex) +# Генерация дополнительных выходных файлов (например, .bin, .hex) +pico_add_extra_outputs(rtos_sample) diff --git a/FreeRTOS_Kernel_import.cmake b/FreeRTOS_Kernel_import.cmake new file mode 100644 index 0000000..15d8e77 --- /dev/null +++ b/FreeRTOS_Kernel_import.cmake @@ -0,0 +1,91 @@ +# This is a copy of /portable/ThirdParty/GCC/RP2040/FREERTOS_KERNEL_import.cmake + +# This can be dropped into an external project to help locate the FreeRTOS kernel +# It should be include()ed prior to project(). Alternatively this file may +# or the CMakeLists.txt in this directory may be included or added via add_subdirectory +# respectively. + +if (DEFINED ENV{FREERTOS_KERNEL_PATH} AND (NOT FREERTOS_KERNEL_PATH)) + set(FREERTOS_KERNEL_PATH $ENV{FREERTOS_KERNEL_PATH}) + message("Using FREERTOS_KERNEL_PATH from environment ('${FREERTOS_KERNEL_PATH}')") +endif () + +# first pass we look in old tree; second pass we look in new tree +foreach(SEARCH_PASS RANGE 0 1) + if (SEARCH_PASS) + # ports may be moving to submodule in the future + set(FREERTOS_KERNEL_RP2040_RELATIVE_PATH "portable/ThirdParty/Community-Supported-Ports/GCC") + set(FREERTOS_KERNEL_RP2040_BACK_PATH "../../../../..") + else() + set(FREERTOS_KERNEL_RP2040_RELATIVE_PATH "portable/ThirdParty/GCC") + set(FREERTOS_KERNEL_RP2040_BACK_PATH "../../../..") + endif() + + if(PICO_PLATFORM STREQUAL "rp2040") + set(FREERTOS_KERNEL_RP2040_RELATIVE_PATH "${FREERTOS_KERNEL_RP2040_RELATIVE_PATH}/RP2040") + else() + if (PICO_PLATFORM STREQUAL "rp2350-riscv") + set(FREERTOS_KERNEL_RP2040_RELATIVE_PATH "${FREERTOS_KERNEL_RP2040_RELATIVE_PATH}/RP2350_RISC-V") + else() + set(FREERTOS_KERNEL_RP2040_RELATIVE_PATH "${FREERTOS_KERNEL_RP2040_RELATIVE_PATH}/RP2350_ARM_NTZ") + endif() + endif() + + if (NOT FREERTOS_KERNEL_PATH) + # check if we are inside the FreeRTOS kernel tree (i.e. this file has been included directly) + get_filename_component(_ACTUAL_PATH ${CMAKE_CURRENT_LIST_DIR} REALPATH) + get_filename_component(_POSSIBLE_PATH ${CMAKE_CURRENT_LIST_DIR}/${FREERTOS_KERNEL_RP2040_BACK_PATH}/${FREERTOS_KERNEL_RP2040_RELATIVE_PATH} REALPATH) + if (_ACTUAL_PATH STREQUAL _POSSIBLE_PATH) + get_filename_component(FREERTOS_KERNEL_PATH ${CMAKE_CURRENT_LIST_DIR}/${FREERTOS_KERNEL_RP2040_BACK_PATH} REALPATH) + endif() + if (_ACTUAL_PATH STREQUAL _POSSIBLE_PATH) + get_filename_component(FREERTOS_KERNEL_PATH ${CMAKE_CURRENT_LIST_DIR}/${FREERTOS_KERNEL_RP2040_BACK_PATH} REALPATH) + message("Setting FREERTOS_KERNEL_PATH to ${FREERTOS_KERNEL_PATH} based on location of FreeRTOS-Kernel-import.cmake") + break() + elseif (PICO_SDK_PATH AND EXISTS "${PICO_SDK_PATH}/../FreeRTOS-Kernel") + set(FREERTOS_KERNEL_PATH ${PICO_SDK_PATH}/../FreeRTOS-Kernel) + message("Defaulting FREERTOS_KERNEL_PATH as sibling of PICO_SDK_PATH: ${FREERTOS_KERNEL_PATH}") + break() + endif() + endif () + + if (NOT FREERTOS_KERNEL_PATH) + foreach(POSSIBLE_SUFFIX Source FreeRTOS-Kernel FreeRTOS/Source) + # check if FreeRTOS-Kernel exists under directory that included us + set(SEARCH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}) + get_filename_component(_POSSIBLE_PATH ${SEARCH_ROOT}/${POSSIBLE_SUFFIX} REALPATH) + if (EXISTS ${_POSSIBLE_PATH}/${FREERTOS_KERNEL_RP2040_RELATIVE_PATH}/CMakeLists.txt) + get_filename_component(FREERTOS_KERNEL_PATH ${_POSSIBLE_PATH} REALPATH) + message("Setting FREERTOS_KERNEL_PATH to '${FREERTOS_KERNEL_PATH}' found relative to enclosing project") + break() + endif() + endforeach() + if (FREERTOS_KERNEL_PATH) + break() + endif() + endif() + + # user must have specified + if (FREERTOS_KERNEL_PATH) + if (EXISTS "${FREERTOS_KERNEL_PATH}/${FREERTOS_KERNEL_RP2040_RELATIVE_PATH}") + break() + endif() + endif() +endforeach () + +if (NOT FREERTOS_KERNEL_PATH) + message(FATAL_ERROR "FreeRTOS location was not specified. Please set FREERTOS_KERNEL_PATH.") +endif() + +set(FREERTOS_KERNEL_PATH "${FREERTOS_KERNEL_PATH}" CACHE PATH "Path to the FreeRTOS Kernel") + +get_filename_component(FREERTOS_KERNEL_PATH "${FREERTOS_KERNEL_PATH}" REALPATH BASE_DIR "${CMAKE_BINARY_DIR}") +if (NOT EXISTS ${FREERTOS_KERNEL_PATH}) + message(FATAL_ERROR "Directory '${FREERTOS_KERNEL_PATH}' not found") +endif() +if (NOT EXISTS ${FREERTOS_KERNEL_PATH}/${FREERTOS_KERNEL_RP2040_RELATIVE_PATH}/CMakeLists.txt) + message(FATAL_ERROR "Directory '${FREERTOS_KERNEL_PATH}' does not contain a '${PICO_PLATFORM}' port here: ${FREERTOS_KERNEL_RP2040_RELATIVE_PATH}") +endif() +set(FREERTOS_KERNEL_PATH ${FREERTOS_KERNEL_PATH} CACHE PATH "Path to the FreeRTOS_KERNEL" FORCE) + +add_subdirectory(${FREERTOS_KERNEL_PATH}/${FREERTOS_KERNEL_RP2040_RELATIVE_PATH} FREERTOS_KERNEL) diff --git a/freertos_sources/FreeRTOS-Kernel b/freertos_sources/FreeRTOS-Kernel new file mode 160000 index 0000000..4f7299d --- /dev/null +++ b/freertos_sources/FreeRTOS-Kernel @@ -0,0 +1 @@ +Subproject commit 4f7299d6ea746b27a9dd19e87af568e34bd65b15 diff --git a/freertos_sources/RPIPico2-Exp b/freertos_sources/RPIPico2-Exp new file mode 160000 index 0000000..0d00c41 --- /dev/null +++ b/freertos_sources/RPIPico2-Exp @@ -0,0 +1 @@ +Subproject commit 0d00c41df1536786b254d24c906c6e337ab550e1 diff --git a/pico_sdk_import.cmake b/pico_sdk_import.cmake new file mode 100644 index 0000000..d493cc2 --- /dev/null +++ b/pico_sdk_import.cmake @@ -0,0 +1,121 @@ +# This is a copy of /external/pico_sdk_import.cmake + +# This can be dropped into an external project to help locate this SDK +# It should be include()ed prior to project() + +# Copyright 2020 (c) 2020 Raspberry Pi (Trading) Ltd. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +# following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following +# disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +if (DEFINED ENV{PICO_SDK_PATH} AND (NOT PICO_SDK_PATH)) + set(PICO_SDK_PATH $ENV{PICO_SDK_PATH}) + message("Using PICO_SDK_PATH from environment ('${PICO_SDK_PATH}')") +endif () + +if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT} AND (NOT PICO_SDK_FETCH_FROM_GIT)) + set(PICO_SDK_FETCH_FROM_GIT $ENV{PICO_SDK_FETCH_FROM_GIT}) + message("Using PICO_SDK_FETCH_FROM_GIT from environment ('${PICO_SDK_FETCH_FROM_GIT}')") +endif () + +if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_PATH} AND (NOT PICO_SDK_FETCH_FROM_GIT_PATH)) + set(PICO_SDK_FETCH_FROM_GIT_PATH $ENV{PICO_SDK_FETCH_FROM_GIT_PATH}) + message("Using PICO_SDK_FETCH_FROM_GIT_PATH from environment ('${PICO_SDK_FETCH_FROM_GIT_PATH}')") +endif () + +if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_TAG} AND (NOT PICO_SDK_FETCH_FROM_GIT_TAG)) + set(PICO_SDK_FETCH_FROM_GIT_TAG $ENV{PICO_SDK_FETCH_FROM_GIT_TAG}) + message("Using PICO_SDK_FETCH_FROM_GIT_TAG from environment ('${PICO_SDK_FETCH_FROM_GIT_TAG}')") +endif () + +if (PICO_SDK_FETCH_FROM_GIT AND NOT PICO_SDK_FETCH_FROM_GIT_TAG) + set(PICO_SDK_FETCH_FROM_GIT_TAG "master") + message("Using master as default value for PICO_SDK_FETCH_FROM_GIT_TAG") +endif() + +set(PICO_SDK_PATH "${PICO_SDK_PATH}" CACHE PATH "Path to the Raspberry Pi Pico SDK") +set(PICO_SDK_FETCH_FROM_GIT "${PICO_SDK_FETCH_FROM_GIT}" CACHE BOOL "Set to ON to fetch copy of SDK from git if not otherwise locatable") +set(PICO_SDK_FETCH_FROM_GIT_PATH "${PICO_SDK_FETCH_FROM_GIT_PATH}" CACHE FILEPATH "location to download SDK") +set(PICO_SDK_FETCH_FROM_GIT_TAG "${PICO_SDK_FETCH_FROM_GIT_TAG}" CACHE FILEPATH "release tag for SDK") + +if (NOT PICO_SDK_PATH) + if (PICO_SDK_FETCH_FROM_GIT) + include(FetchContent) + set(FETCHCONTENT_BASE_DIR_SAVE ${FETCHCONTENT_BASE_DIR}) + if (PICO_SDK_FETCH_FROM_GIT_PATH) + get_filename_component(FETCHCONTENT_BASE_DIR "${PICO_SDK_FETCH_FROM_GIT_PATH}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}") + endif () + FetchContent_Declare( + pico_sdk + GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk + GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG} + ) + + if (NOT pico_sdk) + message("Downloading Raspberry Pi Pico SDK") + # GIT_SUBMODULES_RECURSE was added in 3.17 + if (${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.17.0") + FetchContent_Populate( + pico_sdk + QUIET + GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk + GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG} + GIT_SUBMODULES_RECURSE FALSE + + SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-src + BINARY_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-build + SUBBUILD_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-subbuild + ) + else () + FetchContent_Populate( + pico_sdk + QUIET + GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk + GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG} + + SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-src + BINARY_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-build + SUBBUILD_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-subbuild + ) + endif () + + set(PICO_SDK_PATH ${pico_sdk_SOURCE_DIR}) + endif () + set(FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR_SAVE}) + else () + message(FATAL_ERROR + "SDK location was not specified. Please set PICO_SDK_PATH or set PICO_SDK_FETCH_FROM_GIT to on to fetch from git." + ) + endif () +endif () + +get_filename_component(PICO_SDK_PATH "${PICO_SDK_PATH}" REALPATH BASE_DIR "${CMAKE_BINARY_DIR}") +if (NOT EXISTS ${PICO_SDK_PATH}) + message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' not found") +endif () + +set(PICO_SDK_INIT_CMAKE_FILE ${PICO_SDK_PATH}/pico_sdk_init.cmake) +if (NOT EXISTS ${PICO_SDK_INIT_CMAKE_FILE}) + message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' does not appear to contain the Raspberry Pi Pico SDK") +endif () + +set(PICO_SDK_PATH ${PICO_SDK_PATH} CACHE PATH "Path to the Raspberry Pi Pico SDK" FORCE) + +include(${PICO_SDK_INIT_CMAKE_FILE}) diff --git a/port/FreeRTOS-Kernel/FreeRTOSConfig.h b/port/FreeRTOS-Kernel/FreeRTOSConfig.h new file mode 100644 index 0000000..1c1d645 --- /dev/null +++ b/port/FreeRTOS-Kernel/FreeRTOSConfig.h @@ -0,0 +1,167 @@ +/* + * FreeRTOS V202111.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html + *----------------------------------------------------------*/ + +/* Scheduler Related */ +#define configUSE_PREEMPTION 1 +#define configUSE_TICKLESS_IDLE 1 //DeepSleep? +#define configUSE_IDLE_HOOK 0 +#define configUSE_TICK_HOOK 0 +#define configTICK_RATE_HZ ( ( TickType_t ) 1000 ) +#define configMAX_PRIORITIES 32 +#define configMINIMAL_STACK_SIZE ( configSTACK_DEPTH_TYPE ) 256 +#define configUSE_16_BIT_TICKS 0 + +#define configIDLE_SHOULD_YIELD 1 + +/* Synchronization Related */ +#define configUSE_MUTEXES 1 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configUSE_QUEUE_SETS 1 +#define configUSE_TIME_SLICING 1 +#define configUSE_NEWLIB_REENTRANT 0 +// todo need this for lwip FreeRTOS sys_arch to compile +#define configENABLE_BACKWARD_COMPATIBILITY 1 +#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 5 + +/* System */ +#define configSTACK_DEPTH_TYPE uint32_t +#define configMESSAGE_BUFFER_LENGTH_TYPE size_t + +/* Memory allocation related definitions. */ +#define configSUPPORT_STATIC_ALLOCATION 1 +#define configSUPPORT_DYNAMIC_ALLOCATION 1 +#define configTOTAL_HEAP_SIZE (128*1024) +#define configAPPLICATION_ALLOCATED_HEAP 0 + +/* Hook function related definitions. */ +#define configCHECK_FOR_STACK_OVERFLOW 1 +#define configUSE_MALLOC_FAILED_HOOK 0 +#define configUSE_DAEMON_TASK_STARTUP_HOOK 0 + +/* Run time and task stats gathering related definitions. */ +#define configGENERATE_RUN_TIME_STATS 0 +#define configUSE_TRACE_FACILITY 1 +#define configUSE_STATS_FORMATTING_FUNCTIONS 0 + +/* Co-routine related definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES 1 + +/* Software timer related definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) +#define configTIMER_QUEUE_LENGTH 10 +#define configTIMER_TASK_STACK_DEPTH 1024 + +/* Interrupt nesting behaviour configuration. */ +/* +#define configKERNEL_INTERRUPT_PRIORITY [dependent of processor] +#define configMAX_SYSCALL_INTERRUPT_PRIORITY [dependent on processor and application] +#define configMAX_API_CALL_INTERRUPT_PRIORITY [dependent on processor and application] +*/ + +// Single Core +#define configNUMBER_OF_CORES 1 +#define configTICK_CORE 0 +#define configRUN_MULTIPLE_PRIORITIES 0 +#define configUSE_CORE_AFFINITY 0 +#define configNUM_CORES configNUMBER_OF_CORES //SDK still relies on this + + +/* RP2040 specific */ +#define configSUPPORT_PICO_SYNC_INTEROP 1 +#define configSUPPORT_PICO_TIME_INTEROP 1 + +#include +/* Define to trap errors during development. */ +#define configASSERT(x) assert(x) + +/* Set the following definitions to 1 to include the API function, or zero +to exclude the API function. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_xTaskGetSchedulerState 1 +#define INCLUDE_xTaskGetCurrentTaskHandle 1 +#define INCLUDE_uxTaskGetStackHighWaterMark 1 +#define INCLUDE_xTaskGetIdleTaskHandle 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_xTaskAbortDelay 1 +#define INCLUDE_xTaskGetHandle 1 +#define INCLUDE_xTaskResumeFromISR 1 +#define INCLUDE_xQueueGetMutexHolder 1 + +/* A header file that defines trace macro can be included here. */ + + +#ifdef __cplusplus +extern "C" +{ +#endif + +void *pvPortCalloc( size_t nmemb, size_t size ); +void *pvPortRealloc( void *pv, size_t size ); + +#ifdef __cplusplus +} // extern "C" +#endif + + +#if PICO_RP2350 +#define configENABLE_MPU 0 +#define configENABLE_TRUSTZONE 0 +#define configRUN_FREERTOS_SECURE_ONLY 1 +#define configENABLE_FPU 1 +#define configMAX_SYSCALL_INTERRUPT_PRIORITY 16 +#define configCPU_CLOCK_HZ 150000000 +#endif + + +#endif /* FREERTOS_CONFIG_H */ + diff --git a/port/FreeRTOS-Kernel/IdleMemory.c b/port/FreeRTOS-Kernel/IdleMemory.c new file mode 100644 index 0000000..c7cf5b2 --- /dev/null +++ b/port/FreeRTOS-Kernel/IdleMemory.c @@ -0,0 +1,77 @@ +#include "FreeRTOS.h" +#include +#include +/* configSUPPORT_STATIC_ALLOCATION is set to 1, so the application must provide an +implementation of vApplicationGetIdleTaskMemory() to provide the memory that is +used by the Idle task. */ +void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, + StackType_t **ppxIdleTaskStackBuffer, + uint32_t *pulIdleTaskStackSize ) +{ +/* If the buffers to be provided to the Idle task are declared inside this +function then they must be declared static – otherwise they will be allocated on +the stack and so not exists after this function exits. */ +static StaticTask_t xIdleTaskTCB; +static StackType_t uxIdleTaskStack[ configMINIMAL_STACK_SIZE ]; + + /* Pass out a pointer to the StaticTask_t structure in which the Idle task’s + state will be stored. */ + *ppxIdleTaskTCBBuffer = &xIdleTaskTCB; + + /* Pass out the array that will be used as the Idle task’s stack. */ + *ppxIdleTaskStackBuffer = uxIdleTaskStack; + + /* Pass out the size of the array pointed to by *ppxIdleTaskStackBuffer. + Note that, as the array is necessarily of type StackType_t, + configMINIMAL_STACK_SIZE is specified in words, not bytes. */ + *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE; +} +/* configSUPPORT_STATIC_ALLOCATION and configUSE_TIMERS are both set to 1, so the +application must provide an implementation of vApplicationGetTimerTaskMemory() +to provide the memory that is used by the Timer service task. */ +void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer, + StackType_t **ppxTimerTaskStackBuffer, + uint32_t *pulTimerTaskStackSize ) +{ +/* If the buffers to be provided to the Timer task are declared inside this +function then they must be declared static – otherwise they will be allocated on +the stack and so not exists after this function exits. */ +static StaticTask_t xTimerTaskTCB; +static StackType_t uxTimerTaskStack[ configTIMER_TASK_STACK_DEPTH ]; + + /* Pass out a pointer to the StaticTask_t structure in which the Timer + task’s state will be stored. */ + *ppxTimerTaskTCBBuffer = &xTimerTaskTCB; + + /* Pass out the array that will be used as the Timer task’s stack. */ + *ppxTimerTaskStackBuffer = uxTimerTaskStack; + + /* Pass out the size of the array pointed to by *ppxTimerTaskStackBuffer. + Note that, as the array is necessarily of type StackType_t, + configTIMER_TASK_STACK_DEPTH is specified in words, not bytes. */ + *pulTimerTaskStackSize = configTIMER_TASK_STACK_DEPTH; +} + + +void vApplicationStackOverflowHook( TaskHandle_t xTask, + char *pcTaskName ){ + printf("----------------------------------------------\n"); + printf("STACK OVERFLOW on %s\n", pcTaskName); + printf("----------------------------------------------\n"); + taskDISABLE_INTERRUPTS(); + for( ;; ); +} + +void vAssertCalled( const char *pcFile, uint32_t ulLine ){ + printf("----------------------------------------------\n"); + printf("ASSERT FAILED %s line: %d\n", pcFile, ulLine); + printf("----------------------------------------------\n"); + taskDISABLE_INTERRUPTS(); + for( ;; ); +} + + +void *pvPortRealloc( void *pv, size_t size ){ + vPortFree ( pv ); + return pvPortMalloc( size ); +} diff --git a/port/FreeRTOS-Kernel/cppMemory.cpp b/port/FreeRTOS-Kernel/cppMemory.cpp new file mode 100644 index 0000000..da5f9a2 --- /dev/null +++ b/port/FreeRTOS-Kernel/cppMemory.cpp @@ -0,0 +1,28 @@ +/* + * cppMemory.cpp + * + * Created on: 30 Jun 2023 + * Author: jondurrant + */ + +#include "pico/stdlib.h" + +#include "FreeRTOS.h" + + +void * operator new( size_t size ){ + return pvPortMalloc( size ); +} + +void * operator new[]( size_t size ){ + return pvPortMalloc(size); +} + +void operator delete( void * ptr ){ + vPortFree ( ptr ); +} + +void operator delete[]( void * ptr ){ + vPortFree ( ptr ); +} + diff --git a/port/FreeRTOS-Kernel/freertos_config.cmake b/port/FreeRTOS-Kernel/freertos_config.cmake new file mode 100644 index 0000000..c12bfc3 --- /dev/null +++ b/port/FreeRTOS-Kernel/freertos_config.cmake @@ -0,0 +1,18 @@ +cmake_minimum_required(VERSION 3.15) + +add_library(freertos_config STATIC) + +target_sources(freertos_config PUBLIC + ${CMAKE_CURRENT_LIST_DIR}/IdleMemory.c + ${CMAKE_CURRENT_LIST_DIR}/cppMemory.cpp + ) +target_include_directories(freertos_config PUBLIC + ${CMAKE_CURRENT_LIST_DIR} + ) # The config file directory\n" +target_compile_definitions(freertos_config + PUBLIC projCOVERAGE_TEST=0 + ) +target_link_libraries(freertos_config + FreeRTOS-Kernel + pico_stdlib + ) diff --git a/port/FreeRTOS-Kernel/freertos_unit.cmake b/port/FreeRTOS-Kernel/freertos_unit.cmake new file mode 100644 index 0000000..89d17df --- /dev/null +++ b/port/FreeRTOS-Kernel/freertos_unit.cmake @@ -0,0 +1,18 @@ +cmake_minimum_required(VERSION 3.15) + +add_library(freertos_unit STATIC) + +target_sources(freertos_unit PUBLIC + ${CMAKE_CURRENT_LIST_DIR}/idleMemory.c + ) +target_include_directories(freertos_unit PUBLIC + ${CMAKE_CURRENT_LIST_DIR} + ) +target_compile_definitions(freertos_unit PUBLIC + projCOVERAGE_TEST=0 + PICO_CXX_DISABLE_ALLOCATION_OVERRIDES + ) +target_link_libraries(freertos_unit + FreeRTOS-Kernel + pico_stdlib + ) \ No newline at end of file diff --git a/port/FreeRTOS-Kernel/logging_levels.h b/port/FreeRTOS-Kernel/logging_levels.h new file mode 100644 index 0000000..6dad21a --- /dev/null +++ b/port/FreeRTOS-Kernel/logging_levels.h @@ -0,0 +1,105 @@ +/* + * coreMQTT Agent v1.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file logging_levels.h + * @brief Defines the logging level macros. + */ + +#ifndef LOGGING_LEVELS_H_ +#define LOGGING_LEVELS_H_ + +/** + * @brief No log messages. + * + * When @ref LIBRARY_LOG_LEVEL is #LOG_NONE, logging is disabled and no + * logging messages are printed. + */ +#define LOG_NONE 0 + +/** + * @brief Represents erroneous application state or event. + * + * These messages describe the situations when a library encounters an error from + * which it cannot recover. + * + * These messages are printed when @ref LIBRARY_LOG_LEVEL is defined as either + * of #LOG_ERROR, #LOG_WARN, #LOG_INFO or #LOG_DEBUG. + */ +#define LOG_ERROR 1 + +/** + * @brief Message about an abnormal event. + * + * These messages describe the situations when a library encounters + * abnormal event that may be indicative of an error. Libraries continue + * execution after logging a warning. + * + * These messages are printed when @ref LIBRARY_LOG_LEVEL is defined as either + * of #LOG_WARN, #LOG_INFO or #LOG_DEBUG. + */ +#define LOG_WARN 2 + +/** + * @brief A helpful, informational message. + * + * These messages describe normal execution of a library. They provide + * the progress of the program at a coarse-grained level. + * + * These messages are printed when @ref LIBRARY_LOG_LEVEL is defined as either + * of #LOG_INFO or #LOG_DEBUG. + */ +#define LOG_INFO 3 + +/** + * @brief Detailed and excessive debug information. + * + * Debug log messages are used to provide the + * progress of the program at a fine-grained level. These are mostly used + * for debugging and may contain excessive information such as internal + * variables, buffers, or other specific information. + * + * These messages are only printed when @ref LIBRARY_LOG_LEVEL is defined as + * #LOG_DEBUG. + */ +#define LOG_DEBUG 4 + +/* The macro definition for LIBRARY_LOG_LEVEL is for Doxygen + * documentation only. This macro is typically defined in only the + * _config.h file or the demo_config.h file. */ + +/** + * @brief The logging level verbosity configuration of log messages from library. + * + * The logging verbosity levels are one of #LOG_DEBUG, #LOG_INFO, #LOG_WARN, + * and #LOG_ERROR. + * - With level #LOG_NONE, logging will be disabled. + * - With level #LOG_DEBUG, all log messages will print. + * - With level #LOG_INFO, all log messages, except level #LOG_DEBUG, will print. + * - With level #LOG_WARN, only messages this level and #LOG_ERROR level will print. + * - With level #LOG_ERROR, only messages at this level will print. + */ +#ifdef DOXYGEN + #define LIBRARY_LOG_LEVEL LOG_ERROR +#endif + +#endif /* ifndef LOGGING_LEVELS_H_ */ diff --git a/port/FreeRTOS-Kernel/logging_stack.h b/port/FreeRTOS-Kernel/logging_stack.h new file mode 100644 index 0000000..21407e9 --- /dev/null +++ b/port/FreeRTOS-Kernel/logging_stack.h @@ -0,0 +1,180 @@ +/* + * coreMQTT Agent v1.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file logging_stack.h + * @brief Reference implementation of Logging stack as a header-only library. + */ + +#ifndef LOGGING_STACK_H_ +#define LOGGING_STACK_H_ + +/* Include header for logging level macros. */ +#include +#include +#include +#include "logging_levels.h" + +/* The macro definition for LIBRARY_LOG_NAME is for Doxygen + * documentation only. This macro is typically defined in only the + * _config.h file or the demo_config.h file. */ + +/** + * @brief The name of the library or demo to add as metadata in log messages + * from the library or demo. + * + * This metadata aids in identifying the module source of log messages. + * The metadata is logged in the format `[ ]` as a prefix to the + * log messages. + * Refer to #LOG_METADATA_FORMAT for the complete format of the metadata prefix in + * log messages. + */ +#ifdef DOXYGEN + #define LIBRARY_LOG_NAME "" +#endif + +/* Check if LIBRARY_LOG_NAME macro has been defined. */ +#if !defined( LIBRARY_LOG_NAME ) + #error "Please define LIBRARY_LOG_NAME for the library." +#endif + +/** + * @brief Macro to extract only the file name from file path to use for metadata in + * log messages. + */ +#define FILENAME ( strrchr( __FILE__, '/' ) ? strrchr( __FILE__, '/' ) + 1 : __FILE__ ) + +/* Metadata information to prepend to every log message. */ +#define LOG_METADATA_FORMAT "[%s] [%s:%d] " /**< @brief Format of metadata prefix in log messages as `[] [] [:]` */ +#define LOG_METADATA_ARGS LIBRARY_LOG_NAME, FILENAME, __LINE__ /**< @brief Arguments into the metadata logging prefix format. */ + +#if !defined( DISABLE_LOGGING ) + +/** + * @brief Common macro that maps all the logging interfaces, + * (#LogDebug, #LogInfo, #LogWarn, #LogError) to the platform-specific logging + * function. + * + * `printf` from the standard C library is the POSIX platform implementation used + * for logging functionality. + */ + #define SdkLog( string ) printf string +#else + #define SdkLog( string ) +#endif + +/** + * Disable definition of logging interface macros when generating doxygen output, + * to avoid conflict with documentation of macros at the end of the file. + * @cond DOXYGEN_IGNORE + */ +/* Check that LIBRARY_LOG_LEVEL is defined and has a valid value. */ +#if !defined( LIBRARY_LOG_LEVEL ) || \ + ( ( LIBRARY_LOG_LEVEL != LOG_NONE ) && \ + ( LIBRARY_LOG_LEVEL != LOG_ERROR ) && \ + ( LIBRARY_LOG_LEVEL != LOG_WARN ) && \ + ( LIBRARY_LOG_LEVEL != LOG_INFO ) && \ + ( LIBRARY_LOG_LEVEL != LOG_DEBUG ) \ + ) + #error "Please define LIBRARY_LOG_LEVEL as either LOG_NONE, LOG_ERROR, LOG_WARN, LOG_INFO, or LOG_DEBUG." +#else + #if LIBRARY_LOG_LEVEL == LOG_DEBUG + /* All log level messages will logged. */ + #define LogError( message ) SdkLog( ( "[ERROR] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogWarn( message ) SdkLog( ( "[WARN] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogInfo( message ) SdkLog( ( "[INFO] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogDebug( message ) SdkLog( ( "[DEBUG] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + + #elif LIBRARY_LOG_LEVEL == LOG_INFO + /* Only INFO, WARNING and ERROR messages will be logged. */ + #define LogError( message ) SdkLog( ( "[ERROR] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogWarn( message ) SdkLog( ( "[WARN] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogInfo( message ) SdkLog( ( "[INFO] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogDebug( message ) + + #elif LIBRARY_LOG_LEVEL == LOG_WARN + /* Only WARNING and ERROR messages will be logged.*/ + #define LogError( message ) SdkLog( ( "[ERROR] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogWarn( message ) SdkLog( ( "[WARN] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogInfo( message ) + #define LogDebug( message ) + + #elif LIBRARY_LOG_LEVEL == LOG_ERROR + /* Only ERROR messages will be logged. */ + #define LogError( message ) SdkLog( ( "[ERROR] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogWarn( message ) + #define LogInfo( message ) + #define LogDebug( message ) + + #else /* if LIBRARY_LOG_LEVEL == LOG_ERROR */ + + #define LogError( message ) + #define LogWarn( message ) + #define LogInfo( message ) + #define LogDebug( message ) + + #endif /* if LIBRARY_LOG_LEVEL == LOG_ERROR */ +#endif /* if !defined( LIBRARY_LOG_LEVEL ) || ( ( LIBRARY_LOG_LEVEL != LOG_NONE ) && ( LIBRARY_LOG_LEVEL != LOG_ERROR ) && ( LIBRARY_LOG_LEVEL != LOG_WARN ) && ( LIBRARY_LOG_LEVEL != LOG_INFO ) && ( LIBRARY_LOG_LEVEL != LOG_DEBUG ) ) */ +/** @endcond */ + +/* Doxygen documentation of logging interface macro definitions for Doxygen. */ +#ifdef DOXYGEN + +/** + * @brief Definition of logging interface macro that logs messages at the "Debug" + * level, when debug level logging is enabled. + * + * This macro is only enabled for #LOG_DEBUG level configuration in this + * logging stack implementation. + */ + #define LogDebug( message ) SdkLog( ( "[DEBUG] "LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + +/** + * @brief Definition of logging interface macro that logs messages at the "Info" + * level, when info level logging is enabled. + * + * This macro is only enabled for #LOG_DEBUG and #LOG_INFO level configurations + * in this logging stack implementation. + */ + #define LogInfo( message ) SdkLog( ( "[INFO] "LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + +/** + * @brief Definition of logging interface macro that logs messages at the "Warning" + * level, when warning level logging is enabled. + * + * This macro is only enabled for #LOG_DEBUG, #LOG_INFO and #LOG_WARN level + * configurations in this logging stack implementation. + */ + #define LogWarn( message ) SdkLog( ( "[WARN] "LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + +/** + * @brief Definition of logging interface macro that logs messages at the "Error" + * level, when error level logging is enabled. + * + * This macro is only enabled for all logging level configurations + * unless except the #LOG_NONE configuration. + */ + #define LogError( message ) SdkLog( ( "[ERROR] "LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + +#endif /* ifndef DOXYGEN */ + +#endif /* ifndef LOGGING_STACK_H_ */ diff --git a/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/FreeRTOSConfig.h b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/FreeRTOSConfig.h new file mode 100644 index 0000000..100e87f --- /dev/null +++ b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/FreeRTOSConfig.h @@ -0,0 +1,167 @@ +/* + * FreeRTOS V202111.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html + *----------------------------------------------------------*/ + +/* Scheduler Related */ +#define configUSE_PREEMPTION 1 +#define configUSE_TICKLESS_IDLE 1 //DeepSleep? +#define configUSE_IDLE_HOOK 0 +#define configUSE_TICK_HOOK 0 +#define configTICK_RATE_HZ ( ( TickType_t ) 1000 ) +#define configMAX_PRIORITIES 32 +#define configMINIMAL_STACK_SIZE ( configSTACK_DEPTH_TYPE ) 256 +#define configUSE_16_BIT_TICKS 0 + +#define configIDLE_SHOULD_YIELD 1 + +/* Synchronization Related */ +#define configUSE_MUTEXES 1 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configUSE_QUEUE_SETS 1 +#define configUSE_TIME_SLICING 1 +#define configUSE_NEWLIB_REENTRANT 0 +// todo need this for lwip FreeRTOS sys_arch to compile +#define configENABLE_BACKWARD_COMPATIBILITY 1 +#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 5 + +/* System */ +#define configSTACK_DEPTH_TYPE uint32_t +#define configMESSAGE_BUFFER_LENGTH_TYPE size_t + +/* Memory allocation related definitions. */ +#define configSUPPORT_STATIC_ALLOCATION 1 +#define configSUPPORT_DYNAMIC_ALLOCATION 1 +#define configTOTAL_HEAP_SIZE (128*1024) +#define configAPPLICATION_ALLOCATED_HEAP 0 + +/* Hook function related definitions. */ +#define configCHECK_FOR_STACK_OVERFLOW 1 +#define configUSE_MALLOC_FAILED_HOOK 0 +#define configUSE_DAEMON_TASK_STARTUP_HOOK 0 + +/* Run time and task stats gathering related definitions. */ +#define configGENERATE_RUN_TIME_STATS 0 +#define configUSE_TRACE_FACILITY 1 +#define configUSE_STATS_FORMATTING_FUNCTIONS 0 + +/* Co-routine related definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES 1 + +/* Software timer related definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) +#define configTIMER_QUEUE_LENGTH 10 +#define configTIMER_TASK_STACK_DEPTH 1024 + +/* Interrupt nesting behaviour configuration. */ +/* +#define configKERNEL_INTERRUPT_PRIORITY [dependent of processor] +#define configMAX_SYSCALL_INTERRUPT_PRIORITY [dependent on processor and application] +#define configMAX_API_CALL_INTERRUPT_PRIORITY [dependent on processor and application] +*/ + +// Single Core +#define configNUMBER_OF_CORES 1 +#define configTICK_CORE 0 +#define configRUN_MULTIPLE_PRIORITIES 0 +#define configUSE_CORE_AFFINITY 0 +#define configNUM_CORES configNUMBER_OF_CORES //SDK still relies on this + + +/* RP2040 specific */ +#define configSUPPORT_PICO_SYNC_INTEROP 1 +#define configSUPPORT_PICO_TIME_INTEROP 1 + +#include +/* Define to trap errors during development. */ +#define configASSERT(x) assert(x) + +/* Set the following definitions to 1 to include the API function, or zero +to exclude the API function. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_xTaskGetSchedulerState 1 +#define INCLUDE_xTaskGetCurrentTaskHandle 1 +#define INCLUDE_uxTaskGetStackHighWaterMark 1 +#define INCLUDE_xTaskGetIdleTaskHandle 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_xTaskAbortDelay 1 +#define INCLUDE_xTaskGetHandle 1 +#define INCLUDE_xTaskResumeFromISR 1 +#define INCLUDE_xQueueGetMutexHolder 1 + +/* A header file that defines trace macro can be included here. */ + + +#ifdef __cplusplus +extern "C" +{ +#endif + +void *pvPortCalloc( size_t nmemb, size_t size ); +void *pvPortRealloc( void *pv, size_t size ); + +#ifdef __cplusplus +} // extern "C" +#endif + + +#if PICO_RP2350 +#define configENABLE_MPU 0 +#define configENABLE_TRUSTZONE 0 +#define configRUN_FREERTOS_SECURE_ONLY 1 +#define configENABLE_FPU 1 +#define configMAX_SYSCALL_INTERRUPT_PRIORITY 16 +#define configCPU_CLOCK_HZ 150000000 +#endif + + +#endif /* FREERTOS_CONFIG_H */ + diff --git a/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/IdleMemory.c b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/IdleMemory.c new file mode 100644 index 0000000..c7cf5b2 --- /dev/null +++ b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/IdleMemory.c @@ -0,0 +1,77 @@ +#include "FreeRTOS.h" +#include +#include +/* configSUPPORT_STATIC_ALLOCATION is set to 1, so the application must provide an +implementation of vApplicationGetIdleTaskMemory() to provide the memory that is +used by the Idle task. */ +void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, + StackType_t **ppxIdleTaskStackBuffer, + uint32_t *pulIdleTaskStackSize ) +{ +/* If the buffers to be provided to the Idle task are declared inside this +function then they must be declared static – otherwise they will be allocated on +the stack and so not exists after this function exits. */ +static StaticTask_t xIdleTaskTCB; +static StackType_t uxIdleTaskStack[ configMINIMAL_STACK_SIZE ]; + + /* Pass out a pointer to the StaticTask_t structure in which the Idle task’s + state will be stored. */ + *ppxIdleTaskTCBBuffer = &xIdleTaskTCB; + + /* Pass out the array that will be used as the Idle task’s stack. */ + *ppxIdleTaskStackBuffer = uxIdleTaskStack; + + /* Pass out the size of the array pointed to by *ppxIdleTaskStackBuffer. + Note that, as the array is necessarily of type StackType_t, + configMINIMAL_STACK_SIZE is specified in words, not bytes. */ + *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE; +} +/* configSUPPORT_STATIC_ALLOCATION and configUSE_TIMERS are both set to 1, so the +application must provide an implementation of vApplicationGetTimerTaskMemory() +to provide the memory that is used by the Timer service task. */ +void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer, + StackType_t **ppxTimerTaskStackBuffer, + uint32_t *pulTimerTaskStackSize ) +{ +/* If the buffers to be provided to the Timer task are declared inside this +function then they must be declared static – otherwise they will be allocated on +the stack and so not exists after this function exits. */ +static StaticTask_t xTimerTaskTCB; +static StackType_t uxTimerTaskStack[ configTIMER_TASK_STACK_DEPTH ]; + + /* Pass out a pointer to the StaticTask_t structure in which the Timer + task’s state will be stored. */ + *ppxTimerTaskTCBBuffer = &xTimerTaskTCB; + + /* Pass out the array that will be used as the Timer task’s stack. */ + *ppxTimerTaskStackBuffer = uxTimerTaskStack; + + /* Pass out the size of the array pointed to by *ppxTimerTaskStackBuffer. + Note that, as the array is necessarily of type StackType_t, + configTIMER_TASK_STACK_DEPTH is specified in words, not bytes. */ + *pulTimerTaskStackSize = configTIMER_TASK_STACK_DEPTH; +} + + +void vApplicationStackOverflowHook( TaskHandle_t xTask, + char *pcTaskName ){ + printf("----------------------------------------------\n"); + printf("STACK OVERFLOW on %s\n", pcTaskName); + printf("----------------------------------------------\n"); + taskDISABLE_INTERRUPTS(); + for( ;; ); +} + +void vAssertCalled( const char *pcFile, uint32_t ulLine ){ + printf("----------------------------------------------\n"); + printf("ASSERT FAILED %s line: %d\n", pcFile, ulLine); + printf("----------------------------------------------\n"); + taskDISABLE_INTERRUPTS(); + for( ;; ); +} + + +void *pvPortRealloc( void *pv, size_t size ){ + vPortFree ( pv ); + return pvPortMalloc( size ); +} diff --git a/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/cppMemory.cpp b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/cppMemory.cpp new file mode 100644 index 0000000..da5f9a2 --- /dev/null +++ b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/cppMemory.cpp @@ -0,0 +1,28 @@ +/* + * cppMemory.cpp + * + * Created on: 30 Jun 2023 + * Author: jondurrant + */ + +#include "pico/stdlib.h" + +#include "FreeRTOS.h" + + +void * operator new( size_t size ){ + return pvPortMalloc( size ); +} + +void * operator new[]( size_t size ){ + return pvPortMalloc(size); +} + +void operator delete( void * ptr ){ + vPortFree ( ptr ); +} + +void operator delete[]( void * ptr ){ + vPortFree ( ptr ); +} + diff --git a/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/freertos_config.cmake b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/freertos_config.cmake new file mode 100644 index 0000000..c12bfc3 --- /dev/null +++ b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/freertos_config.cmake @@ -0,0 +1,18 @@ +cmake_minimum_required(VERSION 3.15) + +add_library(freertos_config STATIC) + +target_sources(freertos_config PUBLIC + ${CMAKE_CURRENT_LIST_DIR}/IdleMemory.c + ${CMAKE_CURRENT_LIST_DIR}/cppMemory.cpp + ) +target_include_directories(freertos_config PUBLIC + ${CMAKE_CURRENT_LIST_DIR} + ) # The config file directory\n" +target_compile_definitions(freertos_config + PUBLIC projCOVERAGE_TEST=0 + ) +target_link_libraries(freertos_config + FreeRTOS-Kernel + pico_stdlib + ) diff --git a/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/freertos_unit.cmake b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/freertos_unit.cmake new file mode 100644 index 0000000..89d17df --- /dev/null +++ b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/freertos_unit.cmake @@ -0,0 +1,18 @@ +cmake_minimum_required(VERSION 3.15) + +add_library(freertos_unit STATIC) + +target_sources(freertos_unit PUBLIC + ${CMAKE_CURRENT_LIST_DIR}/idleMemory.c + ) +target_include_directories(freertos_unit PUBLIC + ${CMAKE_CURRENT_LIST_DIR} + ) +target_compile_definitions(freertos_unit PUBLIC + projCOVERAGE_TEST=0 + PICO_CXX_DISABLE_ALLOCATION_OVERRIDES + ) +target_link_libraries(freertos_unit + FreeRTOS-Kernel + pico_stdlib + ) \ No newline at end of file diff --git a/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/logging_levels.h b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/logging_levels.h new file mode 100644 index 0000000..6dad21a --- /dev/null +++ b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/logging_levels.h @@ -0,0 +1,105 @@ +/* + * coreMQTT Agent v1.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file logging_levels.h + * @brief Defines the logging level macros. + */ + +#ifndef LOGGING_LEVELS_H_ +#define LOGGING_LEVELS_H_ + +/** + * @brief No log messages. + * + * When @ref LIBRARY_LOG_LEVEL is #LOG_NONE, logging is disabled and no + * logging messages are printed. + */ +#define LOG_NONE 0 + +/** + * @brief Represents erroneous application state or event. + * + * These messages describe the situations when a library encounters an error from + * which it cannot recover. + * + * These messages are printed when @ref LIBRARY_LOG_LEVEL is defined as either + * of #LOG_ERROR, #LOG_WARN, #LOG_INFO or #LOG_DEBUG. + */ +#define LOG_ERROR 1 + +/** + * @brief Message about an abnormal event. + * + * These messages describe the situations when a library encounters + * abnormal event that may be indicative of an error. Libraries continue + * execution after logging a warning. + * + * These messages are printed when @ref LIBRARY_LOG_LEVEL is defined as either + * of #LOG_WARN, #LOG_INFO or #LOG_DEBUG. + */ +#define LOG_WARN 2 + +/** + * @brief A helpful, informational message. + * + * These messages describe normal execution of a library. They provide + * the progress of the program at a coarse-grained level. + * + * These messages are printed when @ref LIBRARY_LOG_LEVEL is defined as either + * of #LOG_INFO or #LOG_DEBUG. + */ +#define LOG_INFO 3 + +/** + * @brief Detailed and excessive debug information. + * + * Debug log messages are used to provide the + * progress of the program at a fine-grained level. These are mostly used + * for debugging and may contain excessive information such as internal + * variables, buffers, or other specific information. + * + * These messages are only printed when @ref LIBRARY_LOG_LEVEL is defined as + * #LOG_DEBUG. + */ +#define LOG_DEBUG 4 + +/* The macro definition for LIBRARY_LOG_LEVEL is for Doxygen + * documentation only. This macro is typically defined in only the + * _config.h file or the demo_config.h file. */ + +/** + * @brief The logging level verbosity configuration of log messages from library. + * + * The logging verbosity levels are one of #LOG_DEBUG, #LOG_INFO, #LOG_WARN, + * and #LOG_ERROR. + * - With level #LOG_NONE, logging will be disabled. + * - With level #LOG_DEBUG, all log messages will print. + * - With level #LOG_INFO, all log messages, except level #LOG_DEBUG, will print. + * - With level #LOG_WARN, only messages this level and #LOG_ERROR level will print. + * - With level #LOG_ERROR, only messages at this level will print. + */ +#ifdef DOXYGEN + #define LIBRARY_LOG_LEVEL LOG_ERROR +#endif + +#endif /* ifndef LOGGING_LEVELS_H_ */ diff --git a/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/logging_stack.h b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/logging_stack.h new file mode 100644 index 0000000..21407e9 --- /dev/null +++ b/port/FreeRTOS-Kernel/port/FreeRTOS-Kernel/logging_stack.h @@ -0,0 +1,180 @@ +/* + * coreMQTT Agent v1.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file logging_stack.h + * @brief Reference implementation of Logging stack as a header-only library. + */ + +#ifndef LOGGING_STACK_H_ +#define LOGGING_STACK_H_ + +/* Include header for logging level macros. */ +#include +#include +#include +#include "logging_levels.h" + +/* The macro definition for LIBRARY_LOG_NAME is for Doxygen + * documentation only. This macro is typically defined in only the + * _config.h file or the demo_config.h file. */ + +/** + * @brief The name of the library or demo to add as metadata in log messages + * from the library or demo. + * + * This metadata aids in identifying the module source of log messages. + * The metadata is logged in the format `[ ]` as a prefix to the + * log messages. + * Refer to #LOG_METADATA_FORMAT for the complete format of the metadata prefix in + * log messages. + */ +#ifdef DOXYGEN + #define LIBRARY_LOG_NAME "" +#endif + +/* Check if LIBRARY_LOG_NAME macro has been defined. */ +#if !defined( LIBRARY_LOG_NAME ) + #error "Please define LIBRARY_LOG_NAME for the library." +#endif + +/** + * @brief Macro to extract only the file name from file path to use for metadata in + * log messages. + */ +#define FILENAME ( strrchr( __FILE__, '/' ) ? strrchr( __FILE__, '/' ) + 1 : __FILE__ ) + +/* Metadata information to prepend to every log message. */ +#define LOG_METADATA_FORMAT "[%s] [%s:%d] " /**< @brief Format of metadata prefix in log messages as `[] [] [:]` */ +#define LOG_METADATA_ARGS LIBRARY_LOG_NAME, FILENAME, __LINE__ /**< @brief Arguments into the metadata logging prefix format. */ + +#if !defined( DISABLE_LOGGING ) + +/** + * @brief Common macro that maps all the logging interfaces, + * (#LogDebug, #LogInfo, #LogWarn, #LogError) to the platform-specific logging + * function. + * + * `printf` from the standard C library is the POSIX platform implementation used + * for logging functionality. + */ + #define SdkLog( string ) printf string +#else + #define SdkLog( string ) +#endif + +/** + * Disable definition of logging interface macros when generating doxygen output, + * to avoid conflict with documentation of macros at the end of the file. + * @cond DOXYGEN_IGNORE + */ +/* Check that LIBRARY_LOG_LEVEL is defined and has a valid value. */ +#if !defined( LIBRARY_LOG_LEVEL ) || \ + ( ( LIBRARY_LOG_LEVEL != LOG_NONE ) && \ + ( LIBRARY_LOG_LEVEL != LOG_ERROR ) && \ + ( LIBRARY_LOG_LEVEL != LOG_WARN ) && \ + ( LIBRARY_LOG_LEVEL != LOG_INFO ) && \ + ( LIBRARY_LOG_LEVEL != LOG_DEBUG ) \ + ) + #error "Please define LIBRARY_LOG_LEVEL as either LOG_NONE, LOG_ERROR, LOG_WARN, LOG_INFO, or LOG_DEBUG." +#else + #if LIBRARY_LOG_LEVEL == LOG_DEBUG + /* All log level messages will logged. */ + #define LogError( message ) SdkLog( ( "[ERROR] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogWarn( message ) SdkLog( ( "[WARN] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogInfo( message ) SdkLog( ( "[INFO] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogDebug( message ) SdkLog( ( "[DEBUG] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + + #elif LIBRARY_LOG_LEVEL == LOG_INFO + /* Only INFO, WARNING and ERROR messages will be logged. */ + #define LogError( message ) SdkLog( ( "[ERROR] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogWarn( message ) SdkLog( ( "[WARN] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogInfo( message ) SdkLog( ( "[INFO] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogDebug( message ) + + #elif LIBRARY_LOG_LEVEL == LOG_WARN + /* Only WARNING and ERROR messages will be logged.*/ + #define LogError( message ) SdkLog( ( "[ERROR] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogWarn( message ) SdkLog( ( "[WARN] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogInfo( message ) + #define LogDebug( message ) + + #elif LIBRARY_LOG_LEVEL == LOG_ERROR + /* Only ERROR messages will be logged. */ + #define LogError( message ) SdkLog( ( "[ERROR] " LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + #define LogWarn( message ) + #define LogInfo( message ) + #define LogDebug( message ) + + #else /* if LIBRARY_LOG_LEVEL == LOG_ERROR */ + + #define LogError( message ) + #define LogWarn( message ) + #define LogInfo( message ) + #define LogDebug( message ) + + #endif /* if LIBRARY_LOG_LEVEL == LOG_ERROR */ +#endif /* if !defined( LIBRARY_LOG_LEVEL ) || ( ( LIBRARY_LOG_LEVEL != LOG_NONE ) && ( LIBRARY_LOG_LEVEL != LOG_ERROR ) && ( LIBRARY_LOG_LEVEL != LOG_WARN ) && ( LIBRARY_LOG_LEVEL != LOG_INFO ) && ( LIBRARY_LOG_LEVEL != LOG_DEBUG ) ) */ +/** @endcond */ + +/* Doxygen documentation of logging interface macro definitions for Doxygen. */ +#ifdef DOXYGEN + +/** + * @brief Definition of logging interface macro that logs messages at the "Debug" + * level, when debug level logging is enabled. + * + * This macro is only enabled for #LOG_DEBUG level configuration in this + * logging stack implementation. + */ + #define LogDebug( message ) SdkLog( ( "[DEBUG] "LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + +/** + * @brief Definition of logging interface macro that logs messages at the "Info" + * level, when info level logging is enabled. + * + * This macro is only enabled for #LOG_DEBUG and #LOG_INFO level configurations + * in this logging stack implementation. + */ + #define LogInfo( message ) SdkLog( ( "[INFO] "LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + +/** + * @brief Definition of logging interface macro that logs messages at the "Warning" + * level, when warning level logging is enabled. + * + * This macro is only enabled for #LOG_DEBUG, #LOG_INFO and #LOG_WARN level + * configurations in this logging stack implementation. + */ + #define LogWarn( message ) SdkLog( ( "[WARN] "LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + +/** + * @brief Definition of logging interface macro that logs messages at the "Error" + * level, when error level logging is enabled. + * + * This macro is only enabled for all logging level configurations + * unless except the #LOG_NONE configuration. + */ + #define LogError( message ) SdkLog( ( "[ERROR] "LOG_METADATA_FORMAT, LOG_METADATA_ARGS ) ); SdkLog( message ); SdkLog( ( "\r\n" ) ) + +#endif /* ifndef DOXYGEN */ + +#endif /* ifndef LOGGING_STACK_H_ */ diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..0853699 --- /dev/null +++ b/readme.md @@ -0,0 +1,10 @@ +Создать новый проект + +mkdir freertos_sources + +cd freertos_sources +git clone https://github.com/raspberrypi/FreeRTOS-Kernel +git clone https://github.com/jondurrant/RPIPico2-Exp + +cp -r RPIPico2-Exp/examples/FreeRTOSBlink/port ../ +cp RPIPico2-Exp/examples/FreeRTOSBlink/FreeRTOS_Kernel_import.cmake ../FreeRTOS_Kernel_import.cmake \ No newline at end of file diff --git a/readme_en.md b/readme_en.md new file mode 100644 index 0000000..792a048 --- /dev/null +++ b/readme_en.md @@ -0,0 +1,61 @@ +# RTOS Sample Project for Raspberry Pi Pico 2 (Multicore) + +This project demonstrates a hybrid implementation of FreeRTOS and Bare-metal execution on the Raspberry Pi Pico 2 (RP2350), utilizing both processor cores. + +## Project Description +The project showcases how to run a Real-Time Operating System (FreeRTOS) on one core while maintaining a high-precision hardware-timer-driven process on the second core. + +### Core 0: FreeRTOS +Core 0 runs the FreeRTOS scheduler and manages multiple concurrent tasks: +1. **LED Blink Task**: Uses a custom C++ class `Pico2LED` to toggle the built-in LED every 200ms. +2. **USB Print Task**: Prints the system status to the USB serial console every 1 second, including counters from both cores. + +### Core 1: Bare-metal (Hardware Timers) +Core 1 operates in a bare-metal mode to ensure maximum predictability and precision: +- It creates a dedicated **Hardware Alarm Pool**. +- It runs a **Repeating Timer** that increments a global counter every 1000ms via a hardware interrupt. +- The core remains in a low-power state (`__wfi`) until the next interrupt occurs. + +## Algorithm Description +The project implements a multi-core synchronization and execution flow: + +1. **Initialization (Core 0)**: + - Initialize standard I/O. + - Launch Core 1 using `multicore_launch_core1()`. +2. **Bare-metal Execution (Core 1)**: + - Initialize a hardware alarm pool specifically for Core 1. + - Schedule a repeating timer interrupt. + - Enter a loop of "Wait For Interrupt" (`__wfi`). +3. **RTOS Execution (Core 0)**: + - Create FreeRTOS tasks for LED control and USB logging. + - Start the scheduler via `vTaskStartScheduler()`. +4. **Inter-core Communication**: + - Core 0 reads the `core1_counter` variable (marked as `volatile` to prevent compiler optimization) to display the hardware timer\'s progress. + +## Installation and Setup + +### 1. Prerequisites +Ensure you have the Raspberry Pi Pico SDK installed and configured. + +### 2. FreeRTOS Sources Setup +```bash +mkdir freertos_sources +cd freertos_sources +git clone https://github.com/raspberrypi/FreeRTOS-Kernel +git clone https://github.com/jondurrant/RPIPico2-Exp +cp -r RPIPico2-Exp/examples/FreeRTOSBlink/port ../port/FreeRTOS-Kernel +cp RPIPico2-Exp/examples/FreeRTOSBlink/FreeRTOS_Kernel_import.cmake ../FreeRTOS_Kernel_import.cmake +``` +### 3. Build Process + +1. `mkdir build && cd build` +2. `cmake ..` +3. `make` +4. Flash the `.uf2` file to the Pico 2. + +## Project Structure + +- `rtos_sample.cpp`: Main application code (Multi-core logic). +- `CMakeLists.txt`: Build configuration. +- `port/`: FreeRTOS configuration and port files. +- `freertos_sources/`: FreeRTOS kernel and support libraries. diff --git a/readme_ru.md b/readme_ru.md new file mode 100644 index 0000000..87536b2 --- /dev/null +++ b/readme_ru.md @@ -0,0 +1,62 @@ +# Пример проекта RTOS для Raspberry Pi Pico 2 (Многоядерность) + +Этот проект демонстрирует гибридную реализацию FreeRTOS и Bare-metal выполнения на Raspberry Pi Pico 2 (RP2350), используя оба ядра процессора. + +## Описание проекта +Проект показывает, как запустить операционную систему реального времени (FreeRTOS) на одном ядре, сохраняя при этом высокоточный процесс на базе аппаратных таймеров на втором ядре. + +### Ядро 0: FreeRTOS +Ядро 0 запускает планировщик FreeRTOS и управляет несколькими параллельными задачами: +1. **Задача мигания светодиодом (LED Blink Task)**: Использует пользовательский C++ класс `Pico2LED` для переключения встроенного светодиода каждые 200 мс. +2. **Задача вывода в USB (USB Print Task)**: Выводит статус системы в USB-консоль каждую секунду, включая счетчики с обоих ядер. + +### Ядро 1: Bare-metal (Аппаратные таймеры) +Ядро 1 работает в режиме bare-metal для обеспечения максимальной предсказуемости и точности: +- Создает выделенный **пул аппаратных прерываний (Alarm Pool)**. +- Запускает **циклический таймер**, который увеличивает глобальный счетчик каждые 1000 мс через аппаратное прерывание. +- Ядро находится в режиме низкого энергопотребления (`__wfi`) до наступления следующего прерывания. + +## Описание алгоритма +Проект реализует поток синхронизации и выполнения между ядрами: + +1. **Инициализация (Ядро 0)**: + - Инициализация стандартного ввода-вывода. + - Запуск Ядра 1 с помощью `multicore_launch_core1()`. +2. **Bare-metal выполнение (Ядро 1)**: + - Инициализация пула аппаратных прерываний специально для Ядра 1. + - Планирование циклического прерывания таймера. + - Вход в цикл ожидания прерывания (`__wfi`). +3. **Выполнение RTOS (Ядро 0)**: + - Создание задач FreeRTOS для управления LED и логирования в USB. + - Запуск планировщика через `vTaskStartScheduler()`. +4. **Межъядерное взаимодействие**: + - Ядро 0 считывает переменную `core1_counter` (помеченную как `volatile` для предотвращения оптимизации компилятором), чтобы отобразить прогресс аппаратного таймера. + +## Установка и настройка + +### 1. Предварительные требования +Убедитесь, что у вас установлен и настроен Raspberry Pi Pico SDK. + +### 2. Установка исходников FreeRTOS +```bash +mkdir freertos_sources +cd freertos_sources +git clone https://github.com/raspberrypi/FreeRTOS-Kernel +git clone https://github.com/jondurrant/RPIPico2-Exp +cp -r RPIPico2-Exp/examples/FreeRTOSBlink/port ../port/FreeRTOS-Kernel +cp RPIPico2-Exp/examples/FreeRTOSBlink/FreeRTOS_Kernel_import.cmake ../FreeRTOS_Kernel_import.cmake +``` + +### 3. Процесс сборки +1. `mkdir build && cd build` +2. `cmake ..` +3. `make` +4. Прошейте `.uf2` файл в ваш Raspberry Pi Pico 2. + +### Структура проекта + +* 📄 `rtos_sample.cpp` — Основной код приложения (Многоядерная логика) / Main application code (Multi-core logic). +* ⚙️ `CMakeLists.txt` — Конфигурация сборки проекта / Build configuration. +* 📁 `port/` — Файлы конфигурации и адаптации (порта) FreeRTOS / FreeRTOS configuration and port files. +* 📁 `freertos_sources/` — Ядро FreeRTOS и вспомогательные библиотеки / FreeRTOS kernel and support libraries. + diff --git a/rtos_sample.cpp b/rtos_sample.cpp new file mode 100644 index 0000000..3ea8337 --- /dev/null +++ b/rtos_sample.cpp @@ -0,0 +1,190 @@ +#include +#include "pico/stdlib.h" +#include "FreeRTOS.h" +#include "task.h" +#include "pico/multicore.h" // Required for interacting with the second core / Обязательно для работы со вторым ядром +#include "hardware/sync.h" // For safe data increment between cores / Для безопасного инкремента данных между ядрами + +/** + * @brief Global counter incremented by Core 1 via hardware timer. + * volatile ensures the compiler doesn't cache the value in registers. + * @brief Глобальный счетчик, который увеличивается Ядром 1 через аппаратный таймер. + * volatile гарантирует, что компилятор не будет кэшировать значение в регистрах. + */ +volatile uint32_t core1_counter = 0; + +/** + * @brief Pointer to an individual interrupt pool for Core 1 + * @brief Указатель на индивидуальный пул прерываний для Ядра 1 + */ +alarm_pool_t *core1_alarm_pool = nullptr; + +/** + * @brief Maximum number of simultaneous timers in Core 1 pool + * @brief Максимальное количество одновременных таймеров в пуле Ядра 1 + */ +const uint CORE1_MAX_TIMERS = 4; + +/** + * @brief Structure for storing Core 1 hardware timer information + * @brief Структура для хранения информации об аппаратном таймере Ядра 1 + */ +struct repeating_timer timer_core1; + +/** + * @brief Pin of the built-in LED on Raspberry Pi Pico 2 + * @brief Пин встроенного светодиода на Raspberry Pi Pico 2 + */ +const uint LED_PIN = 25; + +// ====================================================================================== +// User-defined class for LED control +// Пользовательский класс для управления светодиодом +// ====================================================================================== +class Pico2LED { +private: + uint m_pin; // GPIO pin number / Номер GPIO пина +public: + /** + * @brief Constructor initializes the GPIO pin + * @brief Конструктор инициализирует GPIO пин + * @param pin The GPIO pin to use / Используемый GPIO пин + */ + Pico2LED(uint pin) : m_pin(pin) { + gpio_init(m_pin); + gpio_set_dir(m_pin, GPIO_OUT); + } + + /** + * @brief Turns the LED on + * @brief Включает светодиод + */ + void turnOn() { + gpio_put(m_pin, 1); + } + + /** + * @brief Turns the LED off + * @brief Выключает светодиод + */ + void turnOff() { + gpio_put(m_pin, 0); + } +}; + +/** + * @brief Функция обратного вызова для аппаратного таймера Ядра 1 + * Вызывается автоматически каждые 1000 мс прерыванием таймера НА ЯДРЕ 1. + */ +bool core1_timer_callback(struct repeating_timer *t) { + // Безопасно увеличиваем счетчик в многоядерной среде + core1_counter++; + return true; // Возвращаем true, чтобы таймер продолжил циклически работать +} + +/** + * @brief Главная функция, выполняемая Ядром 1 + */ +void core1_entry() { + // 1. Создаем выделенный пул аппаратных прерываний (таймеров) специально для Ядра 1. + // Функция привязывает этот пул к аппаратному аппаратному контроллеру прерываний Core 1. + core1_alarm_pool = alarm_pool_create_with_unused_hardware_alarm(CORE1_MAX_TIMERS); + + if (core1_alarm_pool != nullptr) { + // 2. Добавляем циклический таймер именно в НАШ созданный пул Ядра 1. + // Теперь прерывание гарантированно будет обрабатываться только на Core 1. + alarm_pool_add_repeating_timer_ms( + core1_alarm_pool, // Наш кастомный пул + 1000, // Период (1000 мс) + core1_timer_callback,// Функция обратного вызова + NULL, // Пользовательские параметры + &timer_core1 // Структура таймера + ); + } else { + // Ошибка создания пула (например, если закончились аппаратные таймеры) + printf("Ошибка: Не удалось создать alarm pool на Ядре 1!\n"); + } + + // Вечный цикл (пул) Ядра 1 + while (true) { + __wfi(); // Спим до тех пор, пока не сработает прерывание таймера на Core 1 + } +} + +// ====================================================================================== +// STANDARD FREERTOS TASKS (Simple functions) +// ОБЫЧНЫЕ ЗАДАЧИ FREERTOS (Простые функции) +// ====================================================================================== + +/** + * @brief Task 1: Blinks the LED using the Pico2LED class locally + * @brief Задача 1: Мигает светодиодом, используя класс Pico2LED локально + * @param pvParameters Task parameters (unused) / Параметры задачи (не используются) + */ +void led_blink_task(void *pvParameters) { + // Create an object of the class directly inside the task + // Создаем объект класса прямо внутри задачи + Pico2LED my_led(25); // 25 - built-in LED on Pico 2 / 25 - встроенный LED на Pico 2 + + while (true) { + my_led.turnOn(); + vTaskDelay(pdMS_TO_TICKS(200)); // Delay for 200ms / Задержка 200мс + my_led.turnOff(); + vTaskDelay(pdMS_TO_TICKS(200)); // Delay for 200ms / Задержка 200мс + } +} + +/** + * @brief Task 2: Prints a counter to the USB console + * @brief Задача 2: Выводит счетчик в USB консоль + * @param pvParameters Task parameters (unused) / Параметры задачи (не используются) + */ +void usb_print_task(void *pvParameters) { + int core0_counter = 0; + while (true) { + // Выводим в консоль счетчик FreeRTOS (Core 0) и аппаратный счетчик из Core 1 + printf("Core 0 (FreeRTOS) tics: %d | Core 1 (Timer bare-metal) counter: %lu\n", + core0_counter++, core1_counter); + + vTaskDelay(pdMS_TO_TICKS(1000)); + } +} + +// ====================================================================================== +// MAIN FUNCTION +// Главная функция +// ====================================================================================== +int main() { + // Initialize all standard I/O (USB/UART) + // Инициализация всех стандартных средств ввода-вывода (USB/UART) + stdio_init_all(); + + // Launch Core 1 BEFORE starting the FreeRTOS scheduler. + // Pass the core1_entry function as the entry point. + // Запускаем Ядро 1 ДО старта планировщика FreeRTOS. + // Передаем ему функцию входа core1_entry. + multicore_launch_core1(core1_entry); + + /** + * Create standard tasks by passing function pointers + * Создаем обычные задачи, передавая указатели на функции + * + * xTaskCreate parameters: + * 1. Task function / Функция задачи + * 2. Task name / Имя задачи + * 3. Stack size / Размер стека + * 4. Parameters / Параметры + * 5. Priority / Приоритет + * 6. Task handle / Хэндл задачи + */ + xTaskCreate(led_blink_task, "LED_Task", 256, NULL, 1, NULL); + xTaskCreate(usb_print_task, "Print_Task", 256, NULL, 1, NULL); + + // Start the FreeRTOS scheduler + // Запуск планировщика FreeRTOS + vTaskStartScheduler(); + + // Should never reach here + // Сюда выполнение не должно дойти + while (true) {} +} diff --git a/testmaybeFreeRTOSConfig.h.txt b/testmaybeFreeRTOSConfig.h.txt new file mode 100644 index 0000000..9587749 --- /dev/null +++ b/testmaybeFreeRTOSConfig.h.txt @@ -0,0 +1,167 @@ +/* + * FreeRTOS V202111.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html + *----------------------------------------------------------*/ + +/* Scheduler Related */ +#define configUSE_PREEMPTION 1 +#define configUSE_TICKLESS_IDLE 1 //DeepSleep? +#define configUSE_IDLE_HOOK 0 +#define configUSE_TICK_HOOK 0 +#define configTICK_RATE_HZ ( ( TickType_t ) 1000 ) +#define configMAX_PRIORITIES 32 +#define configMINIMAL_STACK_SIZE ( configSTACK_DEPTH_TYPE ) 256 +#define configUSE_16_BIT_TICKS 0 + +#define configIDLE_SHOULD_YIELD 1 + +/* Synchronization Related */ +#define configUSE_MUTEXES 1 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configUSE_QUEUE_SETS 1 +#define configUSE_TIME_SLICING 1 +#define configUSE_NEWLIB_REENTRANT 0 +// todo need this for lwip FreeRTOS sys_arch to compile +#define configENABLE_BACKWARD_COMPATIBILITY 1 +#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 5 + +/* System */ +#define configSTACK_DEPTH_TYPE uint32_t +#define configMESSAGE_BUFFER_LENGTH_TYPE size_t + +/* Memory allocation related definitions. */ +#define configSUPPORT_STATIC_ALLOCATION 1 +#define configSUPPORT_DYNAMIC_ALLOCATION 1 +#define configTOTAL_HEAP_SIZE (128*1024) +#define configAPPLICATION_ALLOCATED_HEAP 0 + +/* Hook function related definitions. */ +#define configCHECK_FOR_STACK_OVERFLOW 1 +#define configUSE_MALLOC_FAILED_HOOK 0 +#define configUSE_DAEMON_TASK_STARTUP_HOOK 0 + +/* Run time and task stats gathering related definitions. */ +#define configGENERATE_RUN_TIME_STATS 0 +#define configUSE_TRACE_FACILITY 1 +#define configUSE_STATS_FORMATTING_FUNCTIONS 0 + +/* Co-routine related definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES 1 + +/* Software timer related definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) +#define configTIMER_QUEUE_LENGTH 10 +#define configTIMER_TASK_STACK_DEPTH 1024 + +/* Interrupt nesting behaviour configuration. */ +#define configKERNEL_INTERRUPT_PRIORITY 255 +#define configMAX_SYSCALL_INTERRUPT_PRIORITY 191 + +// === ЖЕСТКАЯ ПРИВЯЗКА К СORE 0 === +#define configNUMBER_OF_CORES 1 +#define configTICK_CORE 0 +#define configRUN_MULTIPLE_PRIORITIES 0 +#define configUSE_CORE_AFFINITY 0 +#define configNUM_CORES configNUMBER_OF_CORES // SDK все еще полагается на этот макрос + + +/* RP2040/RP2350 specific */ +#define configSUPPORT_PICO_SYNC_INTEROP 1 +#define configSUPPORT_PICO_TIME_INTEROP 1 + +#include +/* Define to trap errors during development. */ +#define configASSERT(x) assert(x) + +/* Set the following definitions to 1 to include the API function, or zero +to exclude the API function. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_xTaskGetSchedulerState 1 +#define INCLUDE_xTaskGetCurrentTaskHandle 1 +#define INCLUDE_uxTaskGetStackHighWaterMark 1 +#define INCLUDE_xTaskGetIdleTaskHandle 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_xTaskAbortDelay 1 +#define INCLUDE_xTaskGetHandle 1 +#define INCLUDE_xTaskResumeFromISR 1 +#define INCLUDE_xQueueGetMutexHolder 1 + +/* A header file that defines trace macro can be included here. */ + + +#ifdef __cplusplus +extern "C" +{ +#endif + +void *pvPortCalloc( size_t nmemb, size_t size ); +void *pvPortRealloc( void *pv, size_t size ); + +#ifdef __cplusplus +} // extern "C" +#endif + + +#if PICO_RP2350 +#define configENABLE_MPU 0 +#define configENABLE_TRUSTZONE 0 +#define configRUN_FREERTOS_SECURE_ONLY 1 +#define configENABLE_FPU 1 +#define configCPU_CLOCK_HZ 150000000 + +/* Перенаправление обработчиков низкоуровневых прерываний ядра для ARM Cortex-M33 */ +#define vPortSVCHandler isr_svcall +#define xPortPendSVHandler isr_pendsv +#define xPortSysTickHandler isr_systick +#endif + + +#endif /* FREERTOS_CONFIG_H */