/*############################################################################
  # Codigo criado por: MarioParente
  # Em desenvolvimento
  # Data: 27/12/2023
  # Detalhes do projeto: v0.1.1
  # Hardware: Display OLED e ATtint85
  ############################################################################*/
/*

  Obs.: Devido ao Wokwi não possuir OLED 128x32
  O oled 128x64 está sendo usado.

  Anotação.
  V   V   V

Vin 
33K (Resistor)
Attint_pin_A2 (PB4)
1k (Resistor)
GND

*/

#include <TinyWireM.h>
#include <Tiny4kOLED.h>

float Mult = 1; // (taxa de multiplicação)

void setup() {
  oled.begin(128, 64, sizeof(tiny4koled_init_128x64br), tiny4koled_init_128x64br); //Para utilizar no WOKWI
//oled.begin(128, 32, sizeof(tiny4koled_init_128x32br), tiny4koled_init_128x32br); //Para utilizar no Projeto real
  oled.setFont(FONT6X8); // fontes disonivel FONT8X16 e FONT6X8
  oled.clear();
  oled.on();
  Inicio();
  delay(100);
}

void Inicio(){
  // Apagar daqui
  oled.setCursor(0, 4);
  oled.startData();
  oled.repeatData(0b00000001,(127/2));
  oled.sendData(0b11111111);
  oled.repeatData(0b00000001,(127/2-1));
  oled.endData();
  // Até aqui

  oled.setCursor(0, 0);
  oled.print(F("Mini Voltimetro  tiny"));

  oled.setCursor(93, 0);
  oled.startData();
  oled.sendData(0b01111100);
  oled.sendData(0b00010010);
  oled.sendData(0b00010001);
  oled.sendData(0b00010010);
  oled.sendData(0b01111100);
  oled.repeatData(0b00000001,2);
  oled.sendData(0b01111111);
  oled.repeatData(0b00000001,2); 
  oled.endData();
}

void loop() {
  oled.setCursor(0, 1);
  oled.print("A2: ");
  oled.print(med(2),2);

  oled.print("V   A3: ");
  oled.print(med(3),2);
  oled.print("V");

  oled.setCursor(0, 2);
  oled.print("A2 Max ");
  oled.print(int(readVcc()/1000));
  oled.print("V | A3 Max 5V");

  oled.setCursor(0, 3);
  oled.print("VCC in: ");
  oled.print(float(readVcc()/1000),3);
  oled.print("V");

  delay(500);
}

float med(int x) {
  float V = (readVcc() / 1000.0) / 5 * (analogRead(x) * 5.0 / 1024.0) * Mult;
  return V;
}

long readVcc() {
  long result;
  // Leia a referência de 1,1 V contra AVcc
  #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
  ADMUX = _BV(MUX5) | _BV(MUX0);
  #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
  ADMUX = _BV(MUX3) | _BV(MUX2);
  #else
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  #endif
  delay(2);                                                // Aguarde Vref resolver
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA, ADSC));
  result = ADCL;
  result |= ADCH << 8;
  result = 1125300L / result;                              // Calcular Vcc (em mV); 1126400 = 1,1*1024*1000
  return result;
}

/*

  result = 1126400L / result; 

*/
ATTINY8520PU