This is an excellent application for a proportional control loop! Constant Current (CC) charging for lithium-ion cells requires precisely managing the current flowing into the battery, and a control loop is perfect for this.
Let's break down how a proportional (P) control loop works in this context and then provide the MicroPython pseudo-code.
Understanding Proportional (P) Control for Constant Current Charging
The goal is to maintain a TARGET_CURRENT (e.g., 1A) flowing into the battery. The system has a way to measure the ACTUAL_CURRENT and a way to adjust the OUTPUT_VOLTAGE from the USB-C supply.
A proportional control loop works by calculating an "error" and then making an adjustment proportional to that error.
- Setpoint: This is your desired current,
TARGET_CURRENT.
- Process Variable (PV): This is the measured
ACTUAL_CURRENT from your USB-C current sensor.
- Error: The difference between the setpoint and the process variable:
Error = TARGET_CURRENT - ACTUAL_CURRENT.
- If
Error is positive, the ACTUAL_CURRENT is too low. We need to increase the USB-C output voltage to drive more current.
- If
Error is negative, the ACTUAL_CURRENT is too high. We need to decrease the USB-C output voltage to reduce current.
- If
Error is zero (or very close), the current is at the target.
- Proportional Gain (Kp): This is a tuning constant that determines how aggressively the system responds to the error.
Voltage_Adjustment = Kp * Error
Kp has units of Volts / Ampere (or Volts / milliAmpere if your current is measured in mA).
- A larger
Kp makes the system respond faster but can lead to oscillations if too high.
- A smaller
Kp makes the system respond slower but can be more stable.
- Output (Manipulated Variable): This is the USB-C output voltage that you command the AP33772 to provide. The calculated
Voltage_Adjustment is added to (or subtracted from) the current target voltage.
How it works in a loop:
In each iteration:
- Read the current flowing into the battery.
- Calculate the error:
Target Current - Actual Current.
- Calculate how much to change the USB-C voltage based on
Kp and the error.
- Apply this change to the USB-C supply via the AP33772.
- Wait for a short period (
time.sleep()) to allow the system to stabilize and for the current reading to reflect the new voltage, then repeat.
Important Considerations for CC Charging (Li-Ion)
- CC-CV Transition: Lithium-ion batteries must be charged in two main stages:
- Constant Current (CC): Charge at a constant current until the battery reaches its maximum voltage (typically 4.2V per cell). This is what we're implementing.
- Constant Voltage (CV): Once 4.2V is reached, hold the voltage at 4.2V and let the current gradually drop. Charging is complete when the current drops to a very low level (e.g., C/10 or C/20). Your P-loop for CC will naturally transition if the battery voltage starts to exceed 4.2V by reducing the current and thus the output voltage. However, it's safer to explicitly monitor battery voltage and switch modes.
- Safety Limits:
- Maximum Battery Voltage: NEVER exceed 4.2V per cell for standard Li-ion. Your control loop should cease CC operation (or transition to CV) if the battery voltage approaches this limit.
- Minimum Battery Voltage: If the battery is deeply discharged (e.g., below 2.5V or 3.0V), a pre-charge stage at a very low current is recommended before starting full CC charging. Your Pico's ADC can measure this.
- USB-C PPS Voltage Range: The AP33772 will have a specific range of voltages it can request (e.g., 3.3V to 21V, with specific steps). Your
target_usb_voltage must be constrained within this range and quantized to the closest available PPS voltage step.
- Initial USB-C Voltage: Start the USB-C supply at a safe low voltage (e.g., 5V, or slightly above the current battery voltage) and let the P-loop increase it as needed.
- Sampling Rate / Loop Delay: Don't run the loop too fast. A
time.sleep() of 50-200ms is usually good. Too fast can lead to instability; too slow can lead to sluggish response.
- P-Only Limitations: A P-only loop might exhibit a small steady-state error (it might not settle exactly on the target current, but very close). For many charging applications, this is acceptable. For perfect tracking, a PI (Proportional-Integral) controller would be used, but P-only is simpler and often sufficient.
MicroPython Pseudo-Code for Proportional CC Charging
This pseudo-code assumes you have functions to interact with your specific hardware:
read_current_sensor(): Returns current in Amps.
read_battery_voltage_adc(): Returns battery voltage in Volts.
set_pps_voltage(volts): Communicates with the AP33772 to request the specified voltage. This function will need to handle selecting the closest available PPS voltage based on the AP33772's capabilities (e.g., PPS offers 20mV steps from 3.3V to 21V).
get_available_pps_voltages(): Returns a list or range of voltages the AP33772 can actually set.
import time
import machine # For ADC, if needed directly
# --- Configuration Constants ---
TARGET_CHARGE_CURRENT_A = 1.0 # Amperes (e.g., 1A)
BATTERY_FULL_VOLTAGE = 4.2 # Volts (for Li-ion 1S cell)
BATTERY_PRECHARGE_THRESHOLD_V = 3.0 # Below this, pre-charge (not implemented in this CC loop)
BATTERY_CUTOFF_CURRENT_A = 0.05 # Amperes, current to stop charging in CV stage (e.g., C/20)
# Proportional Gain (Kp) - This is the most crucial tuning parameter!
# Kp = (Volts change) / (Ampere error)
# Start with a small value and tune upwards.
# A rough starting point might be 0.5 to 5.0, depending on your system's response.
# If Kp is too high, current will oscillate wildly.
# If Kp is too low, current will be slow to reach target or have steady-state error.
KP = 2.0 # Example value, needs tuning!
# USB-C PPS Voltage Limits (example values, check your AP33772 datasheet)
PPS_MIN_V = 3.3
PPS_MAX_V = 21.0
PPS_STEP_MV = 20 # PPS offers 20mV granularity
# Control loop timing
LOOP_DELAY_MS = 100 # Milliseconds between loop iterations
# --- Hardware Abstraction Functions (Implement these based on your setup) ---
# Replace with your actual current sensor reading logic
# e.g., via an ADC connected to a current sense amplifier
def read_current_sensor():
# Dummy implementation: simulate current reading
# In a real scenario, this would read an ADC channel, convert to Amps
# For simulation, let's assume it's influenced by a global 'simulated_voltage'
# and a fixed 'simulated_resistance' to show current response
# In real world: current_adc_value = adc_pin.read_u16()
# current_volts = current_adc_value * (3.3 / 65535) # Pico ADC is 16-bit
# actual_amps = (current_volts - OFFSET_V) / SENSE_RESISTOR / GAIN
return 0.0 # Placeholder: return the measured current in Amperes
# Replace with your actual battery voltage reading logic
# e.g., via a voltage divider into a Pico ADC pin
def read_battery_voltage_adc():
# Dummy implementation: simulate battery voltage
# In a real scenario, this would read an ADC channel, convert to Volts
# battery_adc_value = adc_battery_pin.read_u16()
# battery_volts = battery_adc_value * (3.3 / 65535) * VOLTAGE_DIVIDER_RATIO
return 3.5 # Placeholder: return the measured battery voltage in Volts
# Replace with your actual AP33772 control logic (e.g., I2C communication)
# This function sends a command to the AP33772 to request a specific voltage.
# It needs to find the closest valid PPS voltage step.
def set_pps_voltage(target_voltage_v):
# Clamp target voltage to PPS limits
clamped_voltage = max(PPS_MIN_V, min(PPS_MAX_V, target_voltage_v))
# Quantize to the nearest 20mV PPS step
# Convert to millivolts, round to nearest 20mV, convert back to Volts
quantized_mv = round(clamped_voltage * 1000 / PPS_STEP_MV) * PPS_STEP_MV
final_voltage_v = quantized_mv / 1000.0
# In a real scenario, this would be an I2C command to the AP33772
# e.g., ap33772.request_voltage(final_voltage_v)
print(f"DEBUG: Requesting PPS voltage: {final_voltage_v:.3f}V (from target {target_voltage_v:.3f}V)")
# You might want to store this to know what voltage you last requested
global current_usb_c_output_v
current_usb_c_output_v = final_voltage_v
time.sleep_ms(50) # Give the power supply some time to adjust
# --- Global Variables for Control Loop State ---
current_usb_c_output_v = PPS_MIN_V # Start with the minimum safe voltage
# You might want to get the actual current supply voltage from the AP33772 or measure it.
# --- Main Charging Loop ---
def constant_current_charge():
global current_usb_c_output_v
print("Starting Constant Current (CC) charging...")
print(f"Target Current: {TARGET_CHARGE_CURRENT_A}A")
print(f"Battery Full Voltage: {BATTERY_FULL_VOLTAGE}V")
print(f"Kp: {KP}")
# Initial setting of the USB-C voltage
set_pps_voltage(current_usb_c_output_v)
charging_active = True
while charging_active:
actual_current = read_current_sensor()
battery_voltage = read_battery_voltage_adc()
# --- Check for Pre-charge (optional, but good practice) ---
if battery_voltage < BATTERY_PRECHARGE_THRESHOLD_V:
print(f"WARNING: Battery voltage ({battery_voltage:.2f}V) too low for full CC charge. Implement pre-charge or stop.")
# Here you might set a very low current limit, or just halt charging.
# For simplicity, we'll stop the main loop, but a proper charger would enter a trickle charge state.
set_pps_voltage(PPS_MIN_V) # Reduce voltage to minimum
charging_active = False
break # Exit the loop
# --- Main Proportional Control Loop ---
error = TARGET_CHARGE_CURRENT_A - actual_current
# Calculate voltage adjustment based on P-control
# If current is too low (positive error), increase voltage.
# If current is too high (negative error), decrease voltage.
voltage_adjustment = KP * error
# Update the target voltage for the USB-C supply
current_usb_c_output_v += voltage_adjustment
# Clamp the target voltage to the allowed PPS range
current_usb_c_output_v = max(PPS_MIN_V, min(PPS_MAX_V, current_usb_c_output_v))
# Request the new voltage from the USB-C power supply
set_pps_voltage(current_usb_c_output_v)
print(f"Batt V: {battery_voltage:.2f}V | Current: {actual_current:.3f}A | Error: {error:.3f}A | Adj: {voltage_adjustment:.3f}V | Target USB-C V: {current_usb_c_output_v:.3f}V")
# --- Check for CC to CV Transition or Charge Completion ---
if battery_voltage >= BATTERY_FULL_VOLTAGE:
print(f"Battery reached {BATTERY_FULL_VOLTAGE}V. Transitioning to Constant Voltage (CV) or ending CC stage.")
# At this point, the loop *should* naturally reduce current if it's overshooting,
# or if the battery voltage starts to rise above 4.2V quickly.
# For true CV, you would switch the control loop to regulate voltage at 4.2V,
# and monitor current until it drops below BATTERY_CUTOFF_CURRENT_A.
# For this example, we'll just stop the CC loop.
# --- Simple CV stage (holding voltage, letting current drop) ---
# Now, you'd *fix* the voltage at BATTERY_FULL_VOLTAGE
# and watch the current drop.
set_pps_voltage(BATTERY_FULL_VOLTAGE) # Hold at 4.2V
while actual_current > BATTERY_CUTOFF_CURRENT_A:
time.sleep_ms(LOOP_DELAY_MS)
actual_current = read_current_sensor()
battery_voltage = read_battery_voltage_adc()
print(f"CV Stage: Batt V: {battery_voltage:.2f}V | Current: {actual_current:.3f}A (dropping...)")
if battery_voltage > BATTERY_FULL_VOLTAGE + 0.05: # Small buffer
print("WARNING: Battery voltage exceeded 4.25V during CV. Disconnecting power.")
set_pps_voltage(0.0) # Or minimum safe voltage
charging_active = False
break
if charging_active: # If not already stopped by overvoltage
print(f"Charge complete. Current dropped below {BATTERY_CUTOFF_CURRENT_A}A.")
set_pps_voltage(0.0) # Disconnect power
charging_active = False
time.sleep_ms(LOOP_DELAY_MS) # Wait before next iteration
print("Charging process ended.")
# --- How to run the charging ---
if __name__ == '__main__':
# You would initialize your I2C/SPI for AP33772 and ADC pins here
# Example:
# from machine import Pin, ADC, I2C
# i2c = I2C(0, scl=Pin(9), sda=Pin(8), freq=400000)
# current_adc_pin = ADC(Pin(26))
# battery_voltage_adc_pin = ADC(Pin(27))
# ap33772 = AP33772_Driver(i2c) # Assuming you have a driver class
# Run the charging function
try:
constant_current_charge()
except KeyboardInterrupt:
print("\nCharging interrupted by user.")
set_pps_voltage(0.0) # Ensure power is off
except Exception as e:
print(f"An error occurred: {e}")
set_pps_voltage(0.0) # Ensure power is off
How to Tune Kp
Tuning Kp is critical for stable and efficient charging.
- Start Low: Begin with a very small
Kp value (e.g., 0.1 or 0.5).
- Observe Response: Run the charging loop.
- If the current takes a very long time to reach the
TARGET_CURRENT and settles below it (large steady-state error), Kp is too low.
- If the current overshoots the target and then slowly oscillates around it before settling (or not settling),
Kp is getting too high.
- If the current oscillates wildly and never stabilizes,
Kp is definitely too high.
- Increase Gradually: Double
Kp each time until you see oscillations.
- Back Off: Once you see oscillations, reduce
Kp by half, and then try increasing it by smaller increments (e.g., 0.1, 0.05) until you find the value that provides the fastest response without significant overshoot or sustained oscillation.
Safety during Tuning:
- Always monitor the battery voltage closely.
- Have a way to quickly disconnect power.
- Start with a lower
TARGET_CHARGE_CURRENT_A during initial tuning.
This setup provides a robust foundation for your constant current Li-ion charging solution using your customized Raspberry Pi Pico and the AP33772 controller. Remember that the read_current_sensor(), read_battery_voltage_adc(), and set_pps_voltage() functions are placeholders that you'll need to implement based on your specific sensor interfaces and the AP33772's communication protocol (likely I2C).