// created by upir, 2023
// youtube channel: https://www.youtube.com/upir_upir


#include "U8g2lib.h" // include u8g2 library for drawing on the OLED display

U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0); // ["F" = full framebuffer, size = 1024 bytes, hardware I2C connection]

byte audio_bar_height[7]; // sizes for the individual bars
byte audio_bar_peak[7]; // positions for the individual peaks (lines over the bars)

const unsigned char upir_logo [] PROGMEM = {    // upir logo
  0xEA, 0x3A, 0xAA, 0x28, 0x6A, 0x1A, 0x26, 0x2A, };

void setup() {
  u8g2.setColorIndex(1);  // set the color to white
  u8g2.begin(); // start the u8g2 library/display
}


void loop() { // main loop

  u8g2.clearBuffer();  // clear buffer for storing display content in RAM

  for (int i=0; i<7; i++) { // loop for every fraquency (63Hz, 160Hz, 400Hz, 1kHz, 2.5kHz, 6.25kHz and 16kHz)

    int random_value = random(1024); // calculate random value between 0-1024
    audio_bar_height[i] = audio_bar_height[i] + ((map(random_value, 0, 1024, 0, 53) - audio_bar_height[i]) / 4.0); // update the bar with a new value (slowly)

    // calculate the peak position
    if (audio_bar_peak[i] < audio_bar_height[i]) { // if the peak is below the current bar size
      audio_bar_peak[i] = audio_bar_height[i]; // move peak to the new max. position (i.e. size of the bar)
    } else if (audio_bar_peak[i] > audio_bar_height[i]) { // if the bar is lower than the peak
      audio_bar_peak[i]--; // slowly move the peak down, one pixel every frame
    }

    u8g2.drawBox(2 + i*19, 53-audio_bar_height[i], 10, audio_bar_height[i]); // draw bar

    u8g2.drawBox(2 + i*19, 53-audio_bar_peak[i], 10, 1); // draw peak
  }

  // draw the individual labels
  u8g2.setFont(u8g2_font_nerhoe_tr); // set font
  u8g2.drawStr(  2, 64, "63"); 
  u8g2.drawStr( 19, 64, "160"); 
  u8g2.drawStr( 37, 64, "400"); 
  u8g2.drawStr( 60, 64, "1K"); 
  u8g2.drawStr( 75, 64, "2.5K"); 
  u8g2.drawStr( 95, 64, "6.3K"); 
  u8g2.drawStr(115, 64, "16K");        

  u8g2.drawXBMP(0, 0, 16, 4, upir_logo);  // draw upir logo

  u8g2.sendBuffer(); // send buffer from RAM to display controller
}