read-5bytes-sd

nazarijtipusak080/work-with-sd-esp32/read-5bytes-sd

No description
read-5bytes-sd
@/read-5bytes-sd
CSport
CS (chip select) pin the SD card reader is connected to. Also known as SS (slave select).
FILEstring
File name to append to
Rpulse
Perform file open, read, close cycle
read-5bytes-sd
CS
FILE
R
DONE
B0
B1
B2
B3
B4
B4byte
B3byte
B2byte
B1byte
B0byte
DONEpulse
Fires when write is done
To use the node in your project you should have the nazarijtipusak080/work-with-sd-esp32 library installed. Use the “File → Add Library” menu item in XOD IDE if you don’t have it yet. See Using libraries for more info.

C++ implementation

#pragma XOD evaluate_on_pin disable
#pragma XOD evaluate_on_pin enable input_R
#pragma XOD error_raise enable

#include <SPI.h>
#include <SD.h>

node {

    bool begun;

    void evaluate(Context ctx) {
        if (!isInputDirty<input_R>(ctx))
            return;

        if (!begun) {
            // First time use, initialize
            auto csPin = getValue<input_CS>(ctx);
            SPI.begin(18, 19, 23, csPin); // SCK, MISO, MOSI, CS
            begun = SD.begin(csPin);
        }

        if (!begun) {
            // Initialization failed (wrong connection, no SD card)
            raiseError(ctx);
            return;
        }

        char filename[16] = { 0 };
        dump(getValue<input_FILE>(ctx), filename);
        File myFile = SD.open(filename, FILE_READ);
        if (!myFile) {
            // Failed to open the file. Maybe, SD card gone,
            // try to reinit next time
            begun = false;
            raiseError(ctx); // Can't open file
            return;
        }

        // No need for input_START and input_CAP if we are only reading 5 bytes
        myFile.seek(0);  // Почати з першого байта файлу

        uint8_t byteArray[5] = {0};  // Масив для збереження 5 байт

        uint8_t index = 0;
        while (myFile.available() && index < 5) {  // Читаємо до 5 байтів
            byteArray[index] = myFile.read();  // Читаємо байт і записуємо в масив
            index++;
        }

        //int pos = myFile.position();  // Отримуємо поточну позицію в файлі
        myFile.close();  // Закриваємо файл

        // Передаємо 5 байтів через виходи
        emitValue<output_B0>(ctx, byteArray[0]);
        emitValue<output_B1>(ctx, byteArray[1]);
        emitValue<output_B2>(ctx, byteArray[2]);
        emitValue<output_B3>(ctx, byteArray[3]);
        emitValue<output_B4>(ctx, byteArray[4]);

        // Передаємо сигнал про завершення
        emitValue<output_DONE>(ctx, 1);
        //emitValue<output_POS>(ctx, pos);  // Позиція в файлі
    }
}