#define ledPort 33
#define maxBufferLen 80
char *buffer;
static volatile bool newMessage = 0;
static volatile bool allocated = 0;
unsigned short bufferIndex = 0;
TaskHandle_t listenHandle = NULL;
TaskHandle_t sendHandle = NULL;
TaskHandle_t blinkHandle = NULL;
void listenToSerialMonitor(void*) {
while (1) {
if (!allocated) {
buffer = (char *)calloc(maxBufferLen, sizeof(char));
if (buffer == NULL) {
Serial.println("Memory allocation failed!");
} else {
allocated = 1;
}
}
while (Serial.available()) {
char c = Serial.read();
if (bufferIndex < maxBufferLen - 1 && c != '\n') {
buffer[bufferIndex++] = c;
} else {
buffer[bufferIndex] = '\0';
bufferIndex = 0;
newMessage = 1;
}
}
}
}
void sendoToSerialMonitor(void*) {
while (1) {
if (!newMessage) continue;
Serial.print("Message: ");
for (int i = 0;; i++) {
if (buffer[i] == '\0') break;
Serial.print(buffer[i]);
}
Serial.println();
newMessage = 0;
free(buffer);
allocated = 0;
}
}
void blinkLed(void*) {
while (1) {
if (newMessage) {
digitalWrite(ledPort, HIGH);
vTaskDelay(500 / portTICK_PERIOD_MS);
digitalWrite(ledPort, LOW);
}
}
}
void setup() {
// put your setup code here, to run once:
pinMode(ledPort, OUTPUT);
Serial.begin(115200);
Serial.println("Hello, ESP32!");
xTaskCreatePinnedToCore(listenToSerialMonitor,
"Listen to Serial Monitor",
1024,
NULL,
1,
&listenHandle,
1);
xTaskCreatePinnedToCore(sendoToSerialMonitor,
"Send to Serial Monitor",
1024,
NULL,
1,
&sendHandle,
2);
xTaskCreatePinnedToCore(blinkLed,
"Blink Led",
1024,
NULL,
1,
&blinkHandle,
0);
}
void loop() {
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
}