// ********************
// voltmeter for teaching purposes at the HTL Anichstraße,
// Department of Biomedicine and Health Technology.
// To simulate different input voltage a potentiomenter is used
//Note: This code is only for understanding and learning the programming.
// Due to the complex calculation of mean values, it is not designed to be resource-efficient.
// ********************
//Import Lib for the I2C Display
#include <LiquidCrystal_I2C.h>
//I2C Adress and column and line defintion for the used LCD
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
// create LCD-object based on the importet Lib
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
// definte input port for voltage measurement (potentiometer)
int analogPin = 26;
// Help variables for programming to store and print the
// analog values resp. voltage values
int analogValue = 0;
float voltageValue = 0.0;
String outputString = "";
const int numReadings = 5;
float sensorReadings[numReadings]; // Array zur Aufbewahrung der letzten Sensorwerte
int indexArray = 0; // Index für das Array
//setup (runs once) to initialize the ports
void setup() {
Serial.begin(115200);
// init (start) LCD
lcd.init();
// Turn on the backlight on LCD.
lcd.backlight();
// print the Message on the LCD on the first line.
lcd.print ("Voltmeter v1.0");
Serial.println("Voltmeter v1.0");
}
void loop() {
delay(10); // this speeds up the simulation for Wokwi only
//read the analog value and calculate the voltage
// ESP32: ADW 3.3V input range, 10-Bit resolution
analogValue = analogRead(analogPin);
voltageValue = float(analogValue * 3.3 ) / 4096.0;
// Aktualisiere das Array mit den letzten Sensorwerten
sensorReadings[indexArray] = voltageValue;
indexArray = (indexArray + 1) % numReadings;
float averageVoltage = calculateMean(sensorReadings, numReadings); // Berechne den Durchschnitt
//print to display on the second line
lcd.setCursor (0, 1);
//create the outputstring: Voltage value and Unit
//and print to LCD and serial output
outputString = String(averageVoltage) + "V";
lcd.print (outputString);
Serial.println(outputString);
Serial.println(sensorReadings[0]);
//wait 500ms until reading an new value
delay(500);
}
float calculateMean(float array[], int length) {
if (length <= 0) {
return 0;
}
float sumArray = 0;
// Sum all elements
for (int i = 0; i < length; ++i) {
sumArray += array[i];
}
// calculate mean an return
return sumArray / length;
}