2
votes

I am working on a firmware code, I set interrupt time to 10us but now the loop is running every 5ms, which is much much slower. Any idea on how to speed up the loop is highly appreciate!

unsigned long lastTime;
double BAT_I_FB, Output, Setpoint= 8 ;
double errSum=0, lastErr,error=99;
double kp=0.1, ki=15, kd=0;
double KdVal,KpVal,KiVal,PID,BUS_V;
double SampleTime = 10;

void loop() {

unsigned long now = micros();

int timeChange = (now-lastTime);

if(timeChange >= SampleTime)
{
/*Compute all the working error variables*/
BAT_I_FB = analogRead(pins[15].arduinoPinNumber);
BAT_I_FB = float(BAT_I_FB * (5.0/1024)) * pins[15].multiplier;


error = Setpoint - BAT_I_FB;
errSum += error;
double dErr = (error - lastErr);

BUS_V = analogRead(pins[18].arduinoPinNumber);
BUS_V = float(BUS_V * (5.0/1024)) * pins[18].multiplier;

/*compute PID Output*/

PID = kp * error +ki/10000 * errSum + kd * 1000 * dErr;

Output = (PID-100) * (-2.5);

analogWrite(2, Output);


/*Remember some variable for next time*/
lastErr = error;
lastTime = now;

}
2
How fast is this processor and how much code is in the interrupt handler? You might only be able to execute a handful of instructions in 10us - in which case the solution is "do less stuff or get a faster processor". - user253751

2 Answers

0
votes

note that Ardunio board can not run that fast. For example, for analogRead, it takes about 100 microseconds to read an analog input (see : https://www.arduino.cc/en/Reference/AnalogRead). For analogWrite, it generate a wave of approximately 490 Hz (2ms). And there may be more delays from other parts of the code that you did not show here.

0
votes

In general it is best not to do much work in an interrupt, you didn't show your interrupt code here but with a 10uS rate you can't really do much anyway. Which board are you using? One solution might be to set a flag in your interrupt and then process the interrupt in your main loop but the fact remains that if the work you need to do every 10uS exceeds what your processor can accomplish in that time something needs to give. Think about what part of your code should be deferred in the case of a timing conflict and structure your code that way, interrupts take priority over everything else.