# Motor Controller Limiting Current PWM

Hi,

I need help with a program i’m doing for a motor controller, I am trying to limit the current to 100 amps but but still have the PWM control work. I’ve got the program to stop PWM output when current goes above 100 amps but then I can’t get the PWM to go back down once it reaches that current, any help would be appreciated.

#include <PWM.h>

int32_t frequency = 10000; //frequency HZ

int current = 0; // Current Sensor

int motoramps = 0; // Motor Amps

int throttlePin = A0; //Throttle input

int currentPin = A1; //Current sensor input

void setup() {

// Serial.begin(9600);
bool success = SetPinFrequencySafe(9, frequency);
if(success) {
pinMode (13, OUTPUT);
digitalWrite(13, HIGH);
}
}

void loop() {

throttleValue = map(throttleValue, 0, 1023, 0, 255);

current = map(current, 0, 1023, 0, 5000);
motoramps = ((current - 2525) / 3.65);

if (motoramps <= 100){
pwmWrite(9, throttleValue);
}

// Serial.println(motoramps, 2);

delay(10); // delay inbetween reads for stability
}

This is not going to do what you want

``````motoramps = ((current - 2525) / 3.65);
``````

because you are using integers. I presume the actual division will be by 3 with the decimals ignored.

What value is Serial.print() showing for motorAmps?

I don't know anything about the PWM library - I just use the standard analogWrite() function.

...R

Sorry yes the motoramps & current should be a float not int.

inazumaryuu:
Sorry yes the motoramps & current should be a float not int.

Does that mean that your program is now working properly?

...R

Nope lol I can get the PWM to stop when it goes to 100 amp but then when I adjust the throttle input the pwm won't change to go lower.

inazumaryuu:
Nope lol I can get the PWM to stop when it goes to 100 amp but then when I adjust the throttle input the pwm won’t change to go lower.

That’s because you do nothing if the current goes over 100A.

You need to modify your original code:-

``````  if (motoramps <= 100){
pwmWrite(9, throttleValue);
}

// Serial.println(motoramps, 2);
``````

To include instructions to reduce the pulse width:-

``````  if (motoramps <= 100){
pwmWrite(9, throttleValue);
}
else {
// calculate a reducedThrottleValue based on current throttleValue;
pwmWrite(9, reducedThrottleValue);
}

// Serial.println(motoramps, 2);
``````

Probably the best way to do this is to keep a record of the previous throttle value and if the latest throttle value is greater than or equal to previous value use the previous value (or the previous value reduced by 10%) and if the current value is less than the previous value then use the current value. You’ll have to experiment to see what works with your set up.

Ian

Hi Ian,

Thanks for the reply that makes a lot of sense, do you think you could give me some sample code for doing this because I'm not the best at programming Arduino.