在Arduino TFT屏幕上列出SD卡文件

时间:2013-12-31 00:39:29

标签: arduino

我在尝试列出SD卡中的文件时遇到问题: 我有以下代码:

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

#define sd_cs  4
#define lcd_cs 10
#define dc     9
#define rst    8  

TFT TFTscreen = TFT(lcd_cs, dc, rst);

PImage logo;

void intro() {
    TFTscreen.begin();
    TFTscreen.background(255, 255, 255);
    TFTscreen.stroke(0, 0, 255);
    TFTscreen.println();
    TFTscreen.println("Welcome..");
    delay(500);
}


void draw(char *imageName)  {
  TFTscreen.begin();
  TFTscreen.background(255, 255, 255);

  // Load the image file.
  logo = TFTscreen.loadImage(imageName);
  if (!logo.isValid()) {
    Serial.println("error while loading the image");
  }
  if (logo.isValid() == false) {
    return;
  }

  Serial.println("drawing image");

  // draw the image to the screen
  TFTscreen.image(logo, 0, 0);
}  

void initSD() {    
   Serial.print("Initializing SD card...");
   if (!SD.begin(sd_cs)) {
        Serial.println("failed!");
        return;
   }
   Serial.println("OK!"); 

}  

void setup() 

    Serial.begin(9600);

    intro();

    initSD();

  draw("2.bmp");
}

void loop() { }

以上代码工作正常,&#34;欢迎&#34;消息显示在屏幕上,然后显示&#34; 2.bmp&#34;图像符合预期。串行输出打印:

IniInitializing SD card...OK!
File size: 61496
Image Offset: 54
Header size: 40
Bit Depth: 24
Image size: 128x160
drawing image

现在我尝试列出SD卡根目录下的文件:

File root;
void listSD()  {
    root = SD.open("/");
    printDirectory(root);
}

void printDirectory(File dir) {
    while(true) {

        File entry =  dir.openNextFile();
        if (! entry) {
            dir.rewindDirectory();
            break;
        }

        Serial.println(entry.name());
   }
}

void setup() {
    Serial.begin(9600);

    intro();

    initSD();
    listSD(); //<- this function here

   draw("2.bmp");

}

但是在列出根文件夹后,我发现找不到文件错误:

Initializing SD card...OK!
1.BMP
2.BMP
loadImage: file not found: 2.bmp
error while loading the image
你能告诉我这里有什么问题吗?我怀疑root = SD.open("/");会以某种方式影响TFTscreen.loadImage(imageName);,但我不知道如何。

我使用的是Arduino UNO R3,屏幕为TFT LCD,IDE版本为1.5.5。

2 个答案:

答案 0 :(得分:2)

void printDirectory(File dir) {
  //------------------------------------------------------------
  dir.rewindDirectory(); // you need to rewind the the Directory
  //------------------------------------------------------------
  while(true) { 
    File entry =  dir.openNextFile();
    if (! entry) {
      break;
    }          
    Serial.println(entry.name());

  ..etc

  }
}

// bug issue #904

答案 1 :(得分:0)

好吧,在这个功能中:

void printDirectory(File dir) {
    while(true) {

        File entry =  dir.openNextFile();
        if (! entry) {
            dir.rewindDirectory();
            break;
        }
        else 
            entry.close();  //<-- We need to close the file here

        Serial.println(entry.name());
   }
}

该文件应该关闭,以便稍后阅读..

相关问题