#include <Arduino.h>
#include <U8g2lib.h>
#include <SPI.h>
#include <Wire.h>
//U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, 13, 11, 10, 8);
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
//Definicije
int analogValue = analogRead(A7);
const float BETA = 3950;
char buffer[32];
char voltage_buffer[32];
char str_celsius[10];
char str_voltage[10];
const char DEGREE_SYMBOL[] = { 0xB0, '\0' };
const int WINDOW_SIZE = 20;
int INDEX = 0;
int VALUE = 0;
int SUM = 0;
int READINGS[WINDOW_SIZE];
int AVERAGED = 0;
void setup() {
// put your setup code here, to run once:
u8g2.begin();
u8g2.enableUTF8Print();
}
void loop() {
get_coolant_temp();
get_voltage();
u8g2.firstPage();
do {
//Draw static layout
set_outline();
//Coolant temperature monitor settings
u8g2.setFont(u8g2_font_profont22_tr);
sprintf(buffer, "%s", str_celsius);
u8g2.drawStr(105-u8g2.getStrWidth(buffer), 29, buffer);
u8g2.setFont(u8g2_font_helvB12_tf);
u8g2.drawUTF8(106, 27, DEGREE_SYMBOL);
u8g2.setFont(u8g2_font_profont22_tr);
u8g2.drawStr(112, 29, "C");
//Voltage monitor settings
u8g2.setFont(u8g2_font_profont22_tr);
sprintf(voltage_buffer, "%sV", str_voltage);
u8g2.drawStr(61-u8g2.getStrWidth(voltage_buffer), 28, voltage_buffer);
//Ambient monitor settings
u8g2.drawStr(9, 59, "22°C");
} while ( u8g2.nextPage() );
delay(1000);
}
void set_outline(void)
{
u8g2.setBitmapMode(1);
u8g2.setFontMode(1);
u8g2.drawFrame(0, 0, 64, 32);
u8g2.drawFrame(63, 31, 65, 33);
u8g2.drawFrame(63, 0, 65, 32);
u8g2.drawFrame(0, 31, 64, 33);
u8g2.setFont(u8g2_font_5x8_mf);
u8g2.setFontMode(0);
u8g2.setDrawColor(0);
u8g2.drawStr(1, 8, "Voltage");
u8g2.drawStr(1, 39, "Ambient");
u8g2.drawStr(64, 8, "Coolant temp");
u8g2.setFontMode(1);
u8g2.setDrawColor(1);
}
float get_voltage(void)
{
float voltage = analogRead(A6)*(12.0 / 1023.0);
dtostrf(voltage, 2, 1, str_voltage);
}
int get_coolant_temp(void)
{
int celsius = 1 / (log(1. / (1023. / analogRead(A7) - 1)) / BETA + 1.0 / 298.15) - 273.15;
//itoa(celsius, str_celsius, 10);
// dtostrf(celsius, 2, 1, str_celsius);
//return celsius;
SUM = SUM - READINGS[INDEX]; // Remove the oldest entry from the sum
VALUE = celsius; // Read the next sensor value
READINGS[INDEX] = VALUE; // Add the newest reading to the window
SUM = SUM + VALUE; // Add the newest reading to the sum
INDEX = (INDEX+1) % WINDOW_SIZE; // Increment the index, and wrap to 0 if it exceeds the window size
AVERAGED = SUM / WINDOW_SIZE; // Divide the sum of the window by the window size for the result
itoa(AVERAGED, str_celsius, 10); // Convert integer to array
}