import time
from machine import Pin, ADC, PWM
import dht
# --- Hardware Initialization (As per your diagram.json) ---
sensor_dht = dht.DHT22(Pin(4))
ldr = ADC(Pin(34))
pot_vin = ADC(Pin(35))
pwm_out = PWM(Pin(18), freq=20000)
# --- Tuned Neural Network Weights ---
# W1: 4 neurons, each with 3 inputs [Temp, Lux, Vin]
# Weights are adjusted to reduce D as Vin increases (typical for Boost MPPT)
W1 = [
[-0.15, 0.05, -0.60], # Neuron 1: Strong negative Vin sensitivity
[ 0.10, 0.25, -0.30], # Neuron 2: Lux sensitivity
[-0.05, 0.15, -0.75], # Neuron 3: Strong negative Vin sensitivity
[ 0.05, 0.10, -0.20] # Neuron 4: General sensitivity
]
B1 = [0.4, 0.1, 0.5, 0.2] # Biases for hidden layer
# W2: Output neuron weights for the 4 hidden neurons
W2 = [0.35, 0.25, 0.40, 0.15]
B2 = 0.15 # Lowered base bias to avoid saturation
def relu(x):
return max(0, x)
def predict_mppt(temp, lux, vin):
# Normalize inputs: T(0-50), Lux(0-100), Vin(0-20V)
inputs = [temp/50.0, lux/100.0, vin/20.0]
# Hidden Layer
hidden = []
for i in range(len(W1)):
z = sum(W1[i][j] * inputs[j] for j in range(len(inputs))) + B1[i]
hidden.append(relu(z))
# Output Layer
# Calculates a raw value roughly between 0.1 and 0.9
raw_d = sum(W2[i] * hidden[i] for i in range(len(W2))) + B2
# Map to 10% - 90% Duty Cycle
return max(10, min(90, raw_d * 100))
print("\n--- TUNED MPPT SYSTEM STARTING ---")
while True:
try:
sensor_dht.measure()
t = sensor_dht.temperature()
# Scaling ADC (0-4095)
intensity = ldr.read() / 40.95
voltage_in = pot_vin.read() / 204.75
# Inference
d_val = predict_mppt(t, intensity, voltage_in)
# PWM Register (0-1023)
pwm_out.duty(int((d_val / 100) * 1023))
# Terminal Display
print(f"Vin: {voltage_in:4.1f}V | Lux: {intensity:4.1f}% | Temp: {t:2.0f}C | -> Predicted D: {d_val:4.1f}%")
except Exception as e:
print(f"Error: {e}")
time.sleep(1.5)