#include "DFRobot_GDL.h"
#include "DFRobot_Heartrate.h"

/*M0*/
#if defined ARDUINO_SAM_ZERO
#define TFT_DC  7
#define TFT_CS  5
#define TFT_RST 6
/*ESP32 and ESP8266*/
#elif defined(ESP32) || defined(ESP8266)
#define TFT_DC  D3
#define TFT_CS  D4
#define TFT_RST D5
/*AVR series board*/
#else
#define TFT_DC  2
#define TFT_CS  3
#define TFT_RST 4
#endif

#define heartratePin A1

DFRobot_ST7789_240x320_HW_SPI screen(/*dc=*/TFT_DC,/*cs=*/TFT_CS,/*rst=*/TFT_RST);
DFRobot_Heartrate heartrate;


uint8_t heart[32]={0}; 
uint16_t origin_x = 0;
uint16_t origin_y = 240;
uint8_t count = 0;


void setup(){
  Serial.begin(115200);
  screen.begin();
  heartrate.begin(DIGITAL_MODE);
  screen.setRotation(1);
  screen.fillScreen(COLOR_RGB565_BLACK);
}

void loop() {
  uint8_t rateValue;
  screen.drawRect(0,0,320,50,COLOR_RGB565_WHITE);
  screen.drawFastVLine(130,0,50,COLOR_RGB565_WHITE);
  //set font size to 4, range 1 to 4
  screen.setTextSize(2);
  screen.setFont(&FreeMonoOblique12pt7b);
  screen.setCursor(/*x=*/5,/*y=*/35);
  screen.setTextColor(COLOR_RGB565_ORANGE); 
  screen.setTextWrap(true); 
  screen.print("Rate");
  screen.setCursor(/*x=*/180,/*y=*/35);
  //heartrate.getValue(heartratePin); ///< A1 foot sampled values
  rateValue = heartrate.getRate(A1); ///< Get heart rate value
    screen.fillRect(131,1,188,48,COLOR_RGB565_BLACK);
  screen.print(rateValue); 
  if(rateValue && rateValue > 60 && rateValue <110)  {
    Serial.println(rateValue);
  }
  else{
    return ;
    }
  
  if(count <= 32){
    heart[count] = (rateValue - 50)*5 ;
    count++;
    if((count - 1) == 0) return ;
       
       screen.drawLine(origin_x+10*(count-2),origin_y - heart[count - 2],origin_x+10*(count-1),origin_y - heart[count-1],0xf800);
    } else {
   screen.fillRect(0,100,320,100,COLOR_RGB565_BLACK);
  for(uint8_t i = 0 ;i < 31 ;i++){
    heart[i] = heart[i+1];
    }
    heart[31] = (rateValue - 50)*5;

  
  for(uint8_t i = 0 ;i < 31 ;i++){
     screen.drawLine(origin_x+10*i,origin_y - heart[i],origin_x+10*(i+1),origin_y - heart[i+1],0xf800);
    }
    }
  //delay(20);
}
