ESP-WROOM-02でTFTに画像を表示する

今日のニャンコ その2


電子日めくりカレンダーの2回目です、
@画像データをネットからダウンロードする。
A画像データを変換/整形する。
B画像データをESP8266にアップロードする。
C画像データをESP8266で表示する。

前回は@とAを紹介しました。
そこで、今回はBとCを紹介します。

まず、ESP8266側にFTP Serverのライブラリを追加します。
このライブラリは非常に大作です(よくここまでデバッグしたと感心します)が、表示の互換性の問題でWinSCPやffftpでは接続できませ ん。
そこで、こ のページに従ってライブラリソース(ESP8266FtpServer.cpp)の一部を修正します。
修正後のESP8266FtpServer.cppは以下のようになります。
  else if( ! strcmp( command, "LIST" ))
  {
    if( ! dataConnect())
      client.println( "425 No data connection");
    else
    {
      client.println( "150 Accepted data connection");
      uint16_t nm = 0;
      Dir dir=SPIFFS.openDir(cwdName);
//      if( !SPIFFS.exists(cwdName))
//        client.println( "550 Can't open directory " + String(cwdName) );
//      else
//      {
        while( dir.next())
        {
            String fn, fs;
            fn = dir.fileName();
            fn.remove(0, 1);
            fs = String(dir.fileSize());
//            data.println( "+r,s" + fs);
//            data.println( ",\t" + fn );
              data.print("01-01-2000  00:00AM " + fs);
              data.println(" " + fn);
          nm ++;
        }
        client.println( "226 " + String(nm) + " matches total");
//      }
      data.stop();
    }

次に以下のスケッチをESP8266に書き込みます。
FTPサーバーとして動かすためには、固定IPにした方が便利です。
私の環境では「192.168.10.99」のIPアドレスを使いましたが、myIP(192, 168, 10, 99)の部分は、環境に合わせて変更してください。
/*
 * FTP server sample
 */
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266FtpServer.h>

IPAddress myIP(192, 168, 10, 99);
const char* ssid = "アクセスポイントのSSID";
const char* password = "アクセスポイントのパスワード";

FtpServer ftpSrv;

void setup(void){
  Serial.begin(9600);
  delay(500);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // Set Fix IP
  WiFi.config(myIP, WiFi.gatewayIP(), WiFi.subnetMask());
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  /////FTP Setup, ensure SPIFFS is started before ftp;  /////////
  if (SPIFFS.begin()) {
    Serial.println("SPIFFS opened!");
    //username, password for ftp.  set ports in ESP8266FtpServer.h  (default 21, 50009 for PASV)
    ftpSrv.begin("esp8266","esp8266");
  }   
}

void loop(void){
  ftpSrv.handleFTP();
}

ESP8266へのスケッチの書き込みが終了したら、Raspberry側で以下のコマンドを実行します。
下線部分が入力です。パスワードは表示されません。
$ ftp -p
ftp> open 192.168.10.99
Connected to 192.168.10.99.
220--- Welcome to FTP for ESP8266 ---
220---   By David Paiva   ---
220 --   Version FTP-2016-01-14   --
Name (192.168.10.99:orangepi): esp8266
331 OK. Password required
Password: esp8266
230 OK.
ftp> binary
200 TYPE is now 8-bit binary
ftp> put /tmp/imageDst.bmp image.bmp
local: /tmp/imageDst.bmp remote: image.bmp
227 Entering Passive Mode (192,168,10,99,195,89).
150 Connected to port 50009
226-File successfully transferred
226 2857 ms, 57 kbytes/s
164298 bytes sent in 1.60 secs (100.3793 kB/s)
ftp> dir
227 Entering Passive Mode (192,168,10,99,195,89).
150 Accepted data connection
01-01-2000  00:00AM 164298 image.bmp
226 1 matches total
ftp> bye
221 Goodbye

これで、ESP8266のSPIFFS領域に画像ファイルがアップロードされます。
次に、以下のスケッチでSPIFFS領域にある画像ファイルを表示します。
SPIFFS領域にある画像ファイルの表示はこ ちらを参考にさせていただきました。ありがとうございます。
bmpDraw関数はAdafruit_ILI9341ライブラリのサンプルスケッチに含まれているspitftbitmap.inoを一部変更 しただけです。
変更手順はこ ちらに記載されているとおりです。
/*
 * SPIFFSにあるBMPファイルを表示する
 */
#include <FS.h>
#include <SPI.h>
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

// TFT display and SD card will share the hardware SPI interface.
// Hardware SPI pins are specific to the Arduino board type and
// cannot be remapped to alternate pins.  For Arduino Uno,
// Duemilanove, etc., pin 11 = MOSI, pin 12 = MISO, pin 13 = SCK.

#define TFT_DC 15
#define TFT_CS 2
#define TFT_RST -1

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

void listDir() {
  char cwdName[2];

  strcpy(cwdName,"/");
  Dir dir=SPIFFS.openDir(cwdName);
  while( dir.next()) {
    String fn, fs;
    fn = dir.fileName();
    fn.remove(0, 1);
    fs = String(dir.fileSize());
    Serial.println("<" + fn + "> size=" + fs);
  } // end while
}

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

  tft.begin();
  tft.fillScreen(ILI9341_BLUE);
  tft.setRotation(3);

  Serial.print("Initializing SPIFFS...");
  if (!SPIFFS.begin()) {
    Serial.println("SPIFFS failed!");
  }
  Serial.println("OK!");

  // list directory
  listDir();

  bmpDraw("/image.bmp", 45, 0);
}

void loop() {
}

// 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, 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, startTime = millis();

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

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

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

  // Parse BMP header
  if(read16(bmpFile) == 0x4D42) { // BMP signature
    Serial.print(F("File size: ")); Serial.println(read32(bmpFile));
    (void)read32(bmpFile); // Read & ignore creator bytes
    bmpImageoffset = read32(bmpFile); // Start of image data
    Serial.print(F("Image Offset: ")); Serial.println(bmpImageoffset, DEC);
    // Read DIB header
    Serial.print(F("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(F("Bit Depth: ")); Serial.println(bmpDepth);
      if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed

        goodBmp = true; // Supported BMP format -- proceed!
        Serial.print(F("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.setAddrWindow(x, y, x+w-1, y+h-1);

        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?
            bmpFile.seek(pos,SeekSet);
            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
            }

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

  bmpFile.close();
  if(!goodBmp) Serial.println(F("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;
}


画像データが表示されれば成功です。
ただ、このままでは毎回スケッチを書き換える必要が有ります。
そこで、次回は画像データのアップロードと画像データの表示を自動的に行うようにします。

続く....