I am a bit of a noob as far as Arduino and C(++) goes. but I am having to manually clear a char buf[] even when reinitializing it in a new scope? I would like to understand why and potentially remove my reset_buf() function in my code.
the output WITHOUT reset_buf():
HELLO SDCARD
SD OK!
LOOP
Open test.asc
INP Hello Arduino
CMD: INP
SKP RETURNArduino
CMD: SKP
SLP 1000RNArduino
CMD: SLP
INP Bye Arduinono
CMD: INP
SKP RETURNduinono
CMD: SKP
and then the output WITH reset_buf():
HELLO SDCARD
SD OK!
LOOP
Open test.asc
INP Hello Arduino
CMD: INP
SKP RETURN
CMD: SKP
SLP 1000
CMD: SLP
INP Bye Arduino
CMD: INP
SKP RETURN
CMD: SKP
Hope someone can help and explain.
Here is my code, i have to reset_buf in the loop():
#include <SPI.h>
#include <SD.h>
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
while(!Serial);
Serial.println("HELLO SDCARD");
if (!SD.begin(10)) {
Serial.println("SD ERROR");
while (1);
}
Serial.println("SD OK!");
}
// Read to \n or max 1024 bytes
void readLine(char buf[], File f) {
int rl_len = 0;
while (f.available() && rl_len < 1024) {
char c = f.read();
if (c == '\n') break;
buf[rl_len] = c;
rl_len++;
}
}
void reset_buf(char buf[]) {
for (int i = 0; i < 1024; i++) {
buf[i] = (char)0;
}
}
void processLine(char line[]) {
Serial.println(line);
char cmd[3];
for (int li = 0; li < 3; li++) {
cmd[li] = line[li];
}
Serial.print("CMD: ");
Serial.println(cmd);
}
void loop() {
Serial.println("LOOP");
File script = SD.open("test.asc");
Serial.println("Open test.asc");
while(script.available()) {
char buf[1024];
readLine(buf, script);
processLine(buf);
reset_buf(buf);
}
script.close();
SD.end();
while(1); // freeze device
}