bác nên dùng luôn thư viện PID của C30 nó có viết sãn hàm PID cho bác rồi mà
bác có thể tham khảo code sau:
khai báo biến cho hàm PID
Code:
tPID fooPID;
fractional abcCoefficient[3] __attribute__ ((section (".xbss, bss, xmemory")));
fractional controlHistory[3] __attribute__ ((section (".ybss, bss, ymemory")));
fractional kCoeffs[] = {0,0,0};
khởi tạo cho PID
Code:
void PID_Init(void){
fooPID.abcCoefficients = &abcCoefficient[0]; /*Set up pointer to derived coefficients */
fooPID.controlHistory = &controlHistory[0]; /*Set up pointer to controller history samples */
PIDInit(&fooPID); /*Clear the controler history and the controller output */
kCoeffs[0] = Q15(0.1); // Kp
kCoeffs[1] = Q15(0.07); // Ki
kCoeffs[2] = Q15(0.00); // Kd
PIDCoeffCalc(&kCoeffs[0], &fooPID); /*Derive the a,b, & c coefficients from the Kp, Ki & Kd */
fooPID.controlReference = Q15(1) ; /*Set the Reference Input for your controller */
fooPID.measuredOutput = Q15(0) ;
}
sau đó dùng một timer để tạo ra chu kỳ gọi hàm PID, tính toán lại giá trị đo sau đó gọi hàm PID để xử lý
Code:
fooPID.measuredOutput = Q15(v_calculate(data)/(float)80);
PID(&fooPID);
duty = (unsigned int)(Fract2Float(fooPID.controlOutput) * PTPER *2);