Skip to content

Instantly share code, notes, and snippets.

@ShayBox
Created July 6, 2023 04:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShayBox/5f73273e0fafd638ab2fb918a7222a61 to your computer and use it in GitHub Desktop.
Save ShayBox/5f73273e0fafd638ab2fb918a7222a61 to your computer and use it in GitHub Desktop.
Temporary low voltage detection using standard deviation for RPI Pico W & CircuitPython
import analogio
import board
import math
import time
voltage = analogio.AnalogIn(board.VOLTAGE_MONITOR)
voltage_conversion_factor = 3 * 3.3 / 65535
def calculate_mean(data):
return sum(data) / len(data)
def calculate_std_dev(data, mean):
variance = sum((x - mean) ** 2 for x in data) / len(data)
return math.sqrt(variance)
threshold_outlier = -5
threshold_normal = -10
voltage_history = []
voltage_low = False
while len(voltage_history) < 1000:
voltage_history.append(voltage.value * voltage_conversion_factor)
while True:
battery_voltage = voltage.value * voltage_conversion_factor
voltage_history_copy = voltage_history[:]
voltage_history_copy.append(battery_voltage)
voltage_average = calculate_mean(voltage_history_copy)
voltage_std_dev = calculate_std_dev(voltage_history_copy, voltage_average)
z_scores = [(x - voltage_average) / voltage_std_dev for x in voltage_history_copy]
if any(z_score < threshold_outlier for z_score in z_scores):
if not voltage_low:
voltage_low = True
print("Low voltage outlier detected!")
else:
voltage_history = voltage_history_copy
if voltage_low:
voltage_low = False
print("Voltage back to normal.")
if len(voltage_history) > 1000:
voltage_history.pop(0)
print(f"Voltage: {battery_voltage:0.02f} | Average: {voltage_average:0.02f}")
time.sleep(0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment