





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

#define SD_CS 10                // Pin der mit dem CS des SD Kartenslots verbunden ist
#define TFT_CS 6                // Pin der mit dem CS des Displays verbunden ist
#define TFT_DC 7                // Pin der mit dem DC des Displays verbunden ist
#define TFT_RST 5                // Pin der mit RST des Displays verbunden ist
#define BUFFPIXEL 20                // Pixel die gleichzeitig verarbeitet werden, Abhängig vom verfügbaren Arbeitsspeicher. 20 ist ein guter Standartwert

unsigned long Anzeigezeit = 10000;  // Anzeigezeit in Millisekunden

Adafruit_ST7735 tft =               // Erstellt ein Objekt mit dem Namen tft
  Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

void setup(void) {
  pinMode(TFT_CS, OUTPUT);          // TFT CS Pin als Output
  digitalWrite(TFT_CS, HIGH);       // TFT für SPI deaktivieren
  pinMode(SD_CS, OUTPUT);           // SD CS Pin als Output
  digitalWrite(SD_CS, HIGH);        // SD für SPI deaktiviern  
  tft.initR(INITR_MINI160x80);      // Initialisiert das Display // tft.initR(INITR_MINI160x80) für das 0.96' 160x80 Display
  tft.invertDisplay(true);          // Invertiert die Farben, nötig bei einigen Displays
  SD.begin(SD_CS);                  // Öffnet eine Verbindung zur SD Karte
  tft.setRotation(1);               // Rotation der Anzeige. Mögliche Werte in Klammern sind 0, 1, 2 oder 3. Für 0Grad, 90Grad, 180Grad oder 270Grad gedreht.
}

void loop() {
  File Verzeichnis = SD.open("/");                  // öffnet das Verzeichnis und erstellt ein Objekt
  Verzeichnis.rewindDirectory();                    // Gehe an die vorderste Stelle des Verzeichnisses
  while(true) {                                     // Endlos-Schleife
     File Eintrag =  Verzeichnis.openNextFile();    // Ersdtellt ein Objekt vom nächsten Eintrag im Verzeichniss
     if (! Eintrag) break;                          // Wenn kein neuer Eintrag erstellt wurde, verlasse die Endlos-Schleife
     if (! Eintrag.isDirectory()){                  // Nur ausführen wenn der Eintrag kein Verzeichniss ist
       bmpDraw(Eintrag.name(),0,0);                 // Ruft die BildZeichnen Funktion auf
       delay(Anzeigezeit);                          // Wartet entsprechend der Anzeigezeit in Millisekunden
     }
     Eintrag.close();                               // Schließt das Objekt
   }
}

// Folgende Funktionen sind zum einlesen und zeichenen auf dem Display, kopiert von Adafruit, etwas angepasst
void bmpDraw(const char *filename, uint8_t x, uint16_t y) {
  File     bmpFile;
  int      bmpWidth, bmpHeight;   // W+H in pixels
  uint8_t  bmpDepth;              // Bit depth (currently must be 24)
  uint32_t bmpImageoffset;        // Start of image data in file
  uint32_t rowSize;               // Not always = bmpWidth; may have padding
  uint8_t  sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel)
  uint8_t  buffidx = sizeof(sdbuffer); // Current position in sdbuffer
  boolean  goodBmp = false;       // Set to true on valid header parse
  boolean  flip    = true;        // BMP is stored bottom-to-top
  int      w, h, row, col;
  uint8_t  r, g, b;
  uint32_t pos = 0;
  if((x >= tft.width()) || (y >= tft.height())) return;
  // Open requested file on SD card
  if ((bmpFile = SD.open(filename)) == NULL) return;
  // Parse BMP header
  if(read16(bmpFile) == 0x4D42) { // BMP signature
    (void)read32(bmpFile); // Read & ignore File Size
    (void)read32(bmpFile); // Read & ignore creator bytes
    bmpImageoffset = read32(bmpFile); // Start of image data
    // Read DIB header
    (void)read32(bmpFile); // Read & ignore Header Size
    bmpWidth  = read32(bmpFile);
    bmpHeight = read32(bmpFile);
    if(read16(bmpFile) == 1) { // # planes -- must be '1'
      bmpDepth = read16(bmpFile); // bits per pixel
      if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed
        goodBmp = true; // Supported BMP format -- proceed!
        // BMP rows are padded (if needed) to 4-byte boundary
        rowSize = (bmpWidth * 3 + 3) & ~3;
        // If bmpHeight is negative, image is in top-down order.
        // This is not canon but has been observed in the wild.
        if(bmpHeight < 0) {
          bmpHeight = -bmpHeight;
          flip      = false;
        }
        // Crop area to be loaded
        w = bmpWidth;
        h = bmpHeight;
        if((x+w-1) >= tft.width())  w = tft.width()  - x;
        if((y+h-1) >= tft.height()) h = tft.height() - y;
        // Set TFT address window to clipped image bounds
        tft.startWrite();
        tft.setAddrWindow(x, y, w, h);
        for (row=0; row<h; row++) { // For each scanline...
          // Seek to start of scan line.  It might seem labor-
          // intensive to be doing this on every line, but this
          // method covers a lot of gritty details like cropping
          // and scanline padding.  Also, the seek only takes
          // place if the file position actually needs to change
          // (avoids a lot of cluster math in SD library).
          if(flip) // Bitmap is stored bottom-to-top order (normal BMP)
            pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize;
          else     // Bitmap is stored top-to-bottom
            pos = bmpImageoffset + row * rowSize;
          if(bmpFile.position() != pos) { // Need seek?
            tft.endWrite();
            bmpFile.seek(pos);
            buffidx = sizeof(sdbuffer); // Force buffer reload
          }
          for (col=0; col<w; col++) { // For each pixel...
            // Time to read more pixel data?
            if (buffidx >= sizeof(sdbuffer)) { // Indeed
              bmpFile.read(sdbuffer, sizeof(sdbuffer));
              buffidx = 0; // Set index to beginning
              tft.startWrite();
            }
            // Convert pixel from BMP to TFT format, push to display
            b = sdbuffer[buffidx++];
            g = sdbuffer[buffidx++];
            r = sdbuffer[buffidx++];
            tft.pushColor(tft.color565(r,g,b));
          } // end pixel
        } // end scanline
        tft.endWrite();
      } // end goodBmp
    }
  }
  bmpFile.close();
}

uint16_t read16(File f) {
  uint16_t result;
  ((uint8_t *)&result)[0] = f.read(); // LSB
  ((uint8_t *)&result)[1] = f.read(); // MSB
  return result;
}

uint32_t read32(File f) {
  uint32_t result;
  ((uint8_t *)&result)[0] = f.read(); // LSB
  ((uint8_t *)&result)[1] = f.read();
  ((uint8_t *)&result)[2] = f.read();
  ((uint8_t *)&result)[3] = f.read(); // MSB
  return result;
}