- #include "pid.h"
- #include "encoder.h"
- #include "stm32f10x.h"
- int V_encoder_TIM3(void)//1電機速度計算 轉/秒
- {
- int cnt1;
- cnt1=((int16_t)TIM3->CNT);
- TIM3->CNT=0;
- return cnt1;
- }
- int User_PidSpeedControl1(float SpeedTag)
- {
- float control1=0;
- float kp=450;
- float ki=1;
- float kd=1;
- float errILim=999;
- float errNow;
- float errOld=0;
- float errP=0;
- float errI=0;
- float errD=0;
- float spdNow1;
- float s;
- spdNow1=s;
- errNow =SpeedTag*1.1 - spdNow1;
- errP=errNow;
- errI+=errNow;
- if(errILim != 0)
- {
- if(errI >= errILim) errI = errILim;
- else if(errI <= -errILim) errI = -errILim;
- }
- errD= errNow - errOld;
- errOld = errNow;
- control1= kp * errP + ki * errI + kd * errD;
- if(control1 >= 1000) control1 = 1000-1 ;//上限 CCR的值必須小于或等于ARR的值
- if(control1 <=-1000) control1 = -(1000-1);//下限
-
- if(control1>=0.0) { GPIO_SetBits(GPIOC,GPIO_Pin_4); GPIO_ResetBits(GPIOC,GPIO_Pin_5); }
- else {GPIO_SetBits(GPIOC,GPIO_Pin_5); GPIO_ResetBits(GPIOC,GPIO_Pin_4);}
- if(control1 <0) control1 =-control1;//下限
-
- if(s<=0.1&&s>=-0.1&&SpeedTag==0)TIM_SetCompare1(TIM8,0);
- else TIM_SetCompare1(TIM8,control1);//放入PWM
-
-
- return (int)control1;
- }
復制代碼
- #include "encoder.h"
- #include "usart.h"
- #include "delay.h"
- void TIM3_Configuration(void)//1編碼器接口設置(TIM3)/PA6-A相 PA7-B相
- {
- GPIO_InitTypeDef GPIO_InitStructure;
- TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
- TIM_ICInitTypeDef TIM_ICInitStructure;
-
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA , ENABLE); //使能GPIOA外設時鐘
-
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7;
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //設置為上拉輸入模式
- GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口的速率為50M
- GPIO_Init(GPIOA, &GPIO_InitStructure); //IO口配置函數
- TIM_TimeBaseStructure.TIM_Period =PWMPeriod; //設置在下一個更新事件裝入活動的自動重裝載寄存器周期的值
- TIM_TimeBaseStructure.TIM_Prescaler = 0; //設置用來作為TIMx時鐘頻率除數的預分頻值 不分頻
- TIM_TimeBaseStructure.TIM_ClockDivision = 0; //設置時鐘分割
- TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上計數模式
- TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
-
- //設置定時器3為編碼器模式 IT1 IT2為上升沿計數
- TIM_EncoderInterfaceConfig(TIM3, TIM_EncoderMode_TI12,TIM_ICPolarity_Rising,TIM_ICPolarity_Rising);
- TIM_ICStructInit(&TIM_ICInitStructure);
- TIM_ICInitStructure.TIM_ICFilter = 0; //輸入濾波器
- TIM_ICInit(TIM3, &TIM_ICInitStructure);
- TIM_ClearFlag(TIM3, TIM_FLAG_Update); //清除所有標志位
- TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE); //允許中斷更新
- TIM3->CNT = 0;
- TIM_Cmd(TIM3, ENABLE);
- }
復制代碼
如有錯誤,請大家多多指導,代碼僅供參考:
stm32三輪PID閉環算法.7z
(186.31 KB, 下載次數: 29)
2021-8-6 15:45 上傳
點擊文件名下載附件
STM32三輪pid閉環 下載積分: 黑幣 -5
|