Read string from Serial port is not working
digidhamu opened this issue · 4 comments
I just implemented the ChNil for my project and everything works great without any issue. However, I found that Serial string read is not working and I can only fetch first char of string.
Below code is for your reference and ran on Uno. Please note that I have even tried with native Serial class but same result.
Could you please help me what is wrong.
#include "ChNil.h"
ChNilSerialClass ChNilSerial;
#define Serial ChNilSerial
String recvString = "";
void setup() {
Serial.begin(9600);
chFillStacks();
chBegin();
}
void loop() {
}
THD_WORKING_AREA(waThread1, 64);
THD_FUNCTION(Thread1, arg) {
(void)arg;
while (TRUE) {
while (Serial.available()) {
char c = Serial.read();
recvString += c;
}
recvString.trim();
Serial.print("Received String: ");
Serial.println(recvString);
recvString = "";
chThdSleep(1000);
}
}
THD_TABLE_BEGIN
THD_TABLE_ENTRY(waThread1, NULL, Thread1, NULL)
THD_TABLE_END
The Arduino core can't cope with use of dynamic memory in threads. Strings use dynamic memory and malloc, the memory allocator, gets confused by the separate stack for each thread.
A note about dynamic memory in embedded systems. Most coding standards for critical systems in medicine and transportation forbid the use of dynamic objects like the Arduino String. You can only allocate memory from a pool at startup, not during the critical operation phase.
@greiman Thanks for your quick response.
Do we have any work around for this or we need to live with this?
I occasionally define a String like class with a static fixed length buffer in my apps but I have not generalized this for open source sharing.
It is not practical to patch Arduino malloc or the Arduino String class