/*******************************************************************************
    PocketScreen "SD Write GPIO Value" Example
    written by Florian Keller
    last changed 28 Nov 20

    Reads the value on the A0 GPIO pin and saves it to the SD.
    This sketch opens and closes the file on every write (once a second)
    instead of keeping it open. This prevents data loss when the card is
    removed and cached values have not been written yet.
*******************************************************************************/

#include <PocketScreen.h>
PocketScreen pocketscreen = PocketScreen();

// include SdFat
#include <SdFat.h>
SdFat SD;

// small buffer to stringify the read value
char strbuf[64];

void setup() {
    pocketscreen.begin();

    // open SD connection
    if (!SD.begin()) {
        // open serial monitor
        // don't forget to set your serial monitor baud rate to 115200, too!
        SerialUSB.begin(115200);
    
        // it failed. Check if there is an SD inserted, and print the appopriate error message.
        if (!pocketscreen.isSDInserted()) {
            SerialUSB.println("Error: no SD inserted.");
        } else {
            SerialUSB.println("Error: could not read SD.");
        }
        while (true);
    }
}

void loop() {
    // open file
    File file = SD.open("gpio-write.txt", FILE_WRITE);
    if (file) {
        // read pin value and put int into a string
        int value = analogRead(A0);
        sprintf(strbuf, "%i\n", value);
        
        // write string to file
        file.write(strbuf);
        
        // close file
        file.close();
    }
    
    // wait one second
    delay(1000);
}
