30-12-2017, 19:55
Witam, próbuję zrozumieć i nauczyć się zasad przechwytywania łańcuchów znaków przychodzących po UART i wykorzystywania ich dalej np. do sterowania Arduino za pomocą SMS, itp. Udaje mi się to już jako tako przy wykorzystaniu klasy String ale spotkałem się z opiniami, że lepiej jest działać na tablicach za pomocą klasy Serial. Np na forum.arduino.cc znalazłem taką oto instrukcję pobierania i przekazywania dalej łańcucha znaków (poniżej skopiowałem kod ze strony http://forum.arduino.cc/index.php?topic=396450.0). Zastanawiam się czy zaproponowany sposób to jest typowe rozwiązanie i czy nie można tego rozwiązać jakoś prościej?
Kod:
// Example 2 - Receive with an end-marker
const byte numChars = 32;
char receivedChars[numChars]; // an array to store the received data
boolean newData = false;
void setup() {
Serial.begin(9600);
Serial.println("<Arduino is ready>");
}
void loop() {
recvWithEndMarker();
showNewData();
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '\n';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.print("This just in ... ");
Serial.println(receivedChars);
newData = false;
}
}