Skip to content

Instantly share code, notes, and snippets.

@Olikonsti
Created November 5, 2022 19:54
Show Gist options
  • Save Olikonsti/483432fe2f70074af1b1162ce5fd09e9 to your computer and use it in GitHub Desktop.
Save Olikonsti/483432fe2f70074af1b1162ce5fd09e9 to your computer and use it in GitHub Desktop.
#include <LiquidCrystal_I2C.h>
#define NUM_SAMPLES_V 30
#define NUM_SAMPLES_C
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <Arduino.h>
LiquidCrystal_I2C lcd(0x27,20,4);
double calibration_v;
double vb; //voltage battery
double cl; //current load
double vp; //panel voltage
double cp; //panel current
double pp; //panel power
double pl; //load power
static const unsigned long REFRESH_INTERVAL = 1000; // ms
static unsigned long lastRefreshTime = 0;
void setup() {
Serial.begin(9600);
lcd.init();
lcd.backlight();
}
void loop() {
if (Serial.available() > 0) {
String data = Serial.readStringUntil('\n');
}
calibration_v = 331;//analogRead(A0);
vb = get_voltage(A1);
cl = get_current(A6);
vp = get_voltage(A2);
cp = get_current(A3);
pp = vp * cp;
pl = vb * cl;
if(millis() - lastRefreshTime >= REFRESH_INTERVAL){
lastRefreshTime += REFRESH_INTERVAL;
serial_send();
update_display();
}
}
void serial_send(){
Serial.println("{'vb': " + String(vb) + ", 'cl': " + String(cl) + ", 'vp': " + String(vp) + ", 'cp': " + String(cp) + ", 'pp': " + String(pp) + ", 'pl': " + String(pl) + "}");
//Serial.println(cl);
}
void update_display(){
lcd.setCursor(0, 0);
lcd.print("VB " + String(vb) + " CL " + String(cl));
lcd.setCursor(0, 1);
lcd.print("VCal " + String(calibration_v));
lcd.setCursor(0, 2);
lcd.print("VP " + String(vp) + " CP " + String(cp));
lcd.setCursor(0, 3);
lcd.print("PP " + String(pp) + " PL " + String(pl));
}
double get_voltage(int pin){
int sample_count = 0;
int sum = 0;
while (sample_count < NUM_SAMPLES_V) {
sum += analogRead(pin);
sample_count++;
delay(2);
}
double voltage = (((float)sum / (float)NUM_SAMPLES_V) * 5.0) / 1024.0;
return voltage*(4 + calibration_v/1000); //4.587
}
double get_current(int pin){
double sample_count = 0;
double sum = 0.0;
float volt_c = analogRead(pin)*5/1023.0;
float current_T = (volt_c-2.5)/0.66;
delay(2);
float current = current_T;
return current*10;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment