While loop execution time

Status
Not open for further replies.

gehan_s

Member level 3
Joined
Aug 31, 2012
Messages
62
Helped
3
Reputation
6
Reaction score
3
Trophy points
1,288
Location
Sri Lanka
Visit site
Activity points
1,799
Hi all,

How can I determine the total runtime of this while(1) loop? The microcontroller is a 16F877A and has a oscillator frequency of 20MHz.

Thanks in advance !!!!!!!!!!!!!!!

Code:
void main(){

     float error   = 0;   // present error
     float error_1 = 0;   // previous error
     float acc_err = 0;   // accumulated error
     float vout    = 0;   // actual O/P value
     float set     = 0;   // set O/P value
     float pwm     = 0;
     float Kp      = 0;
     float Ki      = 0;
     float Kd      = 0;
     float T       = 0;   // time between two samples
     char txt1[5];
     char txt2[5];
     
     TRISB         = 0;

     Lcd_Init(&PORTB);
     Pwm_Init(10000);
     Pwm_Start();
     Pwm_Change_Duty(pwm);
     Lcd_Cmd(LCD_CURSOR_OFF);
     Lcd_Cmd(LCD_CLEAR);

     delay_ms(10);

     while(1){
     
          set     = Adc_Read(1);
          Kp      = Adc_Read(2);
          Ki      = Adc_Read(3);
          Kd      = Adc_Read(4);
          vout    = Adc_Read(0);
          set     = (set/1024)*5;
          Kp      = (Kp/1024)*100;
          Ki      = (Ki/1024)*100;
          Kd      = (Kd/1024)*100;
          vout    = (vout/1024)*5;
          error_1 = error;
          error   = set - vout;
          acc_err = acc_err + error;

          pwm     = pwm + (Kp*error) + (Kd*(error-error_1)/T) + (Ki*acc_err*T);

          if(pwm>=255){
          pwm  = 255;
          }
          else if(pwm<0){
          pwm = 0;
          }

          Pwm_Change_Duty(pwm);

     }
}
 

Hi,
There are technical ways to calculate the time taken by loop. We can do that by integrating instruction time as per datasheet of microcontroller. But let me show you the simplest way, as you have a LCD for display, just take one more variable and add it at the end of the code, like
"
unsigned int test_time, test_sec;

..........code.......
test_time++;
if(test_time > 1000)
{
test_time = 0;
test_sec++;
display(test_sec);
}
......as simple as that, Yes that is true it might add some instruction but thats ok we will get approximate timing.
}
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…