Newer
Older
Heltec_WiFi_Kit_8 / BatteryMeters.ino
root on 15 Jun 2 KB Initial commit
#include <Arduino.h>
#include <U8g2lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

U8G2_SSD1306_128X32_UNIVISION_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ 16, /* clock=*/ 5, /* data=*/ 4);
ADC_MODE(ADC_VCC);

void setup() {
  Serial.begin(115200);

  // screen stuff (128 x 32 px)
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  digitalWrite(10, 0);
  digitalWrite(9, 0);   
  u8g2.begin();  
  u8g2.enableUTF8Print(); 

  Serial.println("Setup done");

  getBatteryLevel();
  
  delay(100);
}

int getBatteryLevel() { 
  uint32_t getVcc = ESP.getVcc();
  Serial.println(getVcc);
  float measuredvbat = getVcc; // for actual voltage
  measuredvbat /= 1024; // convert to voltage 
  Serial.println(measuredvbat);

  int percent = map(getVcc, 2300, 3000, 0, 100); // turn vcc into batt perentage (yea I know it's not that accurate due to dropoff rate)
  return percent; 
  //return 30; //DEBUG
}

void smallText(int percent){
  String batvol = "";
  batvol += percent;
  batvol += "%";
  char batChr2[batvol.length()+1]; 
  batvol.toCharArray(batChr2, batvol.length()+1);

  u8g2.setFont(u8g2_font_8x13_mf); 
  u8g2.drawStr(70,25,batChr2);
}

void smallBottomRightIcon(int percent){
  percent = map(percent, 0, 100, 1, 11);
  if(percent > 11){ percent = 11; }
  if(percent < 1){ percent = 1; }
  
  u8g2.setFont(u8g_font_unifont);
  //u8g.setFont(u8g_font_osb21);
  u8g2.drawFrame(111,24,15,8);
  u8g2.drawBox(113,26,percent,4); //3rd param is %(1-11)
  u8g2.drawBox(126,26,2,4);
}

void topBar(int percent){
  percent = map(percent, 0, 100, 1, 128);
  if(percent > 128){ percent = 128; }
  if(percent < 1){ percent = 1; }

  u8g2.drawLine(128-percent,0, 128, 0);
}

void gauge(int percent){
  int arc=10;
  uint8_t angle = map(percent,0,100,0,90);  
  if (angle<45){                                   
    angle=angle+135;
  }else{
    angle=angle-45;
  }
  float x1=sin(2*angle*2*3.14/360);              
  float y1=cos(2*angle*2*3.14/360); 
  u8g2.drawLine(40, 32, 40+arc*x1, 32-arc*y1);
  
  u8g2.drawCircle(40, 32, 15, U8G2_DRAW_UPPER_LEFT);
  u8g2.drawCircle(40, 32, 15, U8G2_DRAW_UPPER_RIGHT);
}

void loop() {
  u8g2.clearBuffer(); 
  int percent = getBatteryLevel();
  
  smallBottomRightIcon(percent);
  topBar(percent);
  gauge(percent);
  smallText(percent);
  
  u8g2.sendBuffer();
  delay(1000);
}