#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <SPI.h>
#include <Button.h>
#include <math.h>

#define TFT_DC 2
#define TFT_CS 15
#define BUTTON_SIN 0   // Broche GPIO 0 pour le bouton sin
#define BUTTON_COS 5   // Broche GPIO 5 pour le bouton cos
#define TFT_WIDTH 320
#define TFT_HEIGHT 240
#define NUM_PERIODS 4 // Nombre de périodes à afficher

volatile bool sinSelected = false;
volatile bool cosSelected = false;
volatile bool signalDisplayed = false;
int drawDelay = 10; // Délai initial entre les itérations de dessin

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
Button buttonSin(BUTTON_SIN);
Button buttonCos(BUTTON_COS);

void setup() {
  Serial.begin(9600);
  tft.begin();
  tft.setRotation(1);
  tft.fillScreen(ILI9341_BLACK);
  tft.setTextColor(ILI9341_WHITE);
  tft.setTextSize(2);

  buttonSin.begin();
  buttonCos.begin();

  attachInterrupt(BUTTON_SIN, sinSelectedInterrupt, FALLING);
  attachInterrupt(BUTTON_COS, cosSelectedInterrupt, FALLING);
}

void loop() {
  if (sinSelected && !signalDisplayed) {
    Serial.println("Bouton sin sélectionné");
    sinSelected = false;
    signalDisplayed = true;
    displaySignal(sinWave);
  }

  if (cosSelected && !signalDisplayed) {
    Serial.println("Bouton cos sélectionné");
    cosSelected = false;
    signalDisplayed = true;
    displaySignal(cosWave);
  }
}

void sinSelectedInterrupt() {
  sinSelected = true;
}

void cosSelectedInterrupt() {
  cosSelected = true;
}

void displaySignal(float (*waveFunction)(float)) {
  for (int period = 0; period < NUM_PERIODS; period++) {
    float periodStart = 2 * PI * period;
    float periodEnd = 2 * PI * (period + 1);
    tft.fillScreen(ILI9341_BLACK);
    drawAxes();
    float xPrev = periodStart;
    float yPrev = (*waveFunction)(xPrev) * (TFT_HEIGHT / 4) + TFT_HEIGHT / 2;
    for (float x = periodStart + 0.1; x < periodEnd; x += 0.1) {
      float y = (*waveFunction)(x) * (TFT_HEIGHT / 4) + TFT_HEIGHT / 2;
      tft.drawLine((xPrev - periodStart) * (TFT_WIDTH / (2 * PI)), yPrev, (x - periodStart) * (TFT_WIDTH / (2 * PI)), y, ILI9341_GREEN);
      xPrev = x;
      yPrev = y;
      delay(drawDelay);
    }
  }
}

float sinWave(float x) {
  return sin(x);
}

float cosWave(float x) {
  return cos(x);
}

void drawAxes() {
  tft.drawLine(0, TFT_HEIGHT / 2, TFT_WIDTH - 1, TFT_HEIGHT / 2, ILI9341_WHITE);
  tft.drawLine(TFT_WIDTH / 2, 0, TFT_WIDTH / 2, TFT_HEIGHT - 1, ILI9341_WHITE);
}
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK
lcd1:VCC
lcd1:GND
lcd1:CS
lcd1:RST
lcd1:D/C
lcd1:MOSI
lcd1:SCK
lcd1:LED
lcd1:MISO
btn1:1.l
btn1:2.l
btn1:1.r
btn1:2.r
btn2:1.l
btn2:2.l
btn2:1.r
btn2:2.r
btn3:1.l
btn3:2.l
btn3:1.r
btn3:2.r
btn4:1.l
btn4:2.l
btn4:1.r
btn4:2.r