Hi
I have tried the solution for shawn hymel freertos course on youtube the 4th memory allocation problem. where one task should be listening to the serial input and another task should print what has been received from the serial input. I have done the code as after receiving the serial input will create a dynamic memory using malloc and the serial input is stored and the pointer of the malloc call is globally declared so that it can be accessed by another task. When I tried to print from another task there is no data. I have checked after assigning the data to the pointer. below is the code
// Use only core 1 for demo purposes
#if CONFIG_FREERTOS_UNICORE
static const BaseType_t app_cpu = 0;
#else
static const BaseType_t app_cpu = 1;
#endif
int flag=0;
static char *ptr=NULL;
int ind=0; //for index
// Task: Perform some mundane task
void testTask(void *parameter) {
unsigned char bytes='0';
while (1) {
if(Serial.available())
{
ptr = (char*)pvPortMalloc(20 * sizeof(char));
// One way to prevent heap overflow is to check the malloc output
if (ptr == NULL) {
Serial.println("Not enough heap.");
vPortFree(NULL);
}
else {
bytes=Serial.read();
if(bytes=='\n')
{
Serial.println("Turning on flag");
//*(ptr+(ind))='\0';
/*for(int i=0;i<ind;i++)
{
Serial.println(*(ptr+i));
}*/
flag=1;
Serial.println("After turning flag");
vTaskDelay(3000 / portTICK_PERIOD_MS);
}
else{
//*(ptr+ind)=bytes;
ptr[ind]=bytes;
//Serial.println(ptr[ind]);
Serial.println(*(ptr+ind));
ind++;
}
}
}
// Wait for a while
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
void printTask(void *parameter) {
int i=0;
while(1){
if(flag==1)
{
Serial.println("In receiving task");
Serial.println(ind);
for(int i=0;i<ind;i++)
{
Serial.println(*(ptr+i));
}
flag=0;
ind=0;
vTaskDelay(100 / portTICK_PERIOD_MS);
vPortFree(ptr);
ptr=NULL;
}
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
void setup() {
// Configure Serial
Serial.begin(115200);
// Wait a moment to start (so we don't miss Serial output)
vTaskDelay(1000 / portTICK_PERIOD_MS);
Serial.println();
Serial.println("---FreeRTOS Memory Demo---");
// Start the only other task
xTaskCreatePinnedToCore(testTask,
"Test Task",
1500,
NULL,
1,
NULL,
app_cpu);
xTaskCreatePinnedToCore(printTask,
"print Task",
1500,
NULL,
1,
NULL,
app_cpu);
// Delete "setup and loop" task
vTaskDelete(NULL);
}
void loop() {
// Execution should never get here
}