Here's a code sample of what I mean, where pwmDuty is in the range 0-16352. You want it so that it scales to 0-511, not 0-512 (so don't use 0-16383, which is 2^14 - 1). You don't even have to have a separate pwmDuty variable that actually is in the range 0-511. Just change pwmDuty at the end. Let's say you want the current to stay constant at "targetCurrent":
ReadCurrent();
if (current < targetCurrent) {
pwmDuty++;
if (pwmDuty > MAX_PWM_DUTY) {
pwmDuty = MAX_PWM_DUTY;
}
}
else if (current > targetCurrent) {
pwmDuty--;
if (pwmDuty < 0) {
pwmDuty = 0;
}
}
if ((pwmDuty & 31) >= 16) { // round up!
OCR1A = (pwmDuty >> 5) + 1;
}
else {
OCR1A = pwmDuty >> 5;
}
|