Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-3-7-sonnet-20250219-thinking-32k· AnthropicHugging Face LMArena Human Preference 140K

I have a Raspberry Pi Pico modified with an AP33772 USB controller that allows me to…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-opus-4-20250514’s answer.
  1. User

    I have a Raspberry Pi Pico modified with an AP33772 USB controller that allows me to pull specific voltages from a PPS enabled USB C power supply. The Pi also includes sensors for the USB C current and voltage, as well as the Pico's normal ADC interface. I would like to implement Constant Current lithium ion cell charging by manipulating the USB C output voltage to maintain the constant current.

    Can you explain how to use a proportional control loop to implement the constant current charging stage? Feel free to use MicroPython psuedo-code.

    Keep in mind that in my application, I will charge many different cells and I may use different power supplies. Any manual tuning dependent on specific hardware or cells will not be possible.

  2. Claude Assistant

    Implementing Constant Current Charging with Proportional Control

    A proportional control loop for constant current charging adjusts the USB-C output voltage based on the error between your target current and the measured current. Here's how to implement this without hardware-specific tuning:

    Basic Proportional Control Approach

    import time
    
    # Configuration
    TARGET_CURRENT = 1.0  # Amps - adjust based on cell capacity (typically 0.5C)
    SAMPLE_INTERVAL = 0.1  # seconds
    MAX_CELL_VOLTAGE = 4.2  # Maximum safe Li-ion voltage
    MIN_VOLTAGE_REQUEST = 3.7  # Starting voltage request
    MAX_VOLTAGE_REQUEST = 12.0  # Maximum voltage to request from PPS
    
    # Initial proportional gain - will be auto-tuned
    Kp = 0.5
    
    def read_usb_current():
        # Read current from your USB-C current sensor
        # Return value in Amps
        pass
    
    def read_cell_voltage():
        # Read the battery cell voltage from ADC
        # Return value in Volts
        pass
    
    def set_pps_voltage(voltage):
        # Command AP33772 to request specific voltage from PPS
        # Implement appropriate safety limits here
        voltage = max(MIN_VOLTAGE_REQUEST, min(voltage, MAX_VOLTAGE_REQUEST))
        # Send command to AP33772
        pass
    
    def auto_tune_controller():
        """Automatically determine appropriate Kp value based on system response"""
        print("Auto-tuning controller...")
        
        # Start with a safe voltage
        set_pps_voltage(MIN_VOLTAGE_REQUEST)
        time.sleep(0.5)  # Let system stabilize
        
        # Measure initial current
        initial_current = read_usb_current()
        
        # Apply a small step change
        test_voltage = MIN_VOLTAGE_REQUEST + 0.3
        set_pps_voltage(test_voltage)
        time.sleep(0.5)  # Let system stabilize
        
        # Measure new current
        new_current = read_usb_current()
        
        # Calculate system gain (ΔI/ΔV)
        current_delta = new_current - initial_current
        voltage_delta = 0.3  # The step we applied
        
        if current_delta <= 0:
            # No positive response, use conservative value
            return 0.2
        
        system_gain = current_delta / voltage_delta
        
        # Calculate Kp - lower gain for more stable response
        # Aim for slight underdamping
        kp = 0.3 / system_gain
        
        # Constrain to reasonable limits
        kp = max(0.05, min(kp, 1.0))
        
        print(f"Auto-tuned Kp: {kp}")
        return kp
    
    def constant_current_charge():
        """Main charging control loop"""
        global Kp
        
        # Auto-tune the controller
        Kp = auto_tune_controller()
        
        # Start with conservative voltage
        current_voltage = MIN_VOLTAGE_REQUEST
        set_pps_voltage(current_voltage)
        
        # Control loop variables
        last_adjustment_time = time.time()
        
        while True:
            # Read current values
            actual_current = read_usb_current()
            cell_voltage = read_cell_voltage()
            
            # Check if we should exit CC phase
            if cell_voltage >= MAX_CELL_VOLTAGE:
                print("Cell reached target voltage - ending CC phase")
                break
            
            # Calculate error
            error = TARGET_CURRENT - actual_current
            
            # Calculate voltage adjustment
            voltage_adjustment = Kp * error
            
            # Limit adjustment size for stability
            voltage_adjustment = max(-0.5, min(voltage_adjustment, 0.5))
            
            # Calculate new voltage
            new_voltage = current_voltage + voltage_adjustment
            
            # Apply new voltage
            set_pps_voltage(new_voltage)
            current_voltage = new_voltage
            
            # Print debug info
            print(f"Current: {actual_current:.3f}A, Target: {TARGET_CURRENT:.3f}A")
            print(f"Adjustment: {voltage_adjustment:.3f}V, New voltage: {new_voltage:.3f}V")
            
            # Sleep until next iteration
            time.sleep(SAMPLE_INTERVAL)
            
            # Periodically re-tune if regulation is poor
            if abs(error) > 0.2 * TARGET_CURRENT and (time.time() - last_adjustment_time > 10):
                Kp = auto_tune_controller()
                last_adjustment_time = time.time()
    

    Key Improvements for Robustness

    Here's an enhanced version with additional features for better adaptability:

    def adaptive_constant_current_charge():
        """Enhanced constant current charging with adaptation"""
        global Kp
        
        # Auto-tune the controller
        Kp = auto_tune_controller()
        
        # Start with conservative voltage
        current_voltage = MIN_VOLTAGE_REQUEST
        set_pps_voltage(current_voltage)
        
        # Control loop variables
        integral = 0
        Ki = Kp * 0.1  # Integral gain
        previous_error = 0
        last_adjustment_time = time.time()
        
        # Performance tracking
        error_history = []
        
        while True:
            # Read current values
            actual_current = read_usb_current()
            cell_voltage = read_cell_voltage()
            
            # Check if we should exit CC phase
            if cell_voltage >= MAX_CELL_VOLTAGE:
                print("Cell reached target voltage - ending CC phase")
                break
            
            # Calculate error
            error = TARGET_CURRENT - actual_current
            error_history.append(abs(error))
            
            # Only keep recent history
            if len(error_history) > 20:
                error_history.pop(0)
            
            # Calculate integral term with anti-windup
            integral += error * SAMPLE_INTERVAL
            integral = max(-1.0, min(integral, 1.0))  # Limit integral windup
            
            # Calculate adjustments
            p_term = Kp * error
            i_term = Ki * integral
            
            # Total adjustment
            voltage_adjustment = p_term + i_term
            
            # Limit adjustment size for stability
            voltage_adjustment = max(-0.5, min(voltage_adjustment, 0.5))
            
            # Calculate new voltage
            new_voltage = current_voltage + voltage_adjustment
            
            # Apply new voltage
            set_pps_voltage(new_voltage)
            current_voltage = new_voltage
            
            # Evaluate control performance
            avg_error = sum(error_history) / len(error_history)
            
            # If regulation is poor, retune controller
            if (avg_error > 0.15 * TARGET_CURRENT and 
                time.time() - last_adjustment_time > 10):
                print("Performance suboptimal, retuning controller...")
                Kp = auto_tune_controller()
                Ki = Kp * 0.1
                integral = 0
                last_adjustment_time = time.time()
                error_history = []
            
            # Sleep until next iteration
            time.sleep(SAMPLE_INTERVAL)
    

    Implementation Notes:

    1. Auto-tuning: The code automatically measures the system response to determine an appropriate Kp value, eliminating the need for manual tuning.

    2. Adaptive Control: The enhanced version periodically evaluates performance and retunes if needed, accommodating different cells and power supplies.

    3. Integral Action: Adding a small integral term helps eliminate steady-state error without needing perfect proportional tuning.

    4. Safety Limits: The code includes voltage limits and adjustment rate limits to prevent dangerous conditions.

    For best results, calculate TARGET_CURRENT based on the cell capacity (typically 0.5C for safe charging), and ensure your current and voltage measurements are properly filtered to reduce noise.

    Would you like me to explain or break down any specific part of this code?

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.