ESP32でILI9341(パラレル)LCDを動かす

# 事の顛末
ESP32でILI9341LCDを動かすことについての情報は結構あり、それを参考にしてやってみようということでLCDを注文した。
しかし、届いたのはパラレルのもの:scream:
改めて注文情報を確認したら、発注ミスでした(´・ω・`)
とりあえず、パラレルなら動作も速いだろうしということで動かしてみようということに
備忘録を兼ね、その記録記します。
# 参考にしたサイト
配線関係、ライブラリ関係は↓を参考にしました、特にタッチスクリーン系

https://blog.xuite.net/iamleon/blog/589265496#

設計思想的やソースコード等は↓の2つのサイト

https://www.pangodream.es/ili9341-esp32-parallel

https://thesolaruniverse.wordpress.com/2021/06/01/esp32-wroom-32-and-uno-shield-parallel-tft-displays/

以上を参考にしながら、ESP32とILI9341の表示とタッチパネルを使える様にすすめていく。
配線は台湾？のサイトにあった↓で進める
![1250370034_x.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3118608/0da65e3f-951d-76a3-7f13-805fd375c87a.jpeg)

配線しようと思って気づいたのだが、基板上のピン配置が自分が使っているのと微妙に違う:grimacing:
![20230313_180639.JPG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3118608/a69d05f6-901b-f213-0880-2dde48fb9b8b.jpeg)
もうデータ変えたくないのでバラのジャンパ線で配線することにした😔
同じチップでもメーカーによってピン配列が異なるので注意しましょう。

# ライブラリの準備
ライブラリ関係では最初の台湾？のサイトを参考にしながら進める。
インストールしたライブラリ
今回の目標としてはタッチパネルまで使用可能にすることなので、その関連も含みます
https://github.com/ImpulseAdventure/GUIslice
https://github.com/Bodmer/TFT_eSPI
https://github.com/adafruit/Adafruit_TouchScreen

まず、ヘッダファイルの変更が必要。
とりあえず、タッチスクリーン系から
TouchScreen.hは
`C:\Users\hogehoge_\Documents\Arduino\libraries\Adafruit_TouchScreen`
にあります。
バックアップは作っておこう
ライブラリ更新を行うと変更が戻ってしまうかもしれないので、変更したファイルも別フォルダにコピーしておいたほうが無難
ここの12と14は接続するピンによって変わります
```
#define aXM 12  // analog input pin connected to LCD_RS 
#define aYP 14  // analog input pin connected to LCD_WR
```



``` ToushScreen.h
// Touch screen library with X Y and Z (pressure) readings as well
// as oversampling to avoid 'bouncing'
// (c) ladyada / adafruit
// Code under MIT License

#ifndef _ADAFRUIT_TOUCHSCREEN_H_
#define _ADAFRUIT_TOUCHSCREEN_H_
#include <stdint.h>

// ESP32 specific 
#define ESP32_WIFI_TOUCH // uncomment to use parallel MCU Friend LCD touchscreen with ESP32 UNO Wifi
#ifdef ESP32 
#define ADC_MAX 4095  // maximum value for ESP32 ADC (default 11db, 12 bits)
#define aXM 12  // analog input pin connected to LCD_RS 
#define aYP 14  // analog input pin connected to LCD_WR
#else
#define ADC_MAX 1023  // Arduino
#endif 
#define NOISE_LEVEL 4  // Allow small amount of measurement noise


#if (defined(__AVR_ATmega328P__) || defined(__AVR_ATmega32U4__) ||             \
     defined(TEENSYDUINO) || defined(__AVR_ATmega2560__) ||                    \
     defined(__AVR_ATmega4809__)) &&                                           \
    !defined(__IMXRT1062__)
typedef volatile uint8_t RwReg;
#elif defined(ARDUINO_STM32_FEATHER)
typedef volatile uint32 RwReg;
#elif defined(NRF52_SERIES) || defined(ESP32) || defined(ESP8266) ||           \
    defined(ARDUINO_ARCH_STM32) || defined(__IMXRT1062__)
typedef volatile uint32_t RwReg;
#else
typedef volatile uint32_t RwReg;
#endif

#if defined(__AVR__) || defined(TEENSYDUINO) || defined(ARDUINO_ARCH_SAMD)
#define USE_FAST_PINIO
#endif

/** Object that encapsulates the X,Y, and Z/pressure measurements for a touch
 * event. */
class TSPoint {
public:
  TSPoint(void);
  TSPoint(int16_t x, int16_t y, int16_t z);

  bool operator==(TSPoint);
  bool operator!=(TSPoint);

  int16_t x, ///< state variable for the x value
      y,     ///< state variable for the y value
      z;     ///< state variable for the z value
};
/** Object that controls and keeps state for a touch screen. */

class TouchScreen {
public:
  /**
   * @brief Construct a new Touch Screen object
   *
   * @param xp X+ pin. Must be an analog pin
   * @param yp Y+ pin. Must be an analog pin
   * @param xm X- pin. Can be a digital pin
   * @param ym Y- pin. Can be a digital pin
   * @param rx The resistance in ohms between X+ and X- to calibrate pressure
   * sensing
   */
  TouchScreen(uint8_t xp, uint8_t yp, uint8_t xm, uint8_t ym, uint16_t rx);

  /**
   * @brief **NOT IMPLEMENTED** Test if the screen has been touched
   *
   * @return true : touch detected false: no touch detected
   */
  bool isTouching(void);
  uint16_t pressure(void);
  int readTouchY();
  int readTouchX();
  TSPoint getPoint();
  int16_t pressureThreshhold; ///< Pressure threshold for `isTouching`

private:
  uint8_t _yp, _ym, _xm, _xp;
  uint16_t _rxplate;

#if defined(USE_FAST_PINIO)
  volatile RwReg *xp_port, *yp_port, *xm_port, *ym_port;
  RwReg xp_pin, xm_pin, yp_pin, ym_pin;
#endif
};

#endif
```

次にタッチパネルキャリブレーション用ヘッダファイル！？
ポイントを日本語コメントしておく
ファイルの場所は`C:\Users\hiro_\Documents\Arduino\libraries\GUIslice\configs`

```esp-tftespi-default-simple.h
#ifndef _GUISLICE_CONFIG_ARD_H_
#define _GUISLICE_CONFIG_ARD_H_

// =============================================================================
// GUIslice library (example user configuration) for:
//   - CPU:     ESP8266 / ESP32
//   - Display: TFT_eSPI (defined by TFT_eSPI config)
//   - Touch:   Simple Analog (Resistive)
//   - Wiring:  Custom breakout
//              - Pinout defined by TFT_eSPI's User_Setup.h
//
//   - Example display:
//     -
//
// TFT_eSPI Notes:
//   - When using the TFT_eSPI library, there are additional
//     library-specific configuration files that may need
//     customization (including pin configuration), such as
//     "User_Setup_Select.h" (typically located in the
//     Arduino /libraries/TFT_eSPI folder). Please refer to
//     Bodmer's TFT_eSPI library for more details:
//     https://github.com/Bodmer/TFT_eSPI
//
//   - To avoid potential SPI conflicts, it is recommended
//     that SUPPORT_TRANSACTIONS is defined in TFT_eSPI's "User Setup"
//
//   - For touch support by external drivers, the TFT_eSPI's integrated
//     XPT2046 touch driver should be disabled. This can be done by
//     ensuring that TFT_eSPI's User_Setup.h does not define TOUCH_CS
//     (ie. it should be commented out).
//
// DIRECTIONS:
// - To use this example configuration, include in "GUIslice_config.h"
//
// WIRING:
// - As this config file is designed for a breakout board, customization
//   of the Pinout in SECTION 2 will be required to match your display.
//
// =============================================================================
// - Calvin Hass
// - https://github.com/ImpulseAdventure/GUIslice
// =============================================================================
//
// The MIT License
//
// Copyright 2016-2020 Calvin Hass
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// =============================================================================
// \file GUIslice_config_ard.h

// =============================================================================
// User Configuration
// - This file can be modified by the user to match the
//   intended target configuration
// =============================================================================

#ifdef __cplusplus
extern "C" {
#endif // __cplusplus


  // =============================================================================
  // USER DEFINED CONFIGURATION
  // =============================================================================

  // -----------------------------------------------------------------------------
  // SECTION 1: Device Mode Selection
  // - The following defines the display and touch drivers
  //   and should not require modifications for this example config
  // -----------------------------------------------------------------------------
  #define DRV_DISP_TFT_ESPI         // bodmer/TFT_eSPI
  #define DRV_TOUCH_ADA_SIMPLE      // Adafruit_TouchScreen touch driver


  // -----------------------------------------------------------------------------
  // SECTION 2: Pinout
  // -----------------------------------------------------------------------------

  // For TFT_eSPI, the display wiring is defined by TFT_eSPI's User_Setup.h

  // SD Card
  //#define ADAGFX_PIN_SDCS    2 // ESP8266 + Adafruit FeatherWing 2.4"
  #define ADAGFX_PIN_SDCS     14 // ESP32   + Adafruit FeatherWing 2.4"
  //#define ADAGFX_PIN_SDCS    5 // Others  + Adafruit FeatherWing 2.4"

  // -----------------------------------------------------------------------------
  // SECTION 3: Orientation
  // -----------------------------------------------------------------------------

  // Set Default rotation of the display
  // - Values 0,1,2,3. Rotation is clockwise
  #define GSLC_ROTATE     1

  // -----------------------------------------------------------------------------
  // SECTION 4: Touch Handling
  // - Documentation for configuring touch support can be found at:
  //   https://github.com/ImpulseAdventure/GUIslice/wiki/Configure-Touch-Support
  // -----------------------------------------------------------------------------


  // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  // SECTION 4A: Update your pin connections here
  // - These values should come from the diag_ard_touch_calib sketch output
  // - Please update the values to the right of ADATOUCH_PIN_* accordingly
  // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


  // TFT_eSPI: Chip Select for Touch Device
  // - Since we are not using the TFT_eSPI's integrated XPT2046 touch driver,
  //   it is best to disable it. This can be done by ensuring that the TOUCH_CS line
  //   in TFT_eSPI's User_Setup.h is commented out.

  // Set the pinout for the 4-wire resistive touchscreen
  // - These settings describe the wiring between the MCU and the
  //   resistive touch overlay.
  //
  // - The diag_ard_touch_detect sketch can be used to detect the
  //   pin connections (on Arduino devices) for your specific shield.
  //
  // - Definition of the pinout configuration options:
  //     ADATOUCH_PIN_YP      // "Y+": Must be an analog pin
  //     ADATOUCH_PIN_XM      // "X-": Must be an analog pin
  //     ADATOUCH_PIN_YM      // "Y-": Can be a digital pin
  //     ADATOUCH_PIN_XP      // "X+": Can be a digital pin

  // Pin connections from diag_ard_touch_detect:
  // NOTE: The following will need to be adjusted to match your touch overlay
  //       This example pin selection is based on a mcufriend-type UNO shield (ILI9341)
  //       with 8-bit parallel interface pin-sharing with the TFT control signals
  //       hand-wired to an ESP32. For this particular example, the following
  //       TFT_eSPI User_Setup was selected: Setup14_ILI9341_Parallel.h.
// ここの４つの数値は接続するピン番号
  #define ADATOUCH_PIN_YP     14
  #define ADATOUCH_PIN_XM     12
  #define ADATOUCH_PIN_YM     22
  #define ADATOUCH_PIN_XP     21


  // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  // SECTION 4B: Update your calibration settings here
  // - These values should come from the diag_ard_touch_calib sketch output
  // - Please update the values to the right of ADATOUCH_X/Y_MIN/MAX_* accordingly
  // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

  // Calibration settings from diag_ard_touch_calib:
// 以下４つの数値はキャリブレーションで得られた数値に変更する
  #define ADATOUCH_X_MIN    3662
  #define ADATOUCH_X_MAX    545
  #define ADATOUCH_Y_MIN    3875
  #define ADATOUCH_Y_MAX    692
  #define ADATOUCH_REMAP_YX 1    // Some touch controllers may swap X & Y coords

  // Touch overlay resistance value
  // - In most cases, this value can be left as-is
  #define ADATOUCH_RX       300   // "rxplate"

  // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  // SECTION 4D: Additional touch configuration
  // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

  // Define pressure threshold for detecting a touch
  // - Specifying this range helps eliminate some erroneous touch events
  //   resulting from noise in the touch overlay detection
  // - For config details, please see:
  //   https://github.com/ImpulseAdventure/GUIslice/wiki/Configuring-Touch-Pressure
  #define ADATOUCH_PRESS_MIN  10
  #define ADATOUCH_PRESS_MAX  4000

  // -----------------------------------------------------------------------------
  // SECTION 5: Diagnostics
  // -----------------------------------------------------------------------------

  // Error reporting
  // - Set DEBUG_ERR to >0 to enable error reporting via the Serial connection
  // - Enabling DEBUG_ERR increases FLASH memory consumption which may be
  //   limited on the baseline Arduino (ATmega328P) devices.
  //   - DEBUG_ERR 0 = Disable all error messaging
  //   - DEBUG_ERR 1 = Enable critical error messaging (eg. init)
  //   - DEBUG_ERR 2 = Enable verbose error messaging (eg. bad parameters, etc.)
  // - For baseline Arduino UNO, recommended to disable this after one has
  //   confirmed basic operation of the library is successful.
  #define DEBUG_ERR               1   // 1,2 to enable, 0 to disable

  // Debug initialization message
  // - By default, GUIslice outputs a message in DEBUG_ERR mode
  //   to indicate the initialization status, even during success.
  // - To disable the messages during successful initialization,
  //   uncomment the following line.
  //#define INIT_MSG_DISABLE

  // -----------------------------------------------------------------------------
  // SECTION 6: Optional Features
  // -----------------------------------------------------------------------------

  // Enable of optional features
  // - For memory constrained devices such as Arduino, it is best to
  //   set the following features to 0 (to disable) unless they are
  //   required.
  #define GSLC_FEATURE_COMPOUND       0   // Compound elements (eg. XSelNum)
  #define GSLC_FEATURE_XTEXTBOX_EMBED 0   // XTextbox control with embedded color
  #define GSLC_FEATURE_INPUT          0   // Keyboard / GPIO input control

  // Enable support for SD card
  // - Set to 1 to enable, 0 to disable
  // - Note that the inclusion of the SD library consumes considerable
  //   RAM and flash memory which could be problematic for Arduino models
  //   with limited resources.
  #define GSLC_SD_EN    0

  // Enable support for SPIFFS File System access
  // - Set to 1 to enable, 0 to disable
  // - Note that this requires the inclusion of TFT_eFEX library
  #define GSLC_SPIFFS_EN               0 


  // =============================================================================
  // SECTION 10: INTERNAL CONFIGURATION
  // - The following settings should not require modification by users
  // =============================================================================

  // -----------------------------------------------------------------------------
  // Touch Handling
  // -----------------------------------------------------------------------------

  // Define the maximum number of touch events that are handled
  // per gslc_Update() call. Normally this can be set to 1 but certain
  // displays may require a greater value (eg. 30) in order to increase
  // responsiveness of the touch functionality.
  #define GSLC_TOUCH_MAX_EVT    1

  // -----------------------------------------------------------------------------
  // Misc
  // -----------------------------------------------------------------------------

  // Define buffer size for loading images from SD
  // - A larger buffer will be faster but at the cost of RAM
  #define GSLC_SD_BUFFPIXEL   50

  // Enable support for graphics clipping (DrvSetClipRect)
  // - Note that this will impact performance of drawing graphics primitives
  #define GSLC_CLIP_EN 1

  // Enable for bitmap transparency and definition of color to use
  #define GSLC_BMP_TRANS_EN     1               // 1 = enabled, 0 = disabled
  #define GSLC_BMP_TRANS_RGB    0xFF,0x00,0xFF  // RGB color (default: MAGENTA)

  #define GSLC_USE_FLOAT        0   // 1=Use floating pt library, 0=Fixed-point lookup tables

  #define GSLC_DEV_TOUCH ""
  #define GSLC_USE_PROGMEM      0

  #define GSLC_LOCAL_STR        0   // 1=Use local strings (in element array), 0=External
  #define GSLC_LOCAL_STR_LEN    30  // Max string length of text elements

  // -----------------------------------------------------------------------------
  // Debug diagnostic modes
  // -----------------------------------------------------------------------------
  // - Uncomment any of the following to enable specific debug modes
  //#define DBG_LOG           // Enable debugging log output
  //#define DBG_TOUCH         // Enable debugging of touch-presses
  //#define DBG_FRAME_RATE    // Enable diagnostic frame rate reporting
  //#define DBG_DRAW_IMM      // Enable immediate rendering of drawing primitives
  //#define DBG_DRIVER        // Enable graphics driver debug reporting


  // =============================================================================

#ifdef __cplusplus
}
#endif // __cplusplus
#endif // _GUISLICE_CONFIG_ARD_H_
```
# 実行
使用したサンプルスケッチは TFT_eSPI → 320x240 → TFT_graphicstest_one_lib 
を読み込み実行
![20230330_161147.JPG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3118608/a1f64297-00f7-76c8-9c06-caa4593bff41.jpeg)
動きました！
最初のほうでグラフィック描画テストがあるのですが、無茶苦茶速い！
あとは漢字を表示したい。
タッチスクリーンは値を得ることまでは成功しました。
これらは後日記事書く予定です。
# 動作確認動画
スケッチ例を実行した動画です。
<iframe width="1317" height="481" src="https://www.youtube.com/embed/tKjIc-yxjf4" title="ESP32でILI9341(パラレル)LCDを動かす 1" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>

<iframe width="320" height="560" src="https://www.youtube.com/embed/B9ZrjqzNA6w" title="ESP32でILI9341(パラレル)LCDを動かす 2" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>