123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- #include <SPI.h>
- #include <SdFat.h>
- #define CS_PIN SS
- #define ROW_DIM 5
- #define COL_DIM 4
- SdFat SD;
- File file;
- size_t readField(File* file, char* str, size_t size, const char* delim) {
- char ch;
- size_t n = 0;
- while ((n + 1) < size && file->read(&ch, 1) == 1) {
-
- if (ch == '\r') {
- continue;
- }
- str[n++] = ch;
- if (strchr(delim, ch)) {
- break;
- }
- }
- str[n] = '\0';
- return n;
- }
- #define errorHalt(msg) {Serial.println(F(msg)); SysCall::halt();}
- void setup() {
- Serial.begin(9600);
-
-
- while (!Serial) {
- SysCall::yield();
- }
- Serial.println("Type any character to start");
- while (!Serial.available()) {
- SysCall::yield();
- }
-
- if (!SD.begin(CS_PIN)) {
- errorHalt("begin failed");
- }
-
- file = SD.open("READNUM.TXT", FILE_WRITE);
- if (!file) {
- errorHalt("open failed");
- }
-
- file.rewind();
-
- file.print(F(
- "11,12,13,14\r\n"
- "21,22,23,24\r\n"
- "31,32,33,34\r\n"
- "41,42,43,44\r\n"
- "51,52,53,54"
- ));
-
- file.rewind();
-
- int array[ROW_DIM][COL_DIM];
- int i = 0;
- int j = 0;
- size_t n;
- char str[20];
- char *ptr;
-
-
- for (i = 0; i < ROW_DIM; i++) {
- for (j = 0; j < COL_DIM; j++) {
- n = readField(&file, str, sizeof(str), ",\n");
- if (n == 0) {
- errorHalt("Too few lines");
- }
- array[i][j] = strtol(str, &ptr, 10);
- if (ptr == str) {
- errorHalt("bad number");
- }
- while (*ptr == ' ') {
- ptr++;
- }
- if (*ptr != ',' && *ptr != '\n' && *ptr != '\0') {
- errorHalt("extra characters in field");
- }
- if (j < (COL_DIM-1) && str[n-1] != ',') {
- errorHalt("line with too few fields");
- }
- }
-
- if (str[n-1] != '\n' && file.available()) {
- errorHalt("missing endl");
- }
- }
-
- for (i = 0; i < ROW_DIM; i++) {
- for (j = 0; j < COL_DIM; j++) {
- if (j) {
- Serial.print(' ');
- }
- Serial.print(array[i][j]);
- }
- Serial.println();
- }
- Serial.println("Done");
- file.close();
- }
- void loop() {
- }
|