#include <TFT_eSPI.h>
#include <SPI.h>
#include <Wire.h>
#include "bmp.h"

#define device_A_CS  6              
#define device_B_CS  10 

TFT_eSPI tft_left = TFT_eSPI(160, 160);  // 左屏
TFT_eSPI tft_right = TFT_eSPI(160, 160); // 右屏

void setup()
{
    Serial.begin(9600);
    Serial.println("Start");

    pinMode (device_A_CS, OUTPUT);
    pinMode (device_B_CS, OUTPUT);

    digitalWrite (device_A_CS, LOW);                                             // we need to 'init' all displays
    digitalWrite (device_B_CS, LOW);

    tft_left.init();
    tft_left.setRotation(2);
    tft_left.fillScreen(TFT_RED);

    tft_right.init();
    tft_right.setRotation(2);
    tft_right.fillScreen(TFT_RED);

    tft_left.setSwapBytes(true);
    tft_right.setSwapBytes(true);

    // 显示左眼和右眼的图像
    showImage(0, 0, 160, 160, bmp1, &tft_left);  // 显示左眼图像
    showImage(0, 0, 160, 160, bmp1, &tft_right); // 显示右眼图像
  

    digitalWrite (device_A_CS, HIGH);                                          
    digitalWrite (device_B_CS, HIGH);    
}


#define PI_BUF_SIZE 9200
void showImage(int32_t x, int32_t y, int32_t w, int32_t h, const uint16_t *data, TFT_eSPI *tft) {
    int32_t dx = 0;
    int32_t dy = 0;
    int32_t dw = w;
    int32_t dh = h;

    // 确保显示区域不超出屏幕范围
    if (x < 0) { dw += x; dx = -x; x = 0; }
    if (y < 0) { dh += y; dy = -y; y = 0; }

    // 限制宽高不超过屏幕的160x160尺寸
    if (x + dw > 160) dw = 160 - x;
    if (y + dh > 160) dh = 160 - y;

    // 如果宽高无效，直接返回
    if (dw < 1 || dh < 1) return;

    CS_L;

    // 跳过不需要的数据部分，调整到正确的起始位置
    data += (dy * w + dx);

    uint16_t buffer[PI_BUF_SIZE];
    uint16_t* pix_buffer = buffer;
    uint16_t high, low;

    // 设置显示区域的窗口
    tft->setWindow(x, y, x + dw - 1, y + dh - 1);

    // 计算完整缓冲区数量
    uint16_t nb = (dw * dh) / PI_BUF_SIZE;

    // 填充并发送缓冲区数据
    for (int32_t i = 0; i < nb; i++) {
        for (int32_t j = 0; j < PI_BUF_SIZE; j++) {
            high = pgm_read_word(&data[(i * PI_BUF_SIZE * 2) + 2 * j + 1]);
            low = pgm_read_word(&data[(i * PI_BUF_SIZE * 2) + 2 * j]);
            pix_buffer[j] = (high << 8) + low;
        }
        tft->pushPixels(pix_buffer, PI_BUF_SIZE);
    }

    // 处理剩余的部分
    uint16_t np = (dw * dh) % PI_BUF_SIZE;

    if (np) {
        for (int32_t i = 0; i < np; i++) {
            high = pgm_read_word(&data[(nb * PI_BUF_SIZE * 2) + 2 * i + 1]);
            low = pgm_read_word(&data[(nb * PI_BUF_SIZE * 2) + 2 * i]);
            pix_buffer[i] = (high << 8) + low;
        }
        tft->pushPixels(pix_buffer, np);
    }

    CS_H;
}


void loop() {
  // put your main code here, to run repeatedly:

}
