// my solution to lesson 4
// Learned so far
// - writing task
// - task scheduling
// - memory managament
// Challenge
// Write 2 tasks.
// task 1 : get input from serial monitor
// after getting a enter , put it into heap memory
// signal to task2 that there is something on the heap
// task2 : read input from the heap if the task 1 signal that there is a message
// display it on the serial monitor
// free the memory
#if CONFIG_FREERTOS_UNICORE
static const BaseType_t app_cpu = 0 ;
#else
static const BaseType_t app_cpu = 1;
#endif
// Pins
static const int led_pin = 2;
bool volatile messageFlag = false;
char * message_ptr;
// Our task is to read in a message
void readMessageFromMonitor(void * parameter) {
char ch;
char buff[40];
int idx = 0;
memset(buff, 0, 20);
while (1) {
if (Serial.available() > 0) {
ch = Serial.read();
if (ch == '\n') {
if(idx != 0 )
{ // clear buffer
buff[idx] = '\0';
idx++;
// make room on the heap for the message
message_ptr = (char *) pvPortMalloc(idx * sizeof(char));
// Place the message on the heap
memcpy(message_ptr, buff, idx);
// set the flag
messageFlag = true;
idx = 0 ;
memset(buff, 0, 20);
}
else
{
/* Ignore the empty buffer. */
}
} else {
if (idx < 39) {
buff[idx] = ch;
idx++;
}
}
}
}
}
void displayMessage(void * parameter) {
while(1) {
if (messageFlag) {
Serial.print("Task2 reads :");
Serial.println(message_ptr);
vPortFree(message_ptr);
messageFlag = false ;
}}
}
void setup() {
pinMode(led_pin, OUTPUT);
Serial.begin(9600);
Serial.println("RW");
// Task to run forever
xTaskCreatePinnedToCore(
readMessageFromMonitor, // Function to be called
"Read Message", // name of the function
1024, // stack size
NULL, // parameter to pass to the function
1, // priority
NULL, // task handle
app_cpu
);
xTaskCreatePinnedToCore(
displayMessage, // Function to be called
"Display Message", // name of the function
1024, // stack size
NULL, // parameter to pass to the function
1, // priority
NULL, // task handle
app_cpu
);
vTaskDelete(NULL);
}
void loop() {
}