Board: Nano 33 BLE Sense Rev2
I want to sort data as it is in the string 'b', but after sorting, the data is sorted in ascending order. What can I do to correct it? Also if I want to read only the last string of a very large file, is it better to just store one string in a file and after reading it, delete and recreate the file to write new data OR store data in same file and read the last string? I want to make the code run faster.
Code:
#include <SD.h>
const int chipSelect = 2; // SD card chip select pin
const int stringLength = 17; // maximum length of the string
char inputString[stringLength]; // a string to hold incoming data from SD card
bool stringComplete = false; // whether the string is complete or not
String a = "1,2,3,4,5,6,7,8,9,0,123,3,5,6,7,8,9,0,12,4,67,89";
char b[] = "3,2,101300,28800"; //17 max, min 12 , Packet,ref,count,state
File dataFile;
void setup() {
Serial.begin(9600); // initialize serial communication
while (!Serial) {
; // wait for serial port to connect
}
if (!SD.begin(chipSelect)) { // initialize SD card
Serial.println("Card failed, or not present");
while (1)
;
}
SD.remove("data.txt");
dataFile = SD.open("data.txt", FILE_WRITE);
dataFile.println(b);
dataFile.close();
Serial.println(strlen(b));
// open the file for reading:
dataFile = SD.open("data.txt", FILE_READ);
if (dataFile) {
while (dataFile.available()) {
char c = dataFile.read();
if (c == '\n') { // the end of a string
inputString[dataFile.position() - 1] = '\0'; // add null terminator to the string
stringComplete = true; // the string is complete
} else if (dataFile.position() >= stringLength) { // the string is too long
inputString[dataFile.position() - 1] = '\0'; // add null terminator to the string
stringComplete = true; // the string is complete
dataFile.seek(dataFile.position() + 1); // skip the rest of the line
} else {
inputString[dataFile.position() - 1] = c; // add a character to the string
}
}
dataFile.close();
} else {
Serial.println("Unable to open file");
}
if (stringComplete) {
// sort the data
int dataArray[4];
int i = 0;
char* ptr = strtok(inputString, ",");
while (ptr != NULL && i < 4) {
dataArray[i] = atoi(ptr); // convert string to integer
ptr = strtok(NULL, ",");
i++;
}
for (int j = 0; j < i - 1; j++) {
for (int k = j + 1; k < i; k++) {
if (dataArray[j] > dataArray[k]) {
int temp = dataArray[j];
dataArray[j] = dataArray[k];
dataArray[k] = temp;
}
}
}
// print the sorted data
Serial.print("Sorted data: ");
for (int j = 0; j < i; j++) {
Serial.print(dataArray[j]);
if (j < i - 1) {
Serial.print(", ");
}
}
Serial.println();
} else {
Serial.println("No complete string found");
}
}
void loop() {
// do nothing
}