cast from void pointer to pointer to struct results in hardware fault in FreeRtos Thread in thread argument

neicdech wrote on Thursday, June 14, 2018:

I am writing a simple blinking LED program in MCUXpresso with ksdk 2.4 and Amazon Freertos. I intended to create two instances of the same thread definition by passing a void pointer to my struct which contains the GPIO type and pin number to the thread and later typecast the void pointer to pointer to my structure. however, during debugging, i realised that the new pointer points to a completely different address from my struct data and it always causes a hardware fault. This is however a code which works very well in Kinetis Design studio. I will appreciate help in understanind this problem.


#include <stdio.h>
#include "board.h"
#include "peripherals.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "MK22F51212.h"
#include "fsl_debug_console.h"


typedef struct BLINKY_param {
	GPIO_Type* GPIO;
	uint8_t Pin_name;
} BLINKY_param_t;

enum PINS {
	PTD2  = 2,                  // LED_A
};

#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "timers.h"
#include "queue.h"

void air_blinky(void* blinky_parameters) ;
#define mask(x)             ( uint32_t )( 1U << (x) )

int main(void) {

	CLOCK_EnableClock(kCLOCK_PortD);
	PORT_SetPinMux(PORTD,PTD2,kPORT_MuxAsGpio);

	gpio_pin_config_t config = { kGPIO_DigitalOutput, 0 };
	GPIO_PinInit(GPIOD, PTD2, &config);

	BLINKY_param_t Board_A_blinky = {GPIOD,PTD2};

	if (xTaskCreate(air_blinky, "air_blinky_A", 50, &Board_A_blinky, 2,
	NULL) == errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY)
		exit(-1);

	vTaskStartScheduler();

	while (1) {
	}
	return 0;
}

void air_blinky(void* blinky_parameters) {

	  BLINKY_param_t* LED = (BLINKY_param_t*) blinky_parameters;

	TickType_t Lastwakeuptime = xTaskGetTickCount();
	uint8_t Flash_Time = 100;

	for (;;)
	{
		GPIO_PortToggle(LED->GPIO, mask(LED->Pin_name));   	       // on
		vTaskDelayUntil(&Lastwakeuptime,((Flash_Time * configTICK_RATE_HZ) / (float) 1000));
		GPIO_PortToggle(GPIOD, mask(PTD2));   	      // off
		vTaskDelayUntil(&Lastwakeuptime,((Flash_Time * configTICK_RATE_HZ) / (float) 1000));
		GPIO_PortToggle(GPIOD, mask(PTD2));   	       // on
		vTaskDelayUntil(&Lastwakeuptime,((Flash_Time * configTICK_RATE_HZ) / (float) 1000));
		GPIO_PortToggle(GPIOD, mask(PTD2));  	      // off

		vTaskDelayUntil(&Lastwakeuptime,((2000 * configTICK_RATE_HZ) / (float) 1000));
	}

}


rtel wrote on Thursday, June 14, 2018:

If your question is “the pointer to Board_A_blinky is corrupt inside the
task air_blinky” then that is because Board_A_blinky is defined on the
stack of main() - which no longer exists when the scheduler has been
started. Either make Board_A_blinky static so it is not on the stack,
or move the definition to be file scope.

neicdech wrote on Thursday, June 14, 2018:

yes, that actually the question. I tried your suggestion and it worked. thanks