first commit

This commit is contained in:
fewikay committed 2026-10-16 13:08:06 +02:00
commit 92cbe97616
1978 files changed
+1688498

No files matched your search

@@ -0,0 +1 @@
used for symbolic linking or referencing from within IDEs, VSCode project is based on Makefiles and therefore this folder is not needed. It is more for CubeIDE Project structure!
@@ -0,0 +1,384 @@
/*
* ipc_eth_consumer.c
*
* Created on: 11.08.2026
* Author: Thorsten
*/
//---------------------------------------------------------------------------------------------------------------------
#include "main.h"
#include "openamp.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "stdio.h"
#include "assert.h"
#include "message_buffer.h"
//---------------------------------------------------------------------------------------------------------------------
#include "IPC/ipc_eth_producer.h"
//---------------------------------------------------------------------------------------------------------------------
#define IPC_PKT_HEADERLEN (20 )
#define IPC_PKT_ETHERNET_TYPE (0xDEADC0DE )
#define IPC_PKT_DISCOVERY_TYPE (0xDEADDA7A )
#define IPC_CTRL_TYPE_GETPENDING (0x80 )
#define IPC_CTRL_TYPE_GETIPADDR (0xF0 )
#define IPC_CTRL_TYPE_GETSUBNET (0xF1 )
//---------------------------------------------------------------------------------------------------------------------
static ipc_eth_packet_t heartbeatPayload = {
//---------------------------------------------------------------------------------------------------------------------
.magic = IPC_PKT_DISCOVERY_TYPE,
.type = 0,
.length = 37,
.result = 0,
.seqID = 0,
.payload = "Hello from STM32H755ZI-Q on ARM CM7!"
};
//---------------------------------------------------------------------------------------------------------------------
struct IPC_ETH_PRODUCER_Context
//---------------------------------------------------------------------------------------------------------------------
{
struct rpmsg_endpoint rp_endpoint;
MessageBufferHandle_t mbufH;
TaskHandle_t taskH;
QueueHandle_t reqQH;
int running;
uint8_t tmp[(((IPC_PKT_MAXSIZE+sizeof(void*)-1)/sizeof(void*))*sizeof(void*))];
char payload[IPC_PKT_MAXSIZE+4*sizeof(void*)];
uint32_t ipaddr;
uint32_t bcast;
uint32_t subnet;
};
//---------------------------------------------------------------------------------------------------------------------
static ipc_eth_packet_t getIPAddress = {
//---------------------------------------------------------------------------------------------------------------------
.magic = IPC_PKT_CONTROL_TYPE,
.type = IPC_CTRL_TYPE_GETIPADDR,
.length = 0,
.result = 0,
.seqID = 0,
};
//---------------------------------------------------------------------------------------------------------------------
static ipc_eth_packet_t ethernetPkt = {
//---------------------------------------------------------------------------------------------------------------------
.magic = IPC_PKT_ETHERNET_TYPE,
.type = 0,
.length = 0,
.result = 0,
.seqID = 0,
};
//---------------------------------------------------------------------------------------------------------------------
static IPC_ETH_PRODUCER_Handle_t singleton_h;
//---------------------------------------------------------------------------------------------------------------------
static int ipc_eth_ProducerRpMsgRxCallback(struct rpmsg_endpoint *ept, void *data, size_t len, uint32_t src, void *priv)
//---------------------------------------------------------------------------------------------------------------------
{
(void)ept;
(void)src;
if(!priv)
return 0;
size_t alignedLen = (((len+sizeof(void*)-1)/sizeof(void*))*sizeof(void*));
IPC_ETH_PRODUCER_Handle_t h = (IPC_ETH_PRODUCER_Handle_t)priv;
if ( alignedLen >= sizeof(h->priv->tmp))
return 0;
// this is an additional copy step as it would be when just using the message buffer.
// its a worse idea at all but this helps overcoming an MPU region configuration, which
// requires us to handle addresses aligned when accessing the shared D3 SRAM. other way
// around would be to disable the MPU for the shared D3 region but i want to practice it
// in the correct way as non buffered, non cached and shared region config which requires
// us to handle it in aligned accesses at all. the message buffer has internal mechanism,
// where this handling is not guaranteed at buffer turn around conditions...
for( size_t i = 0; i < alignedLen/4; i++ ) {
((uint32_t*)h->priv->tmp)[i] = ((uint32_t*)(data))[i];
}
xMessageBufferSend(h->priv->mbufH, h->priv->tmp, len, 0);
return 0;
}
//---------------------------------------------------------------------------------------------------------------------
static void ipc_eth_ProducerRpMsgUnbindCallback(struct rpmsg_endpoint *ept)
//---------------------------------------------------------------------------------------------------------------------
{
if(ept->priv)
{
IPC_ETH_PRODUCER_Handle_t h = (IPC_ETH_PRODUCER_Handle_t)ept->priv;
h->priv->running = 0;
}
}
//---------------------------------------------------------------------------------------------------------------------
static void ipc_eth_ProducerRpMsgNewEndpoint(struct rpmsg_device *rdev, const char *name, uint32_t dest)
//---------------------------------------------------------------------------------------------------------------------
{
(void)rdev;
OPENAMP_create_endpoint(&singleton_h->priv->rp_endpoint, name, dest,
ipc_eth_ProducerRpMsgRxCallback, ipc_eth_ProducerRpMsgUnbindCallback);
}
//---------------------------------------------------------------------------------------------------------------------
static void ipc_eth_ProducerTaskFunction( void * arg )
//---------------------------------------------------------------------------------------------------------------------
{
if(!arg)
vTaskDelete(NULL);
IPC_ETH_PRODUCER_Handle_t h = (IPC_ETH_PRODUCER_Handle_t)arg;
size_t bLen = 0;
unsigned int currentPending = 0;
unsigned int rounds = 0;
unsigned int currentSeqID = 0;
__HAL_RCC_HSEM_CLK_ENABLE();
/*Take HSEM */
HAL_HSEM_FastTake(0U);
/*Release HSEM in order to notify the CPU2(CM4)*/
HAL_HSEM_Release(0U,0);
/* wait until CPU2 wakes up from stop mode */
while((__HAL_RCC_GET_FLAG(RCC_FLAG_D2CKRDY) == RESET)) {
vTaskDelay(pdMS_TO_TICKS(1));
};
if (!h)
goto error;
if (!h->priv)
goto error;
OPENAMP_Wait_EndPointready(&h->priv->rp_endpoint);
// give the network stack i bit of time before starting all the troubles
vTaskDelay(pdMS_TO_TICKS(6000));
while(h->priv->running) {
vTaskDelay(pdMS_TO_TICKS(1));
OPENAMP_check_for_message();
if ( (bLen = xMessageBufferReceive(h->priv->mbufH, h->priv->payload, sizeof(h->priv->payload), pdMS_TO_TICKS(0))) >= IPC_PKT_HEADERLEN) {
if (currentPending > 0 )
currentPending -= 1;
ipc_eth_packet_t *req = (ipc_eth_packet_t *)h->priv->payload;
if (req->length <= (bLen - IPC_PKT_HEADERLEN)) {
if (req->magic == IPC_PKT_CONTROL_TYPE && req->result == 0 && req->type == IPC_CTRL_TYPE_GETIPADDR) {
memcpy(&h->priv->ipaddr, req->payload, sizeof(h->priv->ipaddr));
}
else if (req->magic == IPC_PKT_CONTROL_TYPE && req->result != 0 && req->type == IPC_CTRL_TYPE_GETIPADDR) {
// in case IP address read was not valid, we will set Subnet and IP address back. this is used to indicate
// missing connection or non functional stack on remote processor
h->priv->subnet = 0;
h->priv->ipaddr = 0;
}
else if (req->magic == IPC_PKT_CONTROL_TYPE && req->result == 0 && req->type == IPC_CTRL_TYPE_GETSUBNET) {
memcpy(&h->priv->subnet, req->payload, sizeof(h->priv->subnet));
}
else if (req->magic == IPC_PKT_CONTROL_TYPE && req->result == 0 && req->type == IPC_CTRL_TYPE_GETPENDING &&
h->callbacks.rxCtrlCallback != NULL) {
int numRequests = req->length / (IPC_PKT_HEADERLEN + IPC_CTRLREMOTE_MAX_LENGTH);
int index = 0;
while(numRequests > 0) {
ipc_eth_packet_t *sreq = (ipc_eth_packet_t *)&req->payload[index * (IPC_PKT_HEADERLEN + IPC_CTRLREMOTE_MAX_LENGTH)];
if (sreq->magic == IPC_PKT_CONTROL_TYPE && sreq->result == 0 && sreq->type >= IPC_CTRLREMOTE_SPINDLE_START &&
sreq->type <= IPC_CTRLREMOTE_STEP_MOVE) {
h->callbacks.rxCtrlCallback(h, sreq, h->callbacks.rxCtrlPriv);
}
numRequests-=1;
index+=1;
}
}
}
}
OPENAMP_check_for_message();
//TODO: don't know why but when more messages are pending, everything is destroyed and
// ends up in hard faults caused by virtio structures and addresses
// outside the shared mem region
if(currentPending < 2) {
if (xQueueReceive(h->priv->reqQH, &ethernetPkt, 0) == pdPASS) {
ethernetPkt.type = 0;
ethernetPkt.magic = IPC_PKT_ETHERNET_TYPE;
if ( OPENAMP_send(&h->priv->rp_endpoint, &ethernetPkt, sizeof(ethernetPkt)) == 0 )
currentPending += 1;
currentSeqID += 1;
}
else if (rounds % 7 == 0) {
getIPAddress.type = IPC_CTRL_TYPE_GETPENDING;
getIPAddress.seqID = currentSeqID;
if( OPENAMP_send(&h->priv->rp_endpoint, &getIPAddress, sizeof(getIPAddress)) == 0 )
currentPending += 1;
currentSeqID += 1;
}
if (rounds % 1000 == 0) {
heartbeatPayload.seqID = currentSeqID;
if ( OPENAMP_send(&h->priv->rp_endpoint, &heartbeatPayload, sizeof(heartbeatPayload)) == 0 )
currentPending += 1;
currentSeqID += 1;
if ( h->callbacks.statusReqCallback != NULL ) {
h->callbacks.statusReqCallback(h, h->callbacks.statusReqPriv);
}
}
else if (rounds % 100 == 5) {
if ( h->callbacks.statusReqCallback != NULL ) {
h->callbacks.statusReqCallback(h, h->callbacks.statusReqPriv);
}
}
else if (rounds % 1000 == 1) {
getIPAddress.type = IPC_CTRL_TYPE_GETIPADDR;
getIPAddress.seqID = currentSeqID;
if ( OPENAMP_send(&h->priv->rp_endpoint, &getIPAddress, sizeof(getIPAddress)) == 0)
currentPending += 1;
currentSeqID += 1;
}
else if (rounds % 1000 == 2) {
getIPAddress.type = IPC_CTRL_TYPE_GETSUBNET;
getIPAddress.seqID = currentSeqID;
if ( OPENAMP_send(&h->priv->rp_endpoint, &getIPAddress, sizeof(getIPAddress)) == 0 )
currentPending += 1;
currentSeqID += 1;
}
rounds += 1;
}
OPENAMP_check_for_message();
}
error:
OPENAMP_DeInit();
vTaskDelete(NULL);
}
//---------------------------------------------------------------------------------------------------------------------
int IPC_ETH_PRODUCER_SendPaket(IPC_ETH_PRODUCER_Handle_t h, void* buff, int size)
//---------------------------------------------------------------------------------------------------------------------
{
if ( h == NULL || buff == NULL || size <= 0 )
return -1;
if ( h->priv == NULL || h->priv->reqQH == NULL )
return -1;
ipc_eth_packet_t pkt = {
.length = size,
.magic = IPC_PKT_ETHERNET_TYPE,
.seqID = 0,
.type = 0,
.result = 0,
};
if(size > sizeof(pkt.payload))
return -1;
memcpy(pkt.payload, buff, size);
return -(xQueueSend(h->priv->reqQH, &pkt, 0) == pdFALSE);
}
//---------------------------------------------------------------------------------------------------------------------
int IPC_ETH_PRODUCER_GetIPAddress(IPC_ETH_PRODUCER_Handle_t h, uint32_t *ipv4, uint32_t *subnet)
//---------------------------------------------------------------------------------------------------------------------
{
if (h == NULL)
return 0;
if (h->priv->ipaddr == 0)
return 0;
if(ipv4)
*ipv4 = h->priv->ipaddr;
if(subnet)
*subnet = h->priv->subnet;
return 1;
}
//---------------------------------------------------------------------------------------------------------------------
IPC_ETH_PRODUCER_Handle_t IPC_ETH_PRODUCER_Init(const char *endpoint)
//---------------------------------------------------------------------------------------------------------------------
{
IPC_ETH_PRODUCER_Handle_t h = NULL;
int OpenAmpInit = 0;
if(!endpoint)
goto error;
if(endpoint[0] == '\0')
goto error;
if (MAILBOX_Init())
goto error;
if(!(h = (IPC_ETH_PRODUCER_Handle_t)calloc(1, sizeof(struct IPC_ETH_PRODUCER_Handle))))
goto error;
h->priv = (IPC_ETH_PRODUCER_Context_t)calloc(1, sizeof(struct IPC_ETH_PRODUCER_Context));
if(!h->priv)
goto error;
rpmsg_init_ept(&h->priv->rp_endpoint, endpoint, RPMSG_ADDR_ANY, RPMSG_ADDR_ANY, NULL, NULL);
// set this instance as private data
h->priv->rp_endpoint.priv = h;
singleton_h = h;
if (MX_OPENAMP_Init(RPMSG_MASTER, ipc_eth_ProducerRpMsgNewEndpoint) != 0) {
goto error;
}
OpenAmpInit = 1;
if ((h->priv->mbufH = xMessageBufferCreate(4*IPC_PKT_MAXSIZE)) == NULL)
goto error;
if ((h->priv->reqQH = xQueueCreate(4, sizeof(ethernetPkt))) == NULL)
goto error;
h->priv->running = 1;
if (pdPASS != xTaskCreate(ipc_eth_ProducerTaskFunction, "user2ipc", 4096, h, configMAX_PRIORITIES - 2, &h->priv->taskH))
goto error;
return h;
error:
if (h) {
if(h->priv) {
if(h->priv->taskH) {
h->priv->running = 0;
vTaskDelete(h->priv->taskH);
}
if(h->priv->rp_endpoint.priv == h) {
// no abstraction for destroying, so calling library function directly
rpmsg_destroy_ept(&h->priv->rp_endpoint);
}
if(h->priv->mbufH) {
vMessageBufferDelete(h->priv->mbufH);
}
if(h->priv->reqQH) {
vQueueDelete(h->priv->reqQH);
}
free(h->priv);
}
free(h);
}
h = NULL;
if ( OpenAmpInit )
OPENAMP_DeInit();
return h;
}
@@ -0,0 +1 @@
used for symbolic linking or referencing from within IDEs, VSCode project is based on Makefiles and therefore this folder is not needed. It is more for CubeIDE Project structure!
@@ -0,0 +1,757 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "openamp.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "stdio.h"
#include "assert.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#ifndef HSEM_ID_0
#define HSEM_ID_0 (0U) /* HW semaphore 0*/
#endif
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
SPI_HandleTypeDef hspi1;
TIM_HandleTypeDef htim2;
UART_HandleTypeDef huart3;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MPU_Config(void);
static void MX_GPIO_Init(void);
static void MX_SPI1_Init(void);
static void MX_TIM2_Init(void);
static void MX_USART3_UART_Init(void);
/* USER CODE BEGIN PFP */
extern void initialise_stdlib_abstraction( void );
void vApplicationMallocFailedHook( void )
{
taskDISABLE_INTERRUPTS();
__asm volatile( "bkpt #0" );
for (;;) {;}
}
/*-----------------------------------------------------------*/
void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
{
( void ) pcTaskName;
( void ) pxTask;
taskDISABLE_INTERRUPTS();
__asm volatile( "bkpt #0" );
for (;;) {;}
}
static char myChar = 0;
QueueHandle_t uartRxQueue;
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
// --------------------------------------------------------------------------------------------------------------------
static void playgroundTask(void* args)
// --------------------------------------------------------------------------------------------------------------------
{
(void)args;
while(1) {
vTaskDelay(pdMS_TO_TICKS(10));
}
vTaskDelete(xTaskGetCurrentTaskHandle());
}
// --------------------------------------------------------------------------------------------------------------------
static int CapabilityFunc( int argc, char** argv, void* ctx )
// --------------------------------------------------------------------------------------------------------------------
{
(void)argc;
(void)argv;
(void)ctx;
printf("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\r\nOK",
0, // has spindle
0, // has spindle status
0, // has stepper
0, // has stepper move relative
0, // has stepper move speed
0, // has stepper move async
0, // has stepper status
0, // has stepper refrun
0, // has stepper refrun timeout
0, // has stepper refrun skip
0, // has stepper refrun stay enabled
0, // has stepper reset
0, // has stepper position
0, // has stepper config
0, // has stepper config torque
0, // has stepper config throvercurr
0, // has stepper config powerena
0, // has stepper config stepmode
0, // has stepper config timeoff
0, // has stepper config timeon
0, // has stepper config timefast
0, // has stepper config mmperturn
0, // has stepper config posmax
0, // has stepper config posmin
0, // has stepper config posref
0, // has stepper config stepsperturn
0 // has stepper cancel
);
return 0;
}
#define BKPSRAM_BASE 0x38800000UL
typedef struct {
uint32_t magic;
uint32_t uuid[3];
} device_shared_t;
#define DEVICE_SHARED \
((volatile device_shared_t *)BKPSRAM_BASE)
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
__HAL_RCC_BKPRAM_CLK_ENABLE();
// TODO: in case we have one of these special MCUs,
// ask lecturer before commenting in this line!
//RCC->GCR |= RCC_GCR_BOOT_C2;
//HAL_PWREx_ReleaseCore(PWR_CORE_CPU2);
HAL_PWR_EnableBkUpAccess();
FLASH_OBProgramInitTypeDef OptionsBytesStruct;
//HAL_FLASHEx_EnableDebugger();
HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);
uint32_t prev = OptionsBytesStruct.USERConfig;
#define BCM4 (1 << 22)
#define BCM7 (1 << 23)
#define nRST_STOP_D2 (1 << 24)
#define nRST_STDY_D2 (1 << 25)
if (!(OptionsBytesStruct.USERConfig & BCM4))
OptionsBytesStruct.USERConfig |= BCM4;
if (!(OptionsBytesStruct.USERConfig & BCM7))
OptionsBytesStruct.USERConfig |= BCM7;
if (!(OptionsBytesStruct.USERConfig & nRST_STOP_D2))
OptionsBytesStruct.USERConfig |= nRST_STOP_D2;
if (!(OptionsBytesStruct.USERConfig & nRST_STDY_D2))
OptionsBytesStruct.USERConfig |= nRST_STDY_D2;
if ( prev != OptionsBytesStruct.USERConfig) {
// TODO: in case we have one of these special MCUs,
// ask lecturer before commenting in this line!
//HAL_FLASHEx_OBProgram(&OptionsBytesStruct);
}
DEVICE_SHARED->uuid[0] = *(volatile uint32_t *)0x1FF1E800UL;
DEVICE_SHARED->uuid[1] = *(volatile uint32_t *)0x1FF1E804UL;
DEVICE_SHARED->uuid[2] = *(volatile uint32_t *)0x1FF1E808UL;
__DMB();
DEVICE_SHARED->magic = 0x48475531; // "HGU1"
__DMB();
/* USER CODE END 1 */
/* USER CODE BEGIN Boot_Mode_Sequence_0 */
/* USER CODE END Boot_Mode_Sequence_0 */
/* MPU Configuration--------------------------------------------------------*/
MPU_Config();
/* USER CODE BEGIN Boot_Mode_Sequence_1 */
/* Wait until CPU2 boots and enters in stop mode or timeout*/
int timeout = 0xFFFF;
while((__HAL_RCC_GET_FLAG(RCC_FLAG_D2CKRDY) != RESET) && (timeout-- > 0));
/*if ( timeout < 0 )
{
Error_Handler();
}*/
/* USER CODE END Boot_Mode_Sequence_1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN Boot_Mode_Sequence_2 */
/* When system initialization is finished, Cortex-M7 will release Cortex-M4 by means of
HSEM notification */
/*HW semaphore Clock enable*/
__HAL_RCC_HSEM_CLK_ENABLE();
/*Take HSEM */
HAL_HSEM_FastTake(HSEM_ID_0);
/*Release HSEM in order to notify the CPU2(CM4)*/
HAL_HSEM_Release(HSEM_ID_0,0);
/* wait until CPU2 wakes up from stop mode */
while((__HAL_RCC_GET_FLAG(RCC_FLAG_D2CKRDY) == RESET));
/* USER CODE END Boot_Mode_Sequence_2 */
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_SPI1_Init();
MX_TIM2_Init();
MX_USART3_UART_Init();
/* USER CODE BEGIN 2 */
// cretae a free rtos queue to buffer console characters received from debug uart
uartRxQueue = xQueueCreate(64, sizeof(char));
HAL_UART_Receive_IT(&huart3, (uint8_t *)&myChar, sizeof(myChar));
// create a playground task at the very beginning
xTaskCreate(playgroundTask, "playground", 128, NULL, 1, NULL);
// mask a compiler warning by referencing the function but not using it (void cast)
(void)CapabilityFunc;
// start the scheduler and setup free rtos execution context
vTaskStartScheduler();
// we should never reach that point!
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Supply configuration update enable
*/
HAL_PWREx_ConfigSupply(PWR_DIRECT_SMPS_SUPPLY);
/** Configure the main internal regulator output voltage
*/
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 1;
RCC_OscInitStruct.PLL.PLLN = 100;
RCC_OscInitStruct.PLL.PLLP = 2;
RCC_OscInitStruct.PLL.PLLQ = 4;
RCC_OscInitStruct.PLL.PLLR = 2;
RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_3;
RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE;
RCC_OscInitStruct.PLL.PLLFRACN = 0;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
|RCC_CLOCKTYPE_D3PCLK1|RCC_CLOCKTYPE_D1PCLK1;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2;
RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief SPI1 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI1_Init(void)
{
/* USER CODE BEGIN SPI1_Init 0 */
/* USER CODE END SPI1_Init 0 */
/* USER CODE BEGIN SPI1_Init 1 */
/* USER CODE END SPI1_Init 1 */
/* SPI1 parameter configuration*/
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_HIGH;
hspi1.Init.CLKPhase = SPI_PHASE_2EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 0x0;
hspi1.Init.NSSPMode = SPI_NSS_PULSE_ENABLE;
hspi1.Init.NSSPolarity = SPI_NSS_POLARITY_LOW;
hspi1.Init.FifoThreshold = SPI_FIFO_THRESHOLD_01DATA;
hspi1.Init.TxCRCInitializationPattern = SPI_CRC_INITIALIZATION_ALL_ZERO_PATTERN;
hspi1.Init.RxCRCInitializationPattern = SPI_CRC_INITIALIZATION_ALL_ZERO_PATTERN;
hspi1.Init.MasterSSIdleness = SPI_MASTER_SS_IDLENESS_00CYCLE;
hspi1.Init.MasterInterDataIdleness = SPI_MASTER_INTERDATA_IDLENESS_00CYCLE;
hspi1.Init.MasterReceiverAutoSusp = SPI_MASTER_RX_AUTOSUSP_DISABLE;
hspi1.Init.MasterKeepIOState = SPI_MASTER_KEEP_IO_STATE_DISABLE;
hspi1.Init.IOSwap = SPI_IO_SWAP_DISABLE;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI1_Init 2 */
/* USER CODE END SPI1_Init 2 */
}
/**
* @brief TIM2 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM2_Init(void)
{
/* USER CODE BEGIN TIM2_Init 0 */
/* USER CODE END TIM2_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM2_Init 1 */
/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 0;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 9999;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */
/* USER CODE END TIM2_Init 2 */
HAL_TIM_MspPostInit(&htim2);
}
/**
* @brief USART3 Initialization Function
* @param None
* @retval None
*/
static void MX_USART3_UART_Init(void)
{
/* USER CODE BEGIN USART3_Init 0 */
/* USER CODE END USART3_Init 0 */
/* USER CODE BEGIN USART3_Init 1 */
/* USER CODE END USART3_Init 1 */
huart3.Instance = USART3;
huart3.Init.BaudRate = 115200;
huart3.Init.WordLength = UART_WORDLENGTH_8B;
huart3.Init.StopBits = UART_STOPBITS_1;
huart3.Init.Parity = UART_PARITY_NONE;
huart3.Init.Mode = UART_MODE_TX_RX;
huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart3.Init.OverSampling = UART_OVERSAMPLING_16;
huart3.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart3.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart3.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart3) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&huart3, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&huart3, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&huart3) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART3_Init 2 */
/* USER CODE END USART3_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOG_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOE, SPINDLE_ENA_L_Pin|SPINDLE_ENA_R_Pin|LED_YELLOW_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, LED_GREEN_Pin|LED_RED_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOD, STEP_SPI_CS_Pin|STEP_PULSE_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOG, STEP_RSTN_Pin|STEP_DIR_Pin, GPIO_PIN_RESET);
/*Configure GPIO pins : SPINDLE_ENA_L_Pin SPINDLE_ENA_R_Pin LED_YELLOW_Pin */
GPIO_InitStruct.Pin = SPINDLE_ENA_L_Pin|SPINDLE_ENA_R_Pin|LED_YELLOW_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/*Configure GPIO pin : USR_BUTTON_Pin */
GPIO_InitStruct.Pin = USR_BUTTON_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(USR_BUTTON_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : SPINDLE_SI_R_Pin */
GPIO_InitStruct.Pin = SPINDLE_SI_R_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(SPINDLE_SI_R_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : LED_GREEN_Pin LED_RED_Pin */
GPIO_InitStruct.Pin = LED_GREEN_Pin|LED_RED_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pins : STEP_SPI_CS_Pin STEP_PULSE_Pin */
GPIO_InitStruct.Pin = STEP_SPI_CS_Pin|STEP_PULSE_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/*Configure GPIO pins : STEP_RSTN_Pin STEP_DIR_Pin */
GPIO_InitStruct.Pin = STEP_RSTN_Pin|STEP_DIR_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);
/*Configure GPIO pin : STEP_FLAG_Pin */
GPIO_InitStruct.Pin = STEP_FLAG_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(STEP_FLAG_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : REFERENCE_MARK_Pin LIMIT_SWITCH_Pin */
GPIO_InitStruct.Pin = REFERENCE_MARK_Pin|LIMIT_SWITCH_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : SPINDLE_SI_L_Pin */
GPIO_InitStruct.Pin = SPINDLE_SI_L_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(SPINDLE_SI_L_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}
/* USER CODE BEGIN 4 */
void vAssertCalled( const char * const pcFileName, unsigned long ulLine )
{
volatile uint32_t ulSetToNonZeroInDebuggerToContinue = 0;
/* Parameters are not used. */
( void ) ulLine;
( void ) pcFileName;
taskENTER_CRITICAL();
{
/* You can step out of this function to debug the assertion by using
the debugger to set ulSetToNonZeroInDebuggerToContinue to a non-zero
value. */
while( ulSetToNonZeroInDebuggerToContinue == 0 )
{
}
}
taskEXIT_CRITICAL();
}
int __stdout_put_char(int ch)
{
uint8_t val = ch;
while((huart3.Instance->ISR & UART_FLAG_TXE) == 0);
huart3.Instance->TDR = val;
while((huart3.Instance->ISR & UART_FLAG_TC) == 0);
return 0;
}
int __stdin_get_char(void)
{
if ( xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED )
{
if (huart3.Instance->ISR & UART_FLAG_ORE)
huart3.Instance->ICR = UART_CLEAR_OREF;
if (huart3.Instance->ISR & UART_FLAG_NE)
huart3.Instance->ICR = UART_CLEAR_NEF;
if (huart3.Instance->ISR & UART_FLAG_FE)
huart3.Instance->ICR = UART_CLEAR_FEF;
if ((huart3.Instance->ISR & UART_FLAG_RXNE) == 0) return -1;
return huart3.Instance->RDR;
}
else
{
// we make sure that EOF is returned in case there is a small pause time
// in the input sequence, therefore we do not block infinitely long!
int value = EOF;
if ( xQueueReceive(uartRxQueue, &value, 10 ) ) return value;
else return EOF;
}
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
if ( huart->Instance == USART3 )
{
if ( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )
{
xQueueSendFromISR(uartRxQueue, &myChar, &xHigherPriorityTaskWoken);
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
HAL_UART_Receive_IT(&huart3, (uint8_t *)&myChar, sizeof(myChar));
}
}
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
if ( huart->Instance == USART3 )
{
HAL_UART_Receive_IT(&huart3, (uint8_t *)&myChar, sizeof(myChar));
}
}
/* USER CODE END 4 */
/* MPU Configuration */
void MPU_Config(void)
{
MPU_Region_InitTypeDef MPU_InitStruct = {0};
/* Disables the MPU */
HAL_MPU_Disable();
/** Initializes and configures the Region and the memory to be protected
*/
MPU_InitStruct.Enable = MPU_REGION_ENABLE;
MPU_InitStruct.Number = MPU_REGION_NUMBER0;
MPU_InitStruct.BaseAddress = 0x0;
MPU_InitStruct.Size = MPU_REGION_SIZE_4GB;
MPU_InitStruct.SubRegionDisable = 0x87;
MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0;
MPU_InitStruct.AccessPermission = MPU_REGION_NO_ACCESS;
MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE;
MPU_InitStruct.IsShareable = MPU_ACCESS_SHAREABLE;
MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE;
MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE;
HAL_MPU_ConfigRegion(&MPU_InitStruct);
/** Initializes and configures the Region and the memory to be protected
*/
MPU_InitStruct.Number = MPU_REGION_NUMBER1;
MPU_InitStruct.BaseAddress = 0x38000000;
MPU_InitStruct.Size = MPU_REGION_SIZE_64KB;
MPU_InitStruct.SubRegionDisable = 0x0;
MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS;
HAL_MPU_ConfigRegion(&MPU_InitStruct);
/* Enables the MPU */
HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);
}
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
@@ -0,0 +1,757 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "openamp.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "stdio.h"
#include "assert.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#ifndef HSEM_ID_0
#define HSEM_ID_0 (0U) /* HW semaphore 0*/
#endif
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
SPI_HandleTypeDef hspi1;
TIM_HandleTypeDef htim2;
UART_HandleTypeDef huart3;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MPU_Config(void);
static void MX_GPIO_Init(void);
static void MX_SPI1_Init(void);
static void MX_TIM2_Init(void);
static void MX_USART3_UART_Init(void);
/* USER CODE BEGIN PFP */
extern void initialise_stdlib_abstraction( void );
void vApplicationMallocFailedHook( void )
{
taskDISABLE_INTERRUPTS();
__asm volatile( "bkpt #0" );
for (;;) {;}
}
/*-----------------------------------------------------------*/
void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
{
( void ) pcTaskName;
( void ) pxTask;
taskDISABLE_INTERRUPTS();
__asm volatile( "bkpt #0" );
for (;;) {;}
}
static char myChar = 0;
QueueHandle_t uartRxQueue;
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
// --------------------------------------------------------------------------------------------------------------------
static void playgroundTask(void* args)
// --------------------------------------------------------------------------------------------------------------------
{
(void)args;
while(1) {
vTaskDelay(pdMS_TO_TICKS(10));
}
vTaskDelete(xTaskGetCurrentTaskHandle());
}
// --------------------------------------------------------------------------------------------------------------------
static int CapabilityFunc( int argc, char** argv, void* ctx )
// --------------------------------------------------------------------------------------------------------------------
{
(void)argc;
(void)argv;
(void)ctx;
printf("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\r\nOK",
0, // has spindle
0, // has spindle status
0, // has stepper
0, // has stepper move relative
0, // has stepper move speed
0, // has stepper move async
0, // has stepper status
0, // has stepper refrun
0, // has stepper refrun timeout
0, // has stepper refrun skip
0, // has stepper refrun stay enabled
0, // has stepper reset
0, // has stepper position
0, // has stepper config
0, // has stepper config torque
0, // has stepper config throvercurr
0, // has stepper config powerena
0, // has stepper config stepmode
0, // has stepper config timeoff
0, // has stepper config timeon
0, // has stepper config timefast
0, // has stepper config mmperturn
0, // has stepper config posmax
0, // has stepper config posmin
0, // has stepper config posref
0, // has stepper config stepsperturn
0 // has stepper cancel
);
return 0;
}
#define BKPSRAM_BASE 0x38800000UL
typedef struct {
uint32_t magic;
uint32_t uuid[3];
} device_shared_t;
#define DEVICE_SHARED \
((volatile device_shared_t *)BKPSRAM_BASE)
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
__HAL_RCC_BKPRAM_CLK_ENABLE();
// TODO: in case we have one of these special MCUs,
// ask lecturer before commenting in this line!
//RCC->GCR |= RCC_GCR_BOOT_C2;
//HAL_PWREx_ReleaseCore(PWR_CORE_CPU2);
HAL_PWR_EnableBkUpAccess();
FLASH_OBProgramInitTypeDef OptionsBytesStruct;
//HAL_FLASHEx_EnableDebugger();
HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);
uint32_t prev = OptionsBytesStruct.USERConfig;
#define BCM4 (1 << 22)
#define BCM7 (1 << 23)
#define nRST_STOP_D2 (1 << 24)
#define nRST_STDY_D2 (1 << 25)
if (!(OptionsBytesStruct.USERConfig & BCM4))
OptionsBytesStruct.USERConfig |= BCM4;
if (!(OptionsBytesStruct.USERConfig & BCM7))
OptionsBytesStruct.USERConfig |= BCM7;
if (!(OptionsBytesStruct.USERConfig & nRST_STOP_D2))
OptionsBytesStruct.USERConfig |= nRST_STOP_D2;
if (!(OptionsBytesStruct.USERConfig & nRST_STDY_D2))
OptionsBytesStruct.USERConfig |= nRST_STDY_D2;
if ( prev != OptionsBytesStruct.USERConfig) {
// TODO: in case we have one of these special MCUs,
// ask lecturer before commenting in this line!
//HAL_FLASHEx_OBProgram(&OptionsBytesStruct);
}
DEVICE_SHARED->uuid[0] = *(volatile uint32_t *)0x1FF1E800UL;
DEVICE_SHARED->uuid[1] = *(volatile uint32_t *)0x1FF1E804UL;
DEVICE_SHARED->uuid[2] = *(volatile uint32_t *)0x1FF1E808UL;
__DMB();
DEVICE_SHARED->magic = 0x48475531; // "HGU1"
__DMB();
/* USER CODE END 1 */
/* USER CODE BEGIN Boot_Mode_Sequence_0 */
/* USER CODE END Boot_Mode_Sequence_0 */
/* MPU Configuration--------------------------------------------------------*/
MPU_Config();
/* USER CODE BEGIN Boot_Mode_Sequence_1 */
/* Wait until CPU2 boots and enters in stop mode or timeout*/
int timeout = 0xFFFF;
while((__HAL_RCC_GET_FLAG(RCC_FLAG_D2CKRDY) != RESET) && (timeout-- > 0));
/*if ( timeout < 0 )
{
Error_Handler();
}*/
/* USER CODE END Boot_Mode_Sequence_1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN Boot_Mode_Sequence_2 */
/* When system initialization is finished, Cortex-M7 will release Cortex-M4 by means of
HSEM notification */
/*HW semaphore Clock enable*/
__HAL_RCC_HSEM_CLK_ENABLE();
/*Take HSEM */
HAL_HSEM_FastTake(HSEM_ID_0);
/*Release HSEM in order to notify the CPU2(CM4)*/
HAL_HSEM_Release(HSEM_ID_0,0);
/* wait until CPU2 wakes up from stop mode */
while((__HAL_RCC_GET_FLAG(RCC_FLAG_D2CKRDY) == RESET));
/* USER CODE END Boot_Mode_Sequence_2 */
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_SPI1_Init();
MX_TIM2_Init();
MX_USART3_UART_Init();
/* USER CODE BEGIN 2 */
// cretae a free rtos queue to buffer console characters received from debug uart
uartRxQueue = xQueueCreate(64, sizeof(char));
HAL_UART_Receive_IT(&huart3, (uint8_t *)&myChar, sizeof(myChar));
// create a playground task at the very beginning
xTaskCreate(playgroundTask, "playground", 128, NULL, 1, NULL);
// mask a compiler warning by referencing the function but not using it (void cast)
(void)CapabilityFunc;
// start the schedular and setup free rtos execution context
vTaskStartScheduler();
// we should never reach that point!
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Supply configuration update enable
*/
HAL_PWREx_ConfigSupply(PWR_DIRECT_SMPS_SUPPLY);
/** Configure the main internal regulator output voltage
*/
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 1;
RCC_OscInitStruct.PLL.PLLN = 100;
RCC_OscInitStruct.PLL.PLLP = 2;
RCC_OscInitStruct.PLL.PLLQ = 4;
RCC_OscInitStruct.PLL.PLLR = 2;
RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_3;
RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE;
RCC_OscInitStruct.PLL.PLLFRACN = 0;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
|RCC_CLOCKTYPE_D3PCLK1|RCC_CLOCKTYPE_D1PCLK1;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2;
RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief SPI1 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI1_Init(void)
{
/* USER CODE BEGIN SPI1_Init 0 */
/* USER CODE END SPI1_Init 0 */
/* USER CODE BEGIN SPI1_Init 1 */
/* USER CODE END SPI1_Init 1 */
/* SPI1 parameter configuration*/
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_HIGH;
hspi1.Init.CLKPhase = SPI_PHASE_2EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 0x0;
hspi1.Init.NSSPMode = SPI_NSS_PULSE_ENABLE;
hspi1.Init.NSSPolarity = SPI_NSS_POLARITY_LOW;
hspi1.Init.FifoThreshold = SPI_FIFO_THRESHOLD_01DATA;
hspi1.Init.TxCRCInitializationPattern = SPI_CRC_INITIALIZATION_ALL_ZERO_PATTERN;
hspi1.Init.RxCRCInitializationPattern = SPI_CRC_INITIALIZATION_ALL_ZERO_PATTERN;
hspi1.Init.MasterSSIdleness = SPI_MASTER_SS_IDLENESS_00CYCLE;
hspi1.Init.MasterInterDataIdleness = SPI_MASTER_INTERDATA_IDLENESS_00CYCLE;
hspi1.Init.MasterReceiverAutoSusp = SPI_MASTER_RX_AUTOSUSP_DISABLE;
hspi1.Init.MasterKeepIOState = SPI_MASTER_KEEP_IO_STATE_DISABLE;
hspi1.Init.IOSwap = SPI_IO_SWAP_DISABLE;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI1_Init 2 */
/* USER CODE END SPI1_Init 2 */
}
/**
* @brief TIM2 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM2_Init(void)
{
/* USER CODE BEGIN TIM2_Init 0 */
/* USER CODE END TIM2_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM2_Init 1 */
/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 0;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 9999;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */
/* USER CODE END TIM2_Init 2 */
HAL_TIM_MspPostInit(&htim2);
}
/**
* @brief USART3 Initialization Function
* @param None
* @retval None
*/
static void MX_USART3_UART_Init(void)
{
/* USER CODE BEGIN USART3_Init 0 */
/* USER CODE END USART3_Init 0 */
/* USER CODE BEGIN USART3_Init 1 */
/* USER CODE END USART3_Init 1 */
huart3.Instance = USART3;
huart3.Init.BaudRate = 115200;
huart3.Init.WordLength = UART_WORDLENGTH_8B;
huart3.Init.StopBits = UART_STOPBITS_1;
huart3.Init.Parity = UART_PARITY_NONE;
huart3.Init.Mode = UART_MODE_TX_RX;
huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart3.Init.OverSampling = UART_OVERSAMPLING_16;
huart3.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart3.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart3.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart3) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&huart3, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&huart3, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&huart3) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART3_Init 2 */
/* USER CODE END USART3_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOG_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOE, SPINDLE_ENA_L_Pin|SPINDLE_ENA_R_Pin|LED_YELLOW_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, LED_GREEN_Pin|LED_RED_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOD, STEP_SPI_CS_Pin|STEP_PULSE_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOG, STEP_RSTN_Pin|STEP_DIR_Pin, GPIO_PIN_RESET);
/*Configure GPIO pins : SPINDLE_ENA_L_Pin SPINDLE_ENA_R_Pin LED_YELLOW_Pin */
GPIO_InitStruct.Pin = SPINDLE_ENA_L_Pin|SPINDLE_ENA_R_Pin|LED_YELLOW_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/*Configure GPIO pin : USR_BUTTON_Pin */
GPIO_InitStruct.Pin = USR_BUTTON_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(USR_BUTTON_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : SPINDLE_SI_R_Pin */
GPIO_InitStruct.Pin = SPINDLE_SI_R_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(SPINDLE_SI_R_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : LED_GREEN_Pin LED_RED_Pin */
GPIO_InitStruct.Pin = LED_GREEN_Pin|LED_RED_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pins : STEP_SPI_CS_Pin STEP_PULSE_Pin */
GPIO_InitStruct.Pin = STEP_SPI_CS_Pin|STEP_PULSE_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/*Configure GPIO pins : STEP_RSTN_Pin STEP_DIR_Pin */
GPIO_InitStruct.Pin = STEP_RSTN_Pin|STEP_DIR_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);
/*Configure GPIO pin : STEP_FLAG_Pin */
GPIO_InitStruct.Pin = STEP_FLAG_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(STEP_FLAG_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : REFERENCE_MARK_Pin LIMIT_SWITCH_Pin */
GPIO_InitStruct.Pin = REFERENCE_MARK_Pin|LIMIT_SWITCH_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : SPINDLE_SI_L_Pin */
GPIO_InitStruct.Pin = SPINDLE_SI_L_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(SPINDLE_SI_L_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}
/* USER CODE BEGIN 4 */
void vAssertCalled( const char * const pcFileName, unsigned long ulLine )
{
volatile uint32_t ulSetToNonZeroInDebuggerToContinue = 0;
/* Parameters are not used. */
( void ) ulLine;
( void ) pcFileName;
taskENTER_CRITICAL();
{
/* You can step out of this function to debug the assertion by using
the debugger to set ulSetToNonZeroInDebuggerToContinue to a non-zero
value. */
while( ulSetToNonZeroInDebuggerToContinue == 0 )
{
}
}
taskEXIT_CRITICAL();
}
int __stdout_put_char(int ch)
{
uint8_t val = ch;
while((huart3.Instance->ISR & UART_FLAG_TXE) == 0);
huart3.Instance->TDR = val;
while((huart3.Instance->ISR & UART_FLAG_TC) == 0);
return 0;
}
int __stdin_get_char(void)
{
if ( xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED )
{
if (huart3.Instance->ISR & UART_FLAG_ORE)
huart3.Instance->ICR = UART_CLEAR_OREF;
if (huart3.Instance->ISR & UART_FLAG_NE)
huart3.Instance->ICR = UART_CLEAR_NEF;
if (huart3.Instance->ISR & UART_FLAG_FE)
huart3.Instance->ICR = UART_CLEAR_FEF;
if ((huart3.Instance->ISR & UART_FLAG_RXNE) == 0) return -1;
return huart3.Instance->RDR;
}
else
{
// we make sure that EOF is returned in case there is a small pause time
// in the input sequence, therefore we do not block infinitely long!
int value = EOF;
if ( xQueueReceive(uartRxQueue, &value, 10 ) ) return value;
else return EOF;
}
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
if ( huart->Instance == USART3 )
{
if ( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )
{
xQueueSendFromISR(uartRxQueue, &myChar, &xHigherPriorityTaskWoken);
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
HAL_UART_Receive_IT(&huart3, (uint8_t *)&myChar, sizeof(myChar));
}
}
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
if ( huart->Instance == USART3 )
{
HAL_UART_Receive_IT(&huart3, (uint8_t *)&myChar, sizeof(myChar));
}
}
/* USER CODE END 4 */
/* MPU Configuration */
void MPU_Config(void)
{
MPU_Region_InitTypeDef MPU_InitStruct = {0};
/* Disables the MPU */
HAL_MPU_Disable();
/** Initializes and configures the Region and the memory to be protected
*/
MPU_InitStruct.Enable = MPU_REGION_ENABLE;
MPU_InitStruct.Number = MPU_REGION_NUMBER0;
MPU_InitStruct.BaseAddress = 0x0;
MPU_InitStruct.Size = MPU_REGION_SIZE_4GB;
MPU_InitStruct.SubRegionDisable = 0x87;
MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0;
MPU_InitStruct.AccessPermission = MPU_REGION_NO_ACCESS;
MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE;
MPU_InitStruct.IsShareable = MPU_ACCESS_SHAREABLE;
MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE;
MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE;
HAL_MPU_ConfigRegion(&MPU_InitStruct);
/** Initializes and configures the Region and the memory to be protected
*/
MPU_InitStruct.Number = MPU_REGION_NUMBER1;
MPU_InitStruct.BaseAddress = 0x38000000;
MPU_InitStruct.Size = MPU_REGION_SIZE_64KB;
MPU_InitStruct.SubRegionDisable = 0x0;
MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS;
HAL_MPU_ConfigRegion(&MPU_InitStruct);
/* Enables the MPU */
HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);
}
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
@@ -0,0 +1,868 @@
/**
* \file mvsyscall.c
* \brief Wrappers required to use newlib malloc-family within FreeRTOS.
* The syscalls for stdlib are implemented in a minimum way as well
*
* \par Overview
* Route FreeRTOS memory management functions to newlib's malloc family.
* Thus newlib and FreeRTOS share memory-management routines and memory pool,
* and all newlib's internal memory-management requirements are supported.
*
* \author Dave Nadler
* \author Thorsten Kimmel
* \date 20-August-2019
* \version 02-Dec-2021 implemented syscalls for stdlib
* \version 27-Jun-2020 Correct "FreeRTOS.h" capitalization, commentary
* \version 24-Jun-2020 commentary only
* \version 11-Sep-2019 malloc accounting, comments, newlib version check
*
* \see http://www.nadler.com/embedded/newlibAndFreeRTOS.html
* \see https://sourceware.org/newlib/libc.html#Reentrancy
* \see https://sourceware.org/newlib/libc.html#malloc
* \see https://sourceware.org/newlib/libc.html#index-_005f_005fenv_005flock
* \see https://sourceware.org/newlib/libc.html#index-_005f_005fmalloc_005flock
* \see https://sourceforge.net/p/freertos/feature-requests/72/
* \see http://www.billgatliff.com/newlib.html
* \see http://wiki.osdev.org/Porting_Newlib
* \see http://www.embecosm.com/appnotes/ean9/ean9-howto-newlib-1.0.html
*
*
* \copyright
* (c) Dave Nadler 2017-2020, All Rights Reserved.
* Web: http://www.nadler.com
* email: drn@nadler.com
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Use or redistributions of source code must retain the above copyright notice,
* this list of conditions, and the following disclaimer.
*
* - Use or redistributions of source code must retain ALL ORIGINAL COMMENTS, AND
* ANY CHANGES MUST BE DOCUMENTED, INCLUDING:
* - Reason for change (purpose)
* - Functional change
* - Date and author contact
*
* - 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.
*
* 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.
*/
/*!
* Includes
*/
// ----------------------------------------------------------------------------
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <sys/times.h>
#include <newlib.h>
#include <malloc.h>
#include <FreeRTOS.h>
/*!
* In case there is a FreeRTOS used for this application, we have to include
* additional dependencies which are used in memory wrappers
*/
// ----------------------------------------------------------------------------
#ifdef INC_FREERTOS_H
# include "task.h"
# include "semphr.h"
#endif
// ----------------------------------------------------------------------------
/*!
* conditional check to make sure this syscall abstraction and the memory
* wrapper fits to the correct newlib / stdlib version
*/
// ----------------------------------------------------------------------------
#if (( __NEWLIB__ != 3) && ( __NEWLIB__ != 4 )) || ((__NEWLIB__ != 3) && (__NEWLIB_MINOR__ < 1)) || \
((__NEWLIB__ == 3) && (__NEWLIB_MINOR__ > 3) )
#warning "This wrapper was verified for newlib versions 3.1 - 3.3; please ensure newlib's external requirements for malloc-family are unchanged!"
#endif
// ----------------------------------------------------------------------------
/*!
* conditional check to make sure the correct reentrancy configuration has been
* set. Otherwise the stdlib calls could be lead to undefined behavior whenever
* a function is called simultaneous by more than one thread
*/
// ----------------------------------------------------------------------------
#ifdef INC_FREERTOS_H
# if !defined(configUSE_NEWLIB_REENTRANT) || (configUSE_NEWLIB_REENTRANT != 1)
# error "#define configUSE_NEWLIB_REENTRANT 1 which is required for thread-safety of newlib sprintf, dtoa, strtok, etc..."
# endif
#endif
// ----------------------------------------------------------------------------
#ifdef INC_FREERTOS_H
// ----------------------------------------------------------------------------
// The following functions are used to lock IRQs to make sure the newlib functions
// can be used in an IRQ as well, this is not working as expected and so we disable it
// for our platform so far, therefore we have to make sure the user can not enter newlib
// functions when running in ISR context
//! Disables interrupts (after saving prior state)
# define NEWLIB_FUNCS_INSIDE_ISR 0
# if defined(NEWLIB_FUNCS_INSIDE_ISR) && NEWLIB_FUNCS_INSIDE_ISR != 0
define DRN_ENTER_CRITICAL_SECTION(_usis) { _usis = taskENTER_CRITICAL_FROM_ISR(); }
# else
# define DRN_ENTER_CRITICAL_SECTION(_usis) do { int insideAnISR = xPortIsInsideInterrupt(); configASSERT( !insideAnISR ); } while(0)
# endif
//! Re-enables interrupts (unless already disabled prior taskENTER_CRITICAL)
# if defined(NEWLIB_FUNCS_INSIDE_ISR) && NEWLIB_FUNCS_INSIDE_ISR != 0
# define DRN_EXIT_CRITICAL_SECTION(_usis) { taskEXIT_CRITICAL_FROM_ISR(_usis); }
# else
# define DRN_EXIT_CRITICAL_SECTION(_usis)
# endif
// ----------------------------------------------------------------------------
# define __HeapBase _end
# define __HeapLimit _estack
#define MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_STDOUT
#define MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_MALLOC
#define MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_ENV
/*!
* The symbols __HeapBase and __HeapLimit are defined to read the
* heap parameters from symbols defined in the linker script. The
* define macros above are used to adapt these names to the name
* of the variable in the linker script. Both variables will be used
* later to allocate and manage memory of the heap and to detect a
* stack / heap crash...
*/
// ----------------------------------------------------------------------------
extern char __HeapBase, __HeapLimit;
int _write( int file, char* ptr, int len );
int _read( int file, char* ptr, int len );
/*!
* The following semaphore is used to prevent the stdout and stderr device
* to be accessed simultaneous while writing data. This is necessary because
* the stdlib itself is thread safe and has its own buffers for a thread but
* the access to the hardware must be locked as well
*/
// ----------------------------------------------------------------------------
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_STDOUT)
static SemaphoreHandle_t stdioSemaphore;
#endif
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_MALLOC)
static SemaphoreHandle_t mallocSemaphore;
#endif
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_ENV)
static SemaphoreHandle_t envSemaphore;
#endif
#endif
/*!
* pointer to array of char* strings that define the current
* environment variables of the applications environment
*/
// ----------------------------------------------------------------------------
#define xstr(a) str(a)
#define str(a) #a
#define NEWLIB_ENV "STDLIB=newlib-" xstr(__NEWLIB__) "." xstr(__NEWLIB_MINOR__)
#ifdef NDEBUG
# define DEBUG_ENV "DEBUG_ENV=RELEASE"
#else
# define DEBUG_ENV "DEBUG_ENV=DEBUG"
#endif
#define GNUC_ENV "GNUC=" xstr(__GNUC__) "." xstr(__GNUC_MINOR__)
#define OS_VERSION_ENV "OSVERSION=" xstr(tskKERNEL_VERSION_MAJOR) "." xstr(tskKERNEL_VERSION_MINOR)
static char* __env[] = { "ARCH=ARM32", "MCU=STM32F746ZI", "PLATFORM=ARM_FW_PLAYGROUND", "OS=FreeRTOS", "USERNAME=STM32",
NEWLIB_ENV, OS_VERSION_ENV, GNUC_ENV, DEBUG_ENV, "BUILDTIME=" xstr(__TIME__), "BUILDDATE=" xstr(__DATE__),
NULL
};
char** environ = &__env[0];
// ----------------------------------------------------------------------------
/*!
* \brief is used to provide an overwritable stdout channel which can be used
* for debugging purposes in the application
* \param chr
*/
// ----------------------------------------------------------------------------
__attribute__( ( weak ) ) void __stdout_put_char( int chr );
// ----------------------------------------------------------------------------
/*!
* \brief is used to provide an overwritable stdin channel which can be used
* for debugging purposes in the application
*/
// ----------------------------------------------------------------------------
__attribute__( ( weak ) ) int __stdin_get_char( void )
{
return -1;
}
// ----------------------------------------------------------------------------
/*!
* \brief is used to provide an overwritable clock tick function which is used
* by the stdlib
*/
// ----------------------------------------------------------------------------
__attribute__( ( weak ) ) unsigned long long __stdlib_get_system_clock_ticks( void )
{
#if defined(INC_FREERTOS_H)
return (unsigned long long)xTaskGetTickCount();
#else
return 0;
#endif
}
// ----------------------------------------------------------------------------
/*!
* \brief semihosting initialization function which should be called when _start
* is called. afterwards main would be called.
*/
// ----------------------------------------------------------------------------
void initialise_monitor_handles( void )
// ----------------------------------------------------------------------------
{
}
/*!
* \brief this function will be called after initialization of the .bss, .text,
* and .data segment of the application and while the stdlib begins to initialize
* its requirements. This is done by calling the __libc_init_array in _start.S routine
* before calling the main function. By tagging a function with the "constructor"
* attribute, the compiler will add the function pointer to this initialization list.
* \attention This is a GCC attribute. In case the application is compiled with another
* compiler, this attribute must be ported as well!
*/
// ----------------------------------------------------------------------------
__attribute__((constructor))
void initialise_stdlib_abstraction( void )
// ----------------------------------------------------------------------------
{
initialise_monitor_handles();
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_STDOUT)
stdioSemaphore = xSemaphoreCreateRecursiveMutex();
if ( stdioSemaphore == 0 )
{
vAssertCalled( __FILE__, __LINE__ );
}
#endif
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_MALLOC)
mallocSemaphore = xSemaphoreCreateRecursiveMutex();
if ( mallocSemaphore == 0 )
{
vAssertCalled( __FILE__, __LINE__ );
}
#endif
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_ENV)
envSemaphore = xSemaphoreCreateRecursiveMutex();
if ( envSemaphore == 0 )
{
vAssertCalled( __FILE__, __LINE__ );
}
#endif
}
/*!
* \brief returns the process ID (PID) of the calling process.
* \attention we have no real OS and so we only return PID 1 because
* this is the only running process. Everything is in "kernel space" or
* "machine mode"
*/
// ----------------------------------------------------------------------------
int _getpid( void )
// ----------------------------------------------------------------------------
{
return 1;
}
/*!
* \brief The command kill sends the specified signal to the specified
* process.
* \attention we have no real OS and so we cannot kill our only running
* process with PID 1
*/
// ----------------------------------------------------------------------------
int _kill( int pid, int sig )
// ----------------------------------------------------------------------------
{
( void )pid;
( void )sig;
if ( _impure_ptr != 0 )
{
_impure_ptr->_errno = EINVAL;
}
errno = EINVAL;
return -1;
}
/*!
* \brief The command exit is used to stop the process or application
* \attention if the application has called exit, we do must not return
* from this function anymore
*/
// ----------------------------------------------------------------------------
__attribute__( ( noreturn ) )
void _exit ( int status )
// ----------------------------------------------------------------------------
{
_kill( status, -1 );
while ( 1 ) {}
}
/*!
* \brief attempts to read up to 'len' bytes from file descriptor 'file'
* into the buffer starting at 'ptr'.
* \note currently there is only support for stdin. If any other devices
* have to be integrated as well, one should implement an abstraction layer
* which delegates the calls directly to the required device or ressource.
* An example can be seen in altera board support packages with the "dev" struct
*/
// ----------------------------------------------------------------------------
int _read( int file, char* ptr, int len )
// ----------------------------------------------------------------------------
{
( void )file;
int DataIdx;
int resLen = 0;
if ( file == STDIN_FILENO )
{
for ( DataIdx = 0; DataIdx < len; )
{
int result = __stdin_get_char();
if ( result == EOF )
{
if ( resLen == 0 )
{
resLen = EOF;
}
break;
}
*ptr++ = ( char )result;
resLen++;
DataIdx++;
}
}
else
{
if ( _impure_ptr != 0 )
{
_impure_ptr->_errno = EBADF;
}
errno = EBADF;
return -1;
}
return resLen;
}
/*!
* \brief attempts to write 'len' bytes from file descriptor 'file'
* out of the buffer starting at 'ptr'.
* \note currently there is only support for stdout and stderr. If any other devices
* have to be integrated as well, one should implement an abstraction layer
* which delegates the calls directly to the required device or ressource.
* An example can be seen in altera board support packages with the "dev" struct
*/
// ----------------------------------------------------------------------------
int _write( int file, char* ptr, int len )
// ----------------------------------------------------------------------------
{
( void )file;
int DataIdx, locked = 0;
if ( file == STDOUT_FILENO || file == STDERR_FILENO )
{
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_STDOUT)
if ( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
{
xSemaphoreTakeRecursive( stdioSemaphore, -1 );
locked = 1;
}
#endif
if (file == STDERR_FILENO)
{
__stdout_put_char('\033');
__stdout_put_char('[');
__stdout_put_char('3');
__stdout_put_char('1');
__stdout_put_char('m');
}
for ( DataIdx = 0; DataIdx < len; DataIdx++ )
{
__stdout_put_char( ptr[DataIdx] );
}
if (file == STDERR_FILENO)
{
__stdout_put_char('\033');
__stdout_put_char('[');
__stdout_put_char('0');
__stdout_put_char('m');
}
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_STDOUT)
if ( locked )
{
xSemaphoreGiveRecursive( stdioSemaphore );
}
#endif
return len;
}
else
{
if ( _impure_ptr != 0 )
{
_impure_ptr->_errno = EBADF;
}
errno = EBADF;
return -1;
}
}
/*!
* \brief attempts to close a descriptor.
* \note currently there is no support for this function. If any other devices
* have to be integrated as well, one should implement an abstraction layer
* which delegates the calls directly to the required device or ressource.
* An example can be seen in altera board support packages with the "dev" struct
*/
// ----------------------------------------------------------------------------
int _close( int file )
// ----------------------------------------------------------------------------
{
( void )file;
return -1;
}
/*!
* \brief These function returns information about a file, in the buffer
* pointed to by stat
* \note currently there is only support for stdin/out/err function. If any other devices
* have to be integrated as well, one should implement an abstraction layer
* which delegates the calls directly to the required device or ressource.
* An example can be seen in altera board support packages with the "dev" struct
*/
// ----------------------------------------------------------------------------
int _fstat( int file, struct stat* st )
// ----------------------------------------------------------------------------
{
st->st_dev = file;
st->st_size = 0;
st->st_blocks = 0;
if ( file >= 1 && file <= 3 )
{
st->st_mode = S_IFCHR;
return 0;
}
else
{
st->st_mode = S_IFREG;
return -1;
}
}
/*!
* \brief checks wether a descriptor 'file' is a TTY device or not
* \note currently there is only support for stdin/out/err function. If any other devices
* have to be integrated as well, one should implement an abstraction layer
* which delegates the calls directly to the required device or ressource.
* An example can be seen in altera board support packages with the "dev" struct
*/
// ----------------------------------------------------------------------------
int _isatty( int file )
// ----------------------------------------------------------------------------
{
// is stdin, stdout or stderror
if ( file >= 0 && file <= 2 )
{
return file;
}
return 0;
}
// ----------------------------------------------------------------------------
int _lseek( int file, int ptr, int dir )
// ----------------------------------------------------------------------------
{
( void )file;
( void )ptr;
( void )dir;
return 0;
}
// ----------------------------------------------------------------------------
int _open( char* path, int flags, ... )
// ----------------------------------------------------------------------------
{
( void )path;
( void )flags;
/* Pretend like we always fail */
return -1;
}
// ----------------------------------------------------------------------------
int _wait( int* status )
// ----------------------------------------------------------------------------
{
( void )status;
if ( _impure_ptr != 0 )
{
_impure_ptr->_errno = ECHILD;
}
errno = ECHILD;
return -1;
}
// ----------------------------------------------------------------------------
int _unlink( char* name )
// ----------------------------------------------------------------------------
{
( void )name;
if ( _impure_ptr != 0 )
{
_impure_ptr->_errno = ENOENT;
}
errno = ENOENT;
return -1;
}
// ----------------------------------------------------------------------------
int _times( struct tms* buf )
// ----------------------------------------------------------------------------
{
buf->tms_utime = buf->tms_cutime = 0; // we have no user space!
buf->tms_stime = buf->tms_cstime = __stdlib_get_system_clock_ticks( ); // everything runs in one process!
return 0;
}
// ----------------------------------------------------------------------------
int _stat( char* file, struct stat* st )
// ----------------------------------------------------------------------------
{
( void )file;
( void )st;
st->st_mode = S_IFCHR;
return 0;
}
// ----------------------------------------------------------------------------
int _link( char* old, char* new )
// ----------------------------------------------------------------------------
{
( void )old;
( void )new;
if ( _impure_ptr != 0 )
{
_impure_ptr->_errno = EMLINK;
}
errno = EMLINK;
return -1;
}
// ----------------------------------------------------------------------------
int _fork( void )
// ----------------------------------------------------------------------------
{
if ( _impure_ptr != 0 )
{
_impure_ptr->_errno = EAGAIN;
}
errno = EAGAIN;
return -1;
}
// ----------------------------------------------------------------------------
int _execve( char* name, char** argv, char** env )
// ----------------------------------------------------------------------------
{
( void )env;
( void )name;
( void )argv;
if ( _impure_ptr != 0 )
{
_impure_ptr->_errno = ENOMEM;
}
errno = ENOMEM;
return -1;
}
// ================================================================================================
// External routines required by newlib's malloc (sbrk/_sbrk, __malloc_lock/unlock)
// ================================================================================================
#if !defined(INC_FREERTOS_H)
// ----------------------------------------------------------------------------
caddr_t _sbrk( int incr )
// ----------------------------------------------------------------------------
{
register char* stack_ptr asm( "sp" );
extern char end asm( "end" );
static char* heap_end;
char* prev_heap_end;
if ( heap_end == 0 )
{
heap_end = &end;
}
prev_heap_end = heap_end;
if ( heap_end + incr > stack_ptr )
{
// write(1, "Heap and stack collision\n", 25);
// abort();
if ( _impure_ptr != 0 )
{
_impure_ptr->_errno = ENOMEM;
}
errno = ENOMEM;
return ( caddr_t ) -1;
}
heap_end += incr;
return ( caddr_t ) prev_heap_end;
}
#else
static int heapBytesRemaining;
static unsigned int stickyHeapBytesRemaining;
uint32_t TotalHeapSize;
// ----------------------------------------------------------------------------
static UBaseType_t malLock_uxSavedInterruptStatus;
// ----------------------------------------------------------------------------
void* _sbrk_r( struct _reent* pReent, int incr )
// ----------------------------------------------------------------------------
{
( void )malLock_uxSavedInterruptStatus;
( void )pReent;
( void )incr;
register char* stack_ptr asm( "sp" );
// make sure to calculate the correct heap size and bytes remaining at the first call!
if( TotalHeapSize == 0 )
{
TotalHeapSize = heapBytesRemaining = stickyHeapBytesRemaining
= ( int )( ( &__HeapLimit ) - ( &__HeapBase ) )
#ifdef configISR_STACK_SIZE_WORDS
- ( configISR_STACK_SIZE_WORDS * 4 )
#endif
;
};
static char* currentHeapEnd = &__HeapBase;
char* limit = ( xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED ) ?
stack_ptr : // Before scheduler is started, limit is stack pointer (risky!)
&__HeapLimit
#ifdef configISR_STACK_SIZE_WORDS
- ( configISR_STACK_SIZE_WORDS * 4 )
#endif
; // Once running, OK to reuse all remaining RAM except ISR stack (MSP) stack
DRN_ENTER_CRITICAL_SECTION( malLock_uxSavedInterruptStatus );
if ( currentHeapEnd + incr > limit )
{
// Ooops, no more memory available...
#if( configUSE_MALLOC_FAILED_HOOK == 1 )
{
extern void vApplicationMallocFailedHook( void );
DRN_EXIT_CRITICAL_SECTION( malLock_uxSavedInterruptStatus );
vApplicationMallocFailedHook();
}
#elif defined(configHARD_STOP_ON_MALLOC_FAILURE)
// If you want to alert debugger or halt...
// WARNING: brkpt instruction may prevent watchdog operation...
while( 1 )
{
__asm( "bkpt #0" );
}; // Stop in GUI as if at a breakpoint (if debugging, otherwise loop forever)
#else
// Default, if you prefer to believe your application will gracefully trap out-of-memory...
pReent->_errno = ENOMEM; // newlib's thread-specific errno
DRN_EXIT_CRITICAL_SECTION( malLock_uxSavedInterruptStatus );
#endif
return ( char* ) -1; // the malloc-family routine that called sbrk will return 0
}
char* previousHeapEnd = currentHeapEnd;
currentHeapEnd += incr;
heapBytesRemaining -= incr;
// implement the statistical feature to provide the minimum free heap size feature
// of FreeRTOS statistics
if ( stickyHeapBytesRemaining > xPortGetFreeHeapSize() )
{
stickyHeapBytesRemaining = xPortGetFreeHeapSize();
}
DRN_EXIT_CRITICAL_SECTION( malLock_uxSavedInterruptStatus );
return ( char* ) previousHeapEnd;
}
/*! \brief non-reentrant sbrk uses is actually reentrant by using current context
* because the current _reent structure is pointed to by global _impure_ptr
*/
// ----------------------------------------------------------------------------
void* sbrk( ptrdiff_t __incr )
// ----------------------------------------------------------------------------
{
return _sbrk_r( _impure_ptr, __incr );
}
//! _sbrk is a synonym for sbrk.
// ----------------------------------------------------------------------------
char* _sbrk( int incr )
// ----------------------------------------------------------------------------
{
return sbrk( incr );
}
// ----------------------------------------------------------------------------
__attribute__( ( weak ) ) void __malloc_lock( struct _reent* r )
// ----------------------------------------------------------------------------
{
( void )r;
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_MALLOC)
if ( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
{
xSemaphoreTakeRecursive( mallocSemaphore, -1 );
}
#endif
DRN_ENTER_CRITICAL_SECTION( malLock_uxSavedInterruptStatus );
}
// ----------------------------------------------------------------------------
__attribute__( ( weak ) ) void __malloc_unlock( struct _reent* r )
// ----------------------------------------------------------------------------
{
( void )r;
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_MALLOC)
if ( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
{
xSemaphoreGiveRecursive( mallocSemaphore );
}
#endif
DRN_EXIT_CRITICAL_SECTION( malLock_uxSavedInterruptStatus );
}
// ----------------------------------------------------------------------------
__attribute__( ( weak ) ) void __env_lock( void )
// ----------------------------------------------------------------------------
{
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_ENV)
if ( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
{
xSemaphoreTakeRecursive( envSemaphore, -1 );
}
#endif
DRN_ENTER_CRITICAL_SECTION( malLock_uxSavedInterruptStatus );
}
// ----------------------------------------------------------------------------
__attribute__( ( weak ) ) void __env_unlock( void )
// ----------------------------------------------------------------------------
{
#if defined(INC_FREERTOS_H) && defined(MV_SYSCALL_USE_EXCLUSIVE_LOCK_FOR_ENV)
if ( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
{
xSemaphoreGiveRecursive( envSemaphore );
}
#endif
DRN_EXIT_CRITICAL_SECTION( malLock_uxSavedInterruptStatus );
}
// ----------------------------------------------------------------------------
void* pvPortMalloc( size_t xSize )
// ----------------------------------------------------------------------------
{
void* p = malloc( xSize );
return p;
}
// ----------------------------------------------------------------------------
void vPortFree( void* pv )
// ----------------------------------------------------------------------------
{
free( pv );
}
// ----------------------------------------------------------------------------
size_t xPortGetFreeHeapSize( void )
// ----------------------------------------------------------------------------
{
static int lockGuard = 0;
if ( lockGuard != 0 ) return stickyHeapBytesRemaining;
lockGuard = 1;
struct mallinfo mi = mallinfo();
size_t result = mi.fordblks + heapBytesRemaining;
lockGuard = 0;
return result;
}
// ----------------------------------------------------------------------------
size_t xPortGetMinimumEverFreeHeapSize ( void )
// ----------------------------------------------------------------------------
{
return stickyHeapBytesRemaining;
}
//! No implementation needed, but stub provided in case application already calls vPortInitialiseBlocks
// ----------------------------------------------------------------------------
void vPortInitialiseBlocks( void )
// ----------------------------------------------------------------------------
{
return;
}
#endif
@@ -0,0 +1,333 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32h7xx_hal_msp.c
* @brief This file provides code for the MSP Initialization
* and de-Initialization codes.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN Define */
/* USER CODE END Define */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN Macro */
/* USER CODE END Macro */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* External functions --------------------------------------------------------*/
/* USER CODE BEGIN ExternalFunctions */
/* USER CODE END ExternalFunctions */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim);
/**
* Initializes the Global MSP.
*/
void HAL_MspInit(void)
{
/* USER CODE BEGIN MspInit 0 */
/* USER CODE END MspInit 0 */
__HAL_RCC_SYSCFG_CLK_ENABLE();
/* System interrupt init*/
/* Peripheral interrupt init */
/* CM4_SEV_IRQn interrupt configuration */
HAL_NVIC_SetPriority(CM4_SEV_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(CM4_SEV_IRQn);
/* HSEM1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(HSEM1_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(HSEM1_IRQn);
/* USER CODE BEGIN MspInit 1 */
/* USER CODE END MspInit 1 */
}
/**
* @brief SPI MSP Initialization
* This function configures the hardware resources used in this example
* @param hspi: SPI handle pointer
* @retval None
*/
void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
if(hspi->Instance==SPI1)
{
/* USER CODE BEGIN SPI1_MspInit 0 */
/* USER CODE END SPI1_MspInit 0 */
/** Initializes the peripherals clock
*/
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_SPI1;
PeriphClkInitStruct.Spi123ClockSelection = RCC_SPI123CLKSOURCE_PLL;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
{
Error_Handler();
}
/* Peripheral clock enable */
__HAL_RCC_SPI1_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/**SPI1 GPIO Configuration
PA5 ------> SPI1_SCK
PA6 ------> SPI1_MISO
PB5 ------> SPI1_MOSI
*/
GPIO_InitStruct.Pin = STEP_SPI_SCK_Pin|STEP_SPI_MISO_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF5_SPI1;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = STEP_SPI_MOSI_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF5_SPI1;
HAL_GPIO_Init(STEP_SPI_MOSI_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN SPI1_MspInit 1 */
/* USER CODE END SPI1_MspInit 1 */
}
}
/**
* @brief SPI MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param hspi: SPI handle pointer
* @retval None
*/
void HAL_SPI_MspDeInit(SPI_HandleTypeDef* hspi)
{
if(hspi->Instance==SPI1)
{
/* USER CODE BEGIN SPI1_MspDeInit 0 */
/* USER CODE END SPI1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_SPI1_CLK_DISABLE();
/**SPI1 GPIO Configuration
PA5 ------> SPI1_SCK
PA6 ------> SPI1_MISO
PB5 ------> SPI1_MOSI
*/
HAL_GPIO_DeInit(GPIOA, STEP_SPI_SCK_Pin|STEP_SPI_MISO_Pin);
HAL_GPIO_DeInit(STEP_SPI_MOSI_GPIO_Port, STEP_SPI_MOSI_Pin);
/* USER CODE BEGIN SPI1_MspDeInit 1 */
/* USER CODE END SPI1_MspDeInit 1 */
}
}
/**
* @brief TIM_Base MSP Initialization
* This function configures the hardware resources used in this example
* @param htim_base: TIM_Base handle pointer
* @retval None
*/
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* htim_base)
{
if(htim_base->Instance==TIM2)
{
/* USER CODE BEGIN TIM2_MspInit 0 */
/* USER CODE END TIM2_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_TIM2_CLK_ENABLE();
/* USER CODE BEGIN TIM2_MspInit 1 */
/* USER CODE END TIM2_MspInit 1 */
}
}
void HAL_TIM_MspPostInit(TIM_HandleTypeDef* htim)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(htim->Instance==TIM2)
{
/* USER CODE BEGIN TIM2_MspPostInit 0 */
/* USER CODE END TIM2_MspPostInit 0 */
__HAL_RCC_GPIOB_CLK_ENABLE();
/**TIM2 GPIO Configuration
PB10 ------> TIM2_CH3
PB11 ------> TIM2_CH4
*/
GPIO_InitStruct.Pin = SPINDLE_PWM_L_Pin|SPINDLE_PWM_R_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF1_TIM2;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* USER CODE BEGIN TIM2_MspPostInit 1 */
/* USER CODE END TIM2_MspPostInit 1 */
}
}
/**
* @brief TIM_Base MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param htim_base: TIM_Base handle pointer
* @retval None
*/
void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* htim_base)
{
if(htim_base->Instance==TIM2)
{
/* USER CODE BEGIN TIM2_MspDeInit 0 */
/* USER CODE END TIM2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_TIM2_CLK_DISABLE();
/* USER CODE BEGIN TIM2_MspDeInit 1 */
/* USER CODE END TIM2_MspDeInit 1 */
}
}
/**
* @brief UART MSP Initialization
* This function configures the hardware resources used in this example
* @param huart: UART handle pointer
* @retval None
*/
void HAL_UART_MspInit(UART_HandleTypeDef* huart)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
if(huart->Instance==USART3)
{
/* USER CODE BEGIN USART3_MspInit 0 */
/* USER CODE END USART3_MspInit 0 */
/** Initializes the peripherals clock
*/
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USART3;
PeriphClkInitStruct.Usart234578ClockSelection = RCC_USART234578CLKSOURCE_D2PCLK1;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
{
Error_Handler();
}
/* Peripheral clock enable */
__HAL_RCC_USART3_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
/**USART3 GPIO Configuration
PD8 ------> USART3_TX
PD9 ------> USART3_RX
*/
GPIO_InitStruct.Pin = DEBUG_UART_TX_Pin|DEBUG_UART_RX_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF7_USART3;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/* USART3 interrupt Init */
HAL_NVIC_SetPriority(USART3_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(USART3_IRQn);
/* USER CODE BEGIN USART3_MspInit 1 */
/* USER CODE END USART3_MspInit 1 */
}
}
/**
* @brief UART MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param huart: UART handle pointer
* @retval None
*/
void HAL_UART_MspDeInit(UART_HandleTypeDef* huart)
{
if(huart->Instance==USART3)
{
/* USER CODE BEGIN USART3_MspDeInit 0 */
/* USER CODE END USART3_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_USART3_CLK_DISABLE();
/**USART3 GPIO Configuration
PD8 ------> USART3_TX
PD9 ------> USART3_RX
*/
HAL_GPIO_DeInit(GPIOD, DEBUG_UART_TX_Pin|DEBUG_UART_RX_Pin);
/* USART3 interrupt DeInit */
HAL_NVIC_DisableIRQ(USART3_IRQn);
/* USER CODE BEGIN USART3_MspDeInit 1 */
/* USER CODE END USART3_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
@@ -0,0 +1,256 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32h7xx_it.c
* @brief Interrupt Service Routines.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32h7xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/* External variables --------------------------------------------------------*/
extern UART_HandleTypeDef huart3;
/* USER CODE BEGIN EV */
/* USER CODE END EV */
/******************************************************************************/
/* Cortex Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles Non maskable interrupt.
*/
void NMI_Handler(void)
{
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */
while (1)
{
}
/* USER CODE END NonMaskableInt_IRQn 1 */
}
/**
* @brief This function handles Hard fault interrupt.
*/
void HardFault_Handler(void)
{
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_HardFault_IRQn 0 */
/* USER CODE END W1_HardFault_IRQn 0 */
}
}
/**
* @brief This function handles Memory management fault.
*/
void MemManage_Handler(void)
{
/* USER CODE BEGIN MemoryManagement_IRQn 0 */
/* USER CODE END MemoryManagement_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
/* USER CODE END W1_MemoryManagement_IRQn 0 */
}
}
/**
* @brief This function handles Pre-fetch fault, memory access fault.
*/
void BusFault_Handler(void)
{
/* USER CODE BEGIN BusFault_IRQn 0 */
/* USER CODE END BusFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_BusFault_IRQn 0 */
/* USER CODE END W1_BusFault_IRQn 0 */
}
}
/**
* @brief This function handles Undefined instruction or illegal state.
*/
void UsageFault_Handler(void)
{
/* USER CODE BEGIN UsageFault_IRQn 0 */
/* USER CODE END UsageFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_UsageFault_IRQn 0 */
}
}
#if 0
/* USER CODE END W1_UsageFault_IRQn 0 */
}
}
/**
* @brief This function handles System service call via SWI instruction.
*/
void SVC_Handler(void)
{
/* USER CODE BEGIN SVCall_IRQn 0 */
/* USER CODE END SVCall_IRQn 0 */
/* USER CODE BEGIN SVCall_IRQn 1 */
/* USER CODE END SVCall_IRQn 1 */
}
/**
* @brief This function handles Debug monitor.
*/
void DebugMon_Handler(void)
{
/* USER CODE BEGIN DebugMonitor_IRQn 0 */
#endif
void DebugMon_Handler(void)
{
/* USER CODE END DebugMonitor_IRQn 0 */
/* USER CODE BEGIN DebugMonitor_IRQn 1 */
}
#if 0
/* USER CODE END DebugMonitor_IRQn 0 */
/* USER CODE BEGIN DebugMonitor_IRQn 1 */
/* USER CODE END DebugMonitor_IRQn 1 */
}
/**
* @brief This function handles Pendable request for system service.
*/
void PendSV_Handler(void)
{
/* USER CODE BEGIN PendSV_IRQn 0 */
/* USER CODE END PendSV_IRQn 0 */
/* USER CODE BEGIN PendSV_IRQn 1 */
/* USER CODE END PendSV_IRQn 1 */
}
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
/* USER CODE BEGIN SysTick_IRQn 0 */
#endif
void SysTick_Handler(void)
{
extern void xPortSysTickHandler( void );
/* USER CODE END SysTick_IRQn 0 */
HAL_IncTick();
/* USER CODE BEGIN SysTick_IRQn 1 */
xPortSysTickHandler();
/* USER CODE END SysTick_IRQn 1 */
}
/******************************************************************************/
/* STM32H7xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32h7xx.s). */
/******************************************************************************/
/**
* @brief This function handles USART3 global interrupt.
*/
void USART3_IRQHandler(void)
{
/* USER CODE BEGIN USART3_IRQn 0 */
/* USER CODE END USART3_IRQn 0 */
HAL_UART_IRQHandler(&huart3);
/* USER CODE BEGIN USART3_IRQn 1 */
/* USER CODE END USART3_IRQn 1 */
}
/**
* @brief This function handles CM4 send event interrupt for CM7.
*/
void CM4_SEV_IRQHandler(void)
{
/* USER CODE BEGIN CM4_SEV_IRQn 0 */
/* USER CODE END CM4_SEV_IRQn 0 */
/* USER CODE BEGIN CM4_SEV_IRQn 1 */
/* USER CODE END CM4_SEV_IRQn 1 */
}
/**
* @brief This function handles HSEM1 global interrupt.
*/
void HSEM1_IRQHandler(void)
{
/* USER CODE BEGIN HSEM1_IRQn 0 */
/* USER CODE END HSEM1_IRQn 0 */
HAL_HSEM_IRQHandler();
/* USER CODE BEGIN HSEM1_IRQn 1 */
/* USER CODE END HSEM1_IRQn 1 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
@@ -0,0 +1,176 @@
/**
******************************************************************************
* @file syscalls.c
* @author Auto-generated by STM32CubeIDE
* @brief STM32CubeIDE Minimal System calls file
*
* For more information about which c-functions
* need which of these lowlevel functions
* please consult the Newlib libc-manual
******************************************************************************
* @attention
*
* Copyright (c) 2020-2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes */
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <sys/times.h>
/* Variables */
extern int __io_putchar(int ch) __attribute__((weak));
extern int __io_getchar(void) __attribute__((weak));
char *__env[1] = { 0 };
char **environ = __env;
/* Functions */
void initialise_monitor_handles()
{
}
int _getpid(void)
{
return 1;
}
int _kill(int pid, int sig)
{
(void)pid;
(void)sig;
errno = EINVAL;
return -1;
}
void _exit (int status)
{
_kill(status, -1);
while (1) {} /* Make sure we hang here */
}
__attribute__((weak)) int _read(int file, char *ptr, int len)
{
(void)file;
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
*ptr++ = __io_getchar();
}
return len;
}
__attribute__((weak)) int _write(int file, char *ptr, int len)
{
(void)file;
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
__io_putchar(*ptr++);
}
return len;
}
int _close(int file)
{
(void)file;
return -1;
}
int _fstat(int file, struct stat *st)
{
(void)file;
st->st_mode = S_IFCHR;
return 0;
}
int _isatty(int file)
{
(void)file;
return 1;
}
int _lseek(int file, int ptr, int dir)
{
(void)file;
(void)ptr;
(void)dir;
return 0;
}
int _open(char *path, int flags, ...)
{
(void)path;
(void)flags;
/* Pretend like we always fail */
return -1;
}
int _wait(int *status)
{
(void)status;
errno = ECHILD;
return -1;
}
int _unlink(char *name)
{
(void)name;
errno = ENOENT;
return -1;
}
int _times(struct tms *buf)
{
(void)buf;
return -1;
}
int _stat(char *file, struct stat *st)
{
(void)file;
st->st_mode = S_IFCHR;
return 0;
}
int _link(char *old, char *new)
{
(void)old;
(void)new;
errno = EMLINK;
return -1;
}
int _fork(void)
{
errno = EAGAIN;
return -1;
}
int _execve(char *name, char **argv, char **env)
{
(void)name;
(void)argv;
(void)env;
errno = ENOMEM;
return -1;
}
@@ -0,0 +1,79 @@
/**
******************************************************************************
* @file sysmem.c
* @author Generated by STM32CubeIDE
* @brief STM32CubeIDE System Memory calls file
*
* For more information about which C functions
* need which of these lowlevel functions
* please consult the newlib libc manual
******************************************************************************
* @attention
*
* Copyright (c) 2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes */
#include <errno.h>
#include <stdint.h>
/**
* Pointer to the current high watermark of the heap usage
*/
static uint8_t *__sbrk_heap_end = NULL;
/**
* @brief _sbrk() allocates memory to the newlib heap and is used by malloc
* and others from the C library
*
* @verbatim
* ############################################################################
* # .data # .bss # newlib heap # MSP stack #
* # # # # Reserved by _Min_Stack_Size #
* ############################################################################
* ^-- RAM start ^-- _end _estack, RAM end --^
* @endverbatim
*
* This implementation starts allocating at the '_end' linker symbol
* The '_Min_Stack_Size' linker symbol reserves a memory for the MSP stack
* The implementation considers '_estack' linker symbol to be RAM end
* NOTE: If the MSP stack, at any point during execution, grows larger than the
* reserved size, please increase the '_Min_Stack_Size'.
*
* @param incr Memory size
* @return Pointer to allocated memory
*/
void *_sbrk(ptrdiff_t incr)
{
extern uint8_t _end; /* Symbol defined in the linker script */
extern uint8_t _estack; /* Symbol defined in the linker script */
extern uint32_t _Min_Stack_Size; /* Symbol defined in the linker script */
const uint32_t stack_limit = (uint32_t)&_estack - (uint32_t)&_Min_Stack_Size;
const uint8_t *max_heap = (uint8_t *)stack_limit;
uint8_t *prev_heap_end;
/* Initialize heap end at first call */
if (NULL == __sbrk_heap_end)
{
__sbrk_heap_end = &_end;
}
/* Protect heap from growing into the reserved MSP stack */
if (__sbrk_heap_end + incr > max_heap)
{
errno = ENOMEM;
return (void *)-1;
}
prev_heap_end = __sbrk_heap_end;
__sbrk_heap_end += incr;
return (void *)prev_heap_end;
}