View Single Post
Old 07-04-2009, 12:22 PM   #131 (permalink)
MPaulHolmes
PaulH
 
MPaulHolmes's Avatar
 
Join Date: Feb 2008
Location: Maricopa, AZ (sort of. Actually outside of town)
Posts: 3,832

Michael's Electric Beetle - '71 Volkswagen Superbeetle 500000
Thanks: 1,362
Thanked 1,202 Times in 765 Posts
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;
}

__________________
kits and boards
  Reply With Quote