#include <Arduino.h>
#line 1 "/mnt/Data/bach/Electronic/boxmod/BoxmodFirmware/BoxmodFirmware.ino"
#include "src/Btn/Btn.h"
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Fonts/FreeSans9pt7b.h>

#define SSD1306_NO_SPLASH
#define SCREEN_WIDTH 96
#define SCREEN_HEIGHT 16
#define OLED_RESET    -1  // Pas de reset matériel
#define SCREEN_ADDRESS 0x3C  // Adresse I2C (à confirmer avec un scanner I2C)

#define LED_PIN 18

int bat_prct = 100;
float coil_res = 1.1;
float coil_pw = 17.8;

Btn plusBtn(6, 50);
Btn moinsBtn(7, 50);
Btn fireBtn(17, 50);

int batVcheckActivatePin = 42;
int batVcheckMesurePin = 14;


Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#line 29 "/mnt/Data/bach/Electronic/boxmod/BoxmodFirmware/BoxmodFirmware.ino"
void setup();
#line 48 "/mnt/Data/bach/Electronic/boxmod/BoxmodFirmware/BoxmodFirmware.ino"
void drawScreen();
#line 81 "/mnt/Data/bach/Electronic/boxmod/BoxmodFirmware/BoxmodFirmware.ino"
void loop();
#line 29 "/mnt/Data/bach/Electronic/boxmod/BoxmodFirmware/BoxmodFirmware.ino"
void setup() {
  SerialUSB.begin(115200);
  // while (!SerialUSB);             // Leonardo: wait for serial monitor
  SerialUSB.println("\nBoxmodFirmware");

  pinMode(LED_PIN, OUTPUT);
  analogWrite(LED_PIN, 0);

  if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {  
    SerialUSB.println(F("Échec de l'initialisation de l'écran OLED"));
    // while (true);  // Boucle infinie en cas d'échec
  }

  display.clearDisplay();
  delay(500);
  display.setRotation(2);
}


void drawScreen() {
  display.clearDisplay();


  display.setTextColor(SSD1306_WHITE); 
  
  // battery
  display.setTextSize(1);      
  display.setCursor(0, 0);     
  display.print(String(bat_prct)+"%");
  // display.drawRect(0, 0, 39, 69, SSD1306_WHITE);  // Rectangle vide
  // display.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SSD1306_WHITE);  // Rectangle rempli

  // coil resistance
  display.setTextSize(1);
  display.setCursor(0, 8);
  // display.print(String(coil_res)+"Ω");
  char coil_res_output[3];  // Adjust size accordingly
  sprintf(coil_res_output, "%.1f\xE9", coil_res);  // Format float with 1 decimal place
  display.print(coil_res_output);
  
  // power
  display.setTextSize(2);
  display.setCursor(30, 0);     
  // display.print(String(coil_pw)+"W");
  char coil_pw_output[4];  // Adjust size accordingly
  sprintf(coil_pw_output, "%.1fw", coil_pw);  // Format float with 1 decimal place
  display.print(coil_pw_output);
  
  display.display();  // Rafraîchir l'écran

}

void loop() {
  if(plusBtn.getStateOnce() == 0){
    SerialUSB.println("Plus");
    coil_pw+=0.1;
    if (coil_pw >= 20){
      coil_pw = 20;
    }
  }

  if(moinsBtn.getStateOnce() == 0){
    SerialUSB.println("Moins");
    coil_pw-=0.1;
    if (coil_pw <= 5){
      coil_pw = 5;
    }
    
  }

  if(fireBtn.getState() == 0){
    analogWrite(LED_PIN, 255);
  }else{
    analogWrite(LED_PIN, 0);
  }

  drawScreen();
}

