 }
 
 //------------------------------------------------------------------------------------------------------
-// Main loop.
-// Right now the number of times per second that this main loop runs is set by how long the printing to 
-// the serial port takes. You can speed that up by speeding up the baud rate.
-// You can also run the commented out code and the charger routines will run once a second.
-//------------------------------------------------------------------------------------------------------
-
-void constant_power_control(int target_watts) {
- 
+// PWM Adjustments for constant voltage and constant power modes.
+// If "target_difference" > 0, it increases PWM
+// If "target_difference" < 0, it decreases PWM
+// The PWM step adjustment depends on the difference between target and current voltage/power
+//------------------------------------------------------------------------------------------------------
+void adjust_pwm(int target_difference) {
+
   int current_pwm = power_status.pwm_duty;
   int target_difference = target_watts - power_status.sol_watts;
 

  set_pwm_duty(current_pwm);
}

void constant_voltage_control(int target_voltage) {
  
  int current_pwm = power_status.pwm_duty;
  int target_difference = target_voltage - power_status.bat_volts;

  // if target difference is large, use big steps
  int pwm_delta = 1;
  if (abs(target_difference) > 100) {
    pwm_delta = 16;
  }

  // adjust pwm either up or down based on difference sign
  if (target_difference < 0) {
    current_pwm -= pwm_delta;
  } else if (target_difference > 0) {
    current_pwm += pwm_delta;
  }
  
  set_pwm_duty(current_pwm);
}

void loop()                          // run over and over again
{
  read_data();                         //read data from inputs
  //MPPT_state_machine();                      //run the charger state machine

  // update power info
  static int current_power = 0;
  static unsigned int prev_seconds = 0;        // seconds value from previous pass
  if ((seconds - prev_seconds) > 4) {  
    prev_seconds = seconds;		// do this stuff once a second

    if (current_power >= 400) {
      current_power = 100;
    }
    else {
      current_power += 100;
    }
  }

  //constant_voltage_control(current_power);
  //constant_voltage_control(500);
  //constant_power_control(current_power);
  constant_power_control(150);

  // diagnosistic prints
  static int print_counter = 0;
  print_counter++;
  if (print_counter > 200) {
    print_data(); 
    print_counter = 0;
  }


//    read_data();                         //read data from inputs
//    MPPT_state_machine();
//    print_data();                       //print data
//  }
}
//------------------------------------------------------------------------------------------------------

  Serial.print("  ");

  Serial.print("b_volts = ");
  print_int100_dec2(power_status.bat_volts);
  Serial.print("  ");

