Smpling time and pid loop

Hi there i want to know if i get a data every 50 ms and my loop turn every 4 ms. should my pid run on 50 ms or 4 ms ??

More details please

for example i want to stabilze my quadcopter, i have an ultrasonic sensor that i get the data of the altitude every 50 ms and my loop run every 4 ms. i want to do a pid loop to stabilze the altitude.

my question should i call the pid every 50 ms or every 4ms? .

Without getting any new feedback data the PID cannot do anything useful so there is little point in running the PID every 4 ms when new data is only available every 50 ms.

Why is there a discrepancy between the periods ? It would be normal to read the sensor(s) each time through loop() and use the values as inputs to the PID.

every 4 ms i get the angles roll pitch yaw and every 50ms i get data of ultrasonic sensor(). i can't run the same data in the same loop time. i will get a jitter. so i call my pid every 50ms to stabilize the altitude of the drone??

You could have several PIDs running at different frequencies.

Are you relying on the ultrasonic sensor for altitude information ? If so, over what range of altitudes are you hoping for it to work and have you taken into account that it will not work well over some surfaces ?

It would be worth measuring how long the PID calculation takes. When I did some investigations the code from the regular PID library it was very slow because it was using float calculations.


Hi thanks for the answer, the surface the grounde. i put the data of ultrasonic on centimeter range directly to the input of the pid.

and i have other problem, i have a jitter my quadcopter it's not stable when i active the ultrasonic sensore.

the quadcopter fly well without the ultrasonic but when i active the ultrasonic i think a jitter will produce and my quadcopter it's not stable. how can i get the data of the ultrasonic without a jiter ?

i use arduino duo, i use mpu6050 i2cdevlib/Arduino/MPU6050 at master · jrowberg/i2cdevlib · GitHub.

and the code of ultrasonic that i use here it is

void init_SONAR()


    pinMode(trig, OUTPUT);
    digitalWrite(trig, LOW);
    pinMode(echo, INPUT);

void get_distance()

    digitalWrite(trig, HIGH);
    digitalWrite(trig, LOW);
    lecture_echo = pulseIn(echo, HIGH, 17400);
    cm = lecture_echo / 58;

void loop()





my quadcopter it's not stable at all if i call the getdistance every 4 ms() if i call the getdistance evry 50 ms the quadcopter stable but sometime wobble because jitter.

how can i resolve this probleme please

It might help if we could see all of your code...

How stable are the readings from the ultrasonic sensor and what is the maximum height that you expect it to work at ?

"The ground" doesn't look the same on different places on the earth. :)

The reading from the ultrasonic is stable, but will jitter the imu calculation. the code is i added the ultrasonic the code wase post in my previous poste