/************************** Define Global Variables *************************/
unsigned char Kp, Ti, Td;
int Set_Speed;
/*************************** PID Initialization Function *************************/
void PID_Init(void)
{
LastError = 0;
SErro = 0;
Kp = 30;
Ti = 500;
Td = 10;
}
/*************************** PID Control Function *************************/
int PID_Control(int Now_Speed)
{
int Error, SErro, Result;
Error = Now_Speed - Set_Speed;
SErro += Error;
Result = (Kp * Error) + (Kp * 0.05 / Ti * SErro) + (Kp * Td / 0.05 * (Error - LastError));
LastError = Error;
// Limit the output value to a valid range
if (Result < 0)
{
Result = 0;
}
else if (Result > 1000)
{
Result = 1000;
}
return Result;
}
This PID control function is commonly used in motor speed control systems. It calculates the error between the current speed and the desired setpoint, then applies proportional, integral, and derivative terms to adjust the output. The values of Kp, Ti, and Td are tuned based on the system's response to ensure stability and accuracy. The result is capped between 0 and 1000 to prevent over-driving the motor or causing instability. This approach helps maintain smooth and controlled motion in real-time applications.
Contact Switch,Reed Contact Switch,Magnetic Contact,Magnetic Contact Switch
Shanghai Janetec Electric Co., Ltd. , https://www.janetecelectric.com