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

今日のニャンコ その4


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

前回はBとCを自動的に行う方法を紹介しましたが、30分ぐらい経過する と、何もしなくても
ESP8266側のFTPサーバーが反応しなくなってしまいました。
調べましたが原因がよく分からないので以下のように変更します。
No. Raspberry側 ESP8266側
1
起動時にimage.bmpが有れば表示
2 image.bmpをアップロード
upload.txtを監視
3 upload.txtをアップロード
upload.txtを監視
4
upload.txtを削除
5
10秒後に強制リセット
No.1に戻る

ESP8266で強制リセットを行っても、SPIFFS上のファイルには影響しないことはこちらで確認しています。
Raspberry側の処理(No.2 No.3)を15分毎にcronで繰り返し実行します。

ESP8266側のスケッチは以下のようになります。
myIP(192, 168, 10, 99)の部分は、環境に合わせて変更してください。
画像を表示する前に画像ファイルのサイズを求めて、X位置を計算しています。
/*
 * SPIFFSにあるBMPファイルを表示する
 */
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266FtpServer.h>
#include <FS.h>
#include <SPI.h>
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

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

//set #define FTP_DEBUG in ESP8266FtpServer.h to see ftp verbose on serial
FtpServer ftpSrv;

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

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

long lastTime = 0;

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 display_Running_Sketch (void){
  String the_path = __FILE__;
  int slash_loc = the_path.lastIndexOf('/');
  String the_cpp_name = the_path.substring(slash_loc+1);
  int dot_loc = the_cpp_name.lastIndexOf('.');
  String the_sketchname = the_cpp_name.substring(0, dot_loc);

  Serial.print("\nArduino is running Sketch: ");
  Serial.println(the_sketchname);
  Serial.print("Compiled on: ");
  Serial.print(__DATE__);
  Serial.print(" at ");
  Serial.print(__TIME__);
  Serial.print("\n");
}


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(".");
  }
  Serial.println();

  // 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());

  tft.begin();
  tft.fillScreen(ILI9341_BLACK);
  tft.setRotation(3);
  Serial.print("tft.width=");
  Serial.println(tft.width());
  Serial.print("tft.height=");
  Serial.println(tft.height());

  if (SPIFFS.begin()) {
   Serial.println("SPIFFS opened!");
    // Show BMP file
    char path[32];
    strcpy(path, "/image.bmp");
    if (SPIFFS.exists(path)) {
      digitalWrite(TFT_LED, HIGH);
      bmpDraw(path);
    } else {
      Serial.print(path);
      Serial.println(" NOT found");
      digitalWrite(TFT_LED, LOW);
      tft.fillScreen(ILI9341_BLACK);
    }
  } else {
    while (1) {
      Serial.println("SPIFFS failed!");
      delay(1000);
    }
  } 

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

}

void loop(void){
  static long ResetTime = 0x7fffffff;
 
  ftpSrv.handleFTP();
  yield();
  long now = millis();
  if (now - lastTime > 1000) {
    lastTime = now;
    Serial.print("IP Address=");
    Serial.print(WiFi.localIP());
    Serial.print(" ResetTime=");
    Serial.print(ResetTime);
    Serial.print(" ");
    Serial.print("now=");
    Serial.println(now);
    if (ResetTime < now) ESP.reset();

    File bmpFile;
    // upload.txtが有れば10秒後に強制Reset
    if (SPIFFS.exists("/upload.txt")) {
      Serial.println("upload.txt found");
      SPIFFS.remove("/upload.txt");
      ResetTime = now + 10000; //10秒後にreset
    }
  }
}

// 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) {

  File     bmpFile;
  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
  uint8_t  r, g, b;
  uint32_t pos = 0, startTime = millis();

  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));
    int bmpWidth  = read32(bmpFile);
    int bmpHeight = read32(bmpFile);
    int offsetX = 0;
    int offsetY = 0;
    int draw_width = bmpWidth;
    int draw_height = bmpHeight;
    if (bmpWidth <= tft.width()) {
      offsetX = (tft.width() - bmpWidth) / 2;
    } else {
      draw_width = tft.width();
    }
    if (bmpHeight <= tft.height()) {
      offsetY = (tft.height() - bmpHeight) / 2;
    } else {
      draw_height = tft.height();
    }
    Serial.print("offsetX=");
    Serial.println(offsetX);
    Serial.print("offsetY=");
    Serial.println(offsetY);
    Serial.print("draw_width=");
    Serial.println(draw_width);
    Serial.print("draw_height=");
    Serial.println(draw_height);

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

        for (int row=0; row<draw_height; 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 (int col=0; col<draw_width; 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)); // なぜか動かなくなった
            tft.drawPixel(col+offsetX, row+offsetY, tft.color565(r,g,b));

            yield();
           
          } // 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;
}

Raspberry側のcronの設定は以下の様になります。
15分毎にshow_esp8266.shを使ってファイルアップロードを繰り返します。
# m h  dom mon dow   command
*/15 * * * * sudo /home/orangepi/show_esp8266.sh

しばらく動かし続けましたが問題なく動いています。
そこで、夜間は何も表示しないことにしました。
本当はTFTのバックライトをOFFにしたいのですが....
Raspberry側に、ftpのコマンドファイル(ftp2.cmd)とシェルスクリプト(clear_esp8266.sh)を作ります。
【ftp2.cmd】
open 192.168.10.99
user esp8266 esp8266
del image.bmp
put /tmp/upload.txt upload.txt
bye

【clear_esp8266.sh】
#!/bin/bash
#
#set -x
HomeDir="/home/orangepi"
#ESP8266にアップロード
touch /tmp/upload.txt
ftp -p -n < ${HomeDir}/ftp2.cmd > /dev/NULL

昼間(7時から22時)はshow_esp8266.shを、夜間(23時から翌朝7時まで)はclear_esp8266.shを15分間隔で 実 行します。
# m h  dom mon dow   command
*/15 7-22 * * * sudo /home/orangepi/show_esp8266.sh
*/15 23 * * * sudo /home/orangepi/clear_esp8266.sh
*/15 0-6 * * * sudo /home/orangepi/clear_esp8266.sh

ようやく電子日めくりの完成です。
ニャンコではなくワンコ派の方はこちら...