import time
from machine import Pin, ADC
sensor_pin = ADC(Pin(34))
sensor_pin.atten(ADC.ATTN_11DB)
sensor_pin.width(ADC.WIDTH_12BIT)
WINDOW_SIZE = 10
RAW_SAMPLE_INTERVAL = 200
REPORT_INTERVAL = 5000
ANOMALY_THRESHOLD = 3000
window = []
min_val = 4095
max_val = 0
sum_val = 0
sample_counter = 0
anomaly_count = 0
def moving_average(new_sample):
window.append(new_sample)
if len(window) > WINDOW_SIZE:
window.pop(0)
return sum(window) // len(window)
# Timers
last_sample = time.ticks_ms()
last_report = time.ticks_ms()
print("Edge node started - raw sampling stays local, only summaries go out.")
# Main loop
while True:
now = time.ticks_ms()
# Take raw sample every 200 ms
if time.ticks_diff(now, last_sample) >= RAW_SAMPLE_INTERVAL:
last_sample = now
# Read ADC value
raw = sensor_pin.read()
# Apply moving average
filtered = moving_average(raw)
# Update statistics
min_val = min(min_val, filtered)
max_val = max(max_val, filtered)
sum_val += filtered
sample_counter += 1
# Check for anomaly
if filtered > ANOMALY_THRESHOLD:
anomaly_count += 1
print(
"[EDGE EVENT] Threshold crossed! filtered=",
filtered
)
# Generate summary every 5 seconds
if time.ticks_diff(now, last_report) >= REPORT_INTERVAL:
last_report = now
if sample_counter > 0:
mean_val = sum_val // sample_counter
print(
"---- Edge Summary "
"(this is what would be sent to the cloud) ----"
)
print(
"Raw samples processed locally:",
sample_counter
)
print(
"Mean:",
mean_val,
" Min:",
min_val,
" Max:",
max_val,
" Anomalies:",
anomaly_count
)
print(
"Data reduction: 1 summary sent instead of",
sample_counter,
"raw samples"
)
print(
"------------------------------------------------"
)
min_val = 4095
max_val = 0
sum_val = 0
sample_counter = 0
anomaly_count = 0
time.sleep_ms(10)