Tuesday, November 9, 2021

Arduino Nano RP2040 Connect + ST7735 SPI TFT with SD Card, read and display bitmap, using hardware SPI.

Exercises run on Arduino Nano RP2040 Connect (in Arduino framework) work with 1.8" 128x160 ST7735 SPI TFT/SD Card Module, to:
- simple display something on ST7735 SPI TFT
- Display files in SD Card, and read txt file from SD Card.
- Read bmp from SD Card and display on ST7735 SPI TFT
- Try example of Adafruit_ImageReader
- Simplified version display bitmap from SD and display on TFT using Adafruit_ImageReader.

In the following exercise Hardware SPI is used for ST7735 and SD Card SPI interface. refer to last post, SPI pins in Arduino Nano RP2040 Connect is:
- MISO    - D12
- MOSI    - D11
- SCK      - D13

Connection:
 * Nano RP2040 Connect drive ST7735 SPI and SD using hardware SPI
 * 
 * TFT_ST7735 nano RP2040 Connect
 * ------------------------------
 * VCC        3V3
 * GND        GND
 * CS         10
 * RESET      9
 * A0(DC)     8
 * SDA        11
 * SCK        13
 * LED        3V3
 * 
 * TFT_ST7735 nano RP2040 Connect
 * ------------------------------
 * SD_CS      4
 * SD_MOSI    11
 * SD_MISO    12
 * SD_SCK     13
 ****************************************************/

Exercise code:

Please notice that  "Adafruit ST7735 and ST7789 Library" and "Adafruit GFX Library" are needed, make sure it's installed in Arduino IDE's Libraries Manager.

nanoRP2040_ST7735.ino, a simple exercise to display something on ST7735 SPI TFT.

/***************************************************
 * nano RP2040 Connect exercise
 * + ST7745/SD
 * 
 * On Arduino nanp RP2040 Connect:
 * (CIPO/MISO)  - D12
 * (COPI/MOSI)  - D11
 * (SCK)        - D13
 * (CS/SS) - Any GPIO (except for A6/A7
 * 
 * This example drive ST7735 SPI and SD using hardware SPI
 * 
 * TFT_ST7735 nano RP2040 Connect
 * ------------------------------
 * VCC        3V3
 * GND        GND
 * CS         10
 * RESET      9
 * A0(DC)     8
 * SDA        11
 * SCK        13
 * LED        3V3
 * 
 ****************************************************/

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

// TFT display using hardware SPI interface.
// Hardware SPI pins are specific to the Arduino board type and
// cannot be remapped to alternate pins.
#define TFT_CS  10  // Chip select line for TFT display
#define TFT_DC   8  // Data/command line for TFT
#define TFT_RST  9  // Reset line for TFT (or connect to +5V)

Adafruit_ST7735 tft_ST7735 = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

void setup(void) {
  delay(1000);
  Serial.begin(115200);
  delay(1000);
  Serial.println("=====================");
  Serial.println("- setup() -");
  tft_ST7735.initR(INITR_BLACKTAB);
  Serial.println("tft: " 
                  + String(tft_ST7735.width()) + " : " 
                  + String(tft_ST7735.height()));

  tft_ST7735.fillScreen(ST7735_BLACK);
  tft_ST7735.setTextWrap(true);
  tft_ST7735.setTextColor(ST77XX_WHITE);
  tft_ST7735.setCursor(0, 0);
  tft_ST7735.print("Arduino nano RP2040 Connect");
  tft_ST7735.println("\n");

  //----------------------------------------
  delay(2000);

  tft_ST7735.setRotation(3);
  tft_ST7735.setCursor(0, 30);
  tft_ST7735.print("rotation: " + String(tft_ST7735.getRotation()));
  tft_ST7735.setCursor(0, 40);
  tft_ST7735.print(String(tft_ST7735.width()) + " x " + String(tft_ST7735.height()));
  
  delay(2000);

  tft_ST7735.fillScreen(ST77XX_RED);
  tft_ST7735.setCursor(50, 50);
  tft_ST7735.print("RED");
  delay(1000);
  tft_ST7735.fillScreen(ST77XX_GREEN);
  tft_ST7735.setCursor(50, 50);
  tft_ST7735.print("GREEN");
  delay(1000);
  tft_ST7735.fillScreen(ST77XX_BLUE);
  tft_ST7735.setCursor(50, 50);
  tft_ST7735.print("BLUE");
  delay(1000);

  delay(1000);
  
  //----------------------------------------

  Serial.println("\n- End of setup() -\n");
}


void loop() {

  tft_ST7735.fillScreen(ST77XX_BLUE);
  for(int offset=0; offset<tft_ST7735.height()/2; offset++){
    int col;
    if(offset%5 == 0)
      col = ST77XX_WHITE;
    else
      col = ST77XX_BLACK;
      
    tft_ST7735.drawRect(offset, offset, 
                 tft_ST7735.width()-2*offset, tft_ST7735.height()-2*offset,
                 col);
    delay(100);
  }

  delay(2000);

  tft_ST7735.fillScreen(ST77XX_BLACK);
  int cx = tft_ST7735.width()/2;
  int cy = tft_ST7735.height()/2;
  for(int r=0; r<tft_ST7735.height()/2; r=r+10){

    tft_ST7735.drawCircle(cx, cy, 
                 r,
                 ST77XX_WHITE);
    delay(200);
  }

  delay(2000);
  delay(2000);
}


nanoRP2040_ST7735_SD.ino, list files in SD card and read the text file hello.txt.
/***************************************************
 * nano RP2040 Connect exercise
 * + ST7745/SD
 * 
 * On Arduino nanp RP2040 Connect:
 * (CIPO/MISO) - D12
 * (COPI/MOSI) - D11
 * (SCK) - D13
 * (CS/SS) - Any GPIO (except for A6/A7
 * 
 * This example drive ST7735 SPI and SD using hardware SPI
 * 
 * TFT_ST7735 nano RP2040 Connect
 * ------------------------------
 * VCC        3V3
 * GND        GND
 * CS         10
 * RESET      9
 * A0(DC)     8
 * SDA        11
 * SCK        13
 * LED        3V3
 * 
 * TFT_ST7735 nano RP2040 Connect
 * ------------------------------
 * SD_CS      4
 * SD_MOSI    11
 * SD_MISO    12
 * SD_SCK     13
 ****************************************************/

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

// TFT display and SD card will share the hardware SPI interface.
// Hardware SPI pins are specific to the Arduino board type
#define SD_CS    4  // Chip select line for SD card
#define TFT_CS  10  // Chip select line for TFT display
#define TFT_DC   8  // Data/command line for TFT
#define TFT_RST  9  // Reset line for TFT (or connect to +5V)

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

File root;
File myFile;

void setup(void) {
  delay(1000);
  Serial.begin(115200);
  delay(1000);
  Serial.println("=====================");
  Serial.println("- setup() -");
  tft.initR(INITR_BLACKTAB);
  Serial.println("tft: " 
                  + String(tft.width()) + " : " 
                  + String(tft.height()));

  tft.fillScreen(ST7735_BLACK);
  tft.setTextWrap(true);
  tft.setTextColor(ST77XX_WHITE);
  tft.setCursor(0, 0);
  tft.print("Arduino nano RP2040 Connect");
  tft.println("\n");

  //----------------------------------------
  Serial.println("Initializing SD card...");
  if (!SD.begin(SD_CS)){
    Serial.println("SD.begin() failed!");
  }
  else{
    Serial.println("SD.begin() Success.");

    root = SD.open("/");
    printDirectory(root, 0);

    Serial.println("===============================");
    // open the file for reading:
    myFile = SD.open("hello.txt");
    if (myFile) {
      Serial.println("test.txt:");
      Serial.println("-------------------------------");
      // read from the file until there's nothing else in it:
      while (myFile.available()) {
      //Serial.write(myFile.read());
      byte b = myFile.read();
      Serial.write(b);
      tft.print((char)b);
      }
      // close the file:
      myFile.close();
    } else {
      // if the file didn't open, print an error:
      Serial.println("error opening test.txt");
    }
    Serial.println("\n===============================\n");

    
  }


  //----------------------------------------

  Serial.println("\n- End of setup() -\n");
}


void loop() {

  delay(100);
}

//
// printDirectory() copy from:
// Examples > SD > listfiles
//

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}


nanoRP2040_ST7735_SD_bmp.ino, read bmp files in SD Card, test.bmp, test2.bmp and test3.bmp, and display on ST7735 SPI TFT. It can be noted in bmpDraw(), copy from examples under "Adafruit ST7735 and ST7789 Library" > shieldtest, bmpDepth must be 24. To prepare bmp for this using GIMP, refer to the above video, ~ 6:38.
/***************************************************
 * nano RP2040 Connect exercise
 * + ST7745/SD
 * 
 * On Arduino nanp RP2040 Connect:
 * (CIPO/MISO) - D12
 * (COPI/MOSI) - D11
 * (SCK) - D13
 * (CS/SS) - Any GPIO (except for A6/A7
 * 
 * This example drive ST7735 SPI and SD using hardware SPI
 * 
 * TFT_ST7735 nano RP2040 Connect
 * ------------------------------
 * VCC        3V3
 * GND        GND
 * CS         10
 * RESET      9
 * A0(DC)     8
 * SDA        11
 * SCK        13
 * LED        3V3
 * 
 * TFT_ST7735 nano RP2040 Connect
 * ------------------------------
 * SD_CS      4
 * SD_MOSI    11
 * SD_MISO    12
 * SD_SCK     13
 ****************************************************/

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

// TFT display and SD card will share the hardware SPI interface.
// Hardware SPI pins are specific to the Arduino board type.
#define SD_CS    4  // Chip select line for SD card
#define TFT_CS  10  // Chip select line for TFT display
#define TFT_DC   8  // Data/command line for TFT
#define TFT_RST  9  // Reset line for TFT (or connect to +5V)

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

File root;
File myFile;

void setup(void) {
  delay(1000);
  Serial.begin(115200);
  delay(1000);
  
  Serial.println("=====================");
  Serial.println("- setup() -");
  tft.initR(INITR_BLACKTAB);
  Serial.println("tft: " 
                  + String(tft.width()) + " : " 
                  + String(tft.height()));

  tft.fillScreen(ST7735_BLACK);
  tft.setTextWrap(true);
  tft.setTextColor(ST77XX_WHITE);
  tft.setCursor(0, 0);
  tft.print("Arduino nano RP2040 Connect");

  //----------------------------------------
  Serial.println("Initializing SD card...");
  if (!SD.begin(SD_CS)){
    Serial.println("SD.begin() failed!");
  }
  else{
    Serial.println("SD.begin() Success.");

    root = SD.open("/");
    printDirectory(root, 0);

  }


  //----------------------------------------

  Serial.println("\n- End of setup() -\n");
}

const int NO_OF_BMP = 3;
char* bmpFiles[NO_OF_BMP] = {"/test.bmp", "/test2.bmp",  "/test3.bmp"};

void loop() {
  for(int i=0; i<NO_OF_BMP; i++){
    bmpDraw(bmpFiles[i], 0, 0);
    delay(2000);
  }
}

//
// printDirectory() copy from:
// Examples > SD > listfiles
//

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

//
// bmpDraw() copy from:
// Examples under "Adafruit ST7735 and ST7789 Library" > shieldtest
//
// This function opens a Windows Bitmap (BMP) file and
// displays it at the given coordinates.  It's sped up
// by reading many pixels worth of data at a time
// (rather than pixel by pixel).  Increasing the buffer
// size takes more of the Arduino's precious RAM but
// makes loading a little faster.  20 pixels seems a
// good balance.

#define BUFFPIXEL 20

void bmpDraw(char *filename, uint8_t x, uint8_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, startTime = millis();

  if((x >= tft.width()) || (y >= tft.height())) return;

  Serial.println();
  Serial.print("Loading image '");
  Serial.print(filename);
  Serial.println('\'');

  // Open requested file on SD card
  if ((bmpFile = SD.open(filename)) == NULL) {
    Serial.print("File not found");
    return;
  }

  // Parse BMP header
  if(read16(bmpFile) == 0x4D42) { // BMP signature
    Serial.print("File size: "); Serial.println(read32(bmpFile));
    (void)read32(bmpFile); // Read & ignore creator bytes
    bmpImageoffset = read32(bmpFile); // Start of image data
    Serial.print("Image Offset: "); Serial.println(bmpImageoffset, DEC);
    // Read DIB header
    Serial.print("Header size: "); Serial.println(read32(bmpFile));
    bmpWidth  = read32(bmpFile);
    bmpHeight = read32(bmpFile);
    if(read16(bmpFile) == 1) { // # planes -- must be '1'
      bmpDepth = read16(bmpFile); // bits per pixel
      Serial.print("Bit Depth: "); Serial.println(bmpDepth);
      if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed

        goodBmp = true; // Supported BMP format -- proceed!
        Serial.print("Image size: ");
        Serial.print(bmpWidth);
        Serial.print('x');
        Serial.println(bmpHeight);

        // 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();
        Serial.print("Loaded in ");
        Serial.print(millis() - startTime);
        Serial.println(" ms");
      } // end goodBmp
    }
  }

  bmpFile.close();
  if(!goodBmp) Serial.println("BMP format not recognized.");
}

// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.

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;
}


nanoRP2040_ST7735_SD_ImageReader.ino, a simplified version to display bitmaps using Adafruit_ImageReader, make sure it's installed.
// Adafruit_ImageReader test for Adafruit ST7735 TFT Breakout for Arduino.
// Demonstrates loading images from SD card or flash memory to the screen,
// to RAM, and how to query image file dimensions.
// Requires three BMP files in root directory of SD card:
// test.bmp, test2.bmp and test3.bmp.
// As written, this uses the microcontroller's SPI interface for the screen
// (not 'bitbang') and must be wired to specific pins.

#include <Adafruit_GFX.h>         // Core graphics library
#include <Adafruit_ST7735.h>      // Hardware-specific library
#include <SdFat.h>                // SD card & FAT filesystem library
#include <Adafruit_ImageReader.h> // Image-reading functions

// TFT display and SD card share the hardware SPI interface, using
// 'select' pins for each to identify the active device on the bus.

#define SD_CS    4 // SD card select pin
#define TFT_CS  10 // TFT select pin
#define TFT_DC   8 // TFT display/command pin
#define TFT_RST  9 // Or set to -1 and connect to Arduino RESET pin

SdFat                SD;         // SD card filesystem
Adafruit_ImageReader reader(SD); // Image-reader object, pass in SD filesys

Adafruit_ST7735      tft    = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
Adafruit_Image       img;        // An image loaded into RAM
int32_t              width  = 0, // BMP image dimensions
                     height = 0;

void setup(void) {

  ImageReturnCode stat; // Status from image-reading functions

  Serial.begin(115200);

  tft.initR(INITR_BLACKTAB); // Initialize screen

  // The Adafruit_ImageReader constructor call (above, before setup())
  // accepts an uninitialized SdFat or FatFileSystem object. This MUST
  // BE INITIALIZED before using any of the image reader functions!
  Serial.print(F("Initializing filesystem..."));

  // SD card is pretty straightforward, a single call...
  if(!SD.begin(SD_CS, SD_SCK_MHZ(10))) { // Breakouts require 10 MHz limit due ...
    Serial.println(F("SD begin() failed"));
    for(;;); // Fatal error, do not continue
  }

  Serial.println(F("OK!"));

  // Fill screen blue. Not a required step, this just shows that we're
  // successfully communicating with the screen.
  tft.fillScreen(ST7735_BLUE);

  // Load full-screen BMP file 'test.bmp' at position (0,0) (top left).
  // Notice the 'reader' object performs this, with 'tft' as an argument.
  Serial.print(F("Loading test.bmp to screen..."));
  stat = reader.drawBMP("/test.bmp", tft, 0, 0);
  reader.printStatus(stat);   // How'd we do?

  // Query the dimensions of image 'test2.bmp' WITHOUT loading to screen:
  Serial.print(F("Querying test2.bmp image size..."));
  stat = reader.bmpDimensions("/test2.bmp", &width, &height);
  reader.printStatus(stat);   // How'd we do?
  if(stat == IMAGE_SUCCESS) { // If it worked, print image size...
    Serial.print(F("Image dimensions: "));
    Serial.print(width);
    Serial.write('x');
    Serial.println(height);
  }

  // Load small BMP 'test3.bmp' into a GFX canvas in RAM.
  Serial.print(F("Loading test3.bmp to canvas..."));
  stat = reader.loadBMP("/test3.bmp", img);
  reader.printStatus(stat); // How'd we do?

  delay(2000); // Pause 2 seconds before moving on to loop()
}

void loop() {

  for(int r=0; r<4; r++) { // For each of 4 rotations...
    tft.setRotation(r);    // Set rotation
    tft.fillScreen(0);     // and clear screen

    reader.drawBMP("/test2.bmp", tft, 0, 0);

    delay(1000); // Pause 1 sec.

    img.draw(tft,                                    // Pass in tft object
        0 ,  // Horiz pos.
        0); // Vert pos

    delay(2000); // Pause 2 sec.
  }

}

Related:


No comments:

Post a Comment