#include "gpio.h"
#include "common.h"
#include "uart.h"
#include "adc.h"
#include "ftm.h"
#define in1 PAout(17) //定义PTE端口的6引脚输出控制
#define in2 PAout(15) //定义PTE端口的7引脚输出控制
float Perror=0,P=0.01,D=0.065, error_old=0,Derror=0,error=0;//D=0.6-0.7
int zuo=0, you=0 ;
float d=0 ;
double PIDCalc(void)
{
Perror=P*error;
you=ADC_ReadValue(HW_ADC1, kADC_MuxA);//zuo
zuo=ADC_ReadValue(HW_ADC0, kADC_MuxA);//you
error=zuo-you;
Derror=D*(Perror-error);
return Derror;
}
int main(void)
{
static int x=500;
DelayInit();
GPIO_QuickInit(HW_GPIOA, 17, kGPIO_Mode_OPP);// in1 PA17
GPIO_QuickInit(HW_GPIOA, 16, kGPIO_Mode_OPP);// in2 PA15
GPIO_QuickInit(HW_GPIOE, 6, kGPIO_Mode_OPP); //定义PE6为LED 表示点
UART_QuickInit(UART0_RX_PD06_TX_PD07, 115200);//USART RX_PD6 TX_PD7
/* 初始化ADC模块 ADC0_SE4B_PC2 ADC1_SE5_PE1 */
ADC_InitTypeDef ADC_InitStruct1;
ADC_InitStruct1.instance = HW_ADC0;
ADC_InitStruct1.clockDiv = kADC_ClockDiv2; /* ADC采样时钟2分频 */
ADC_InitStruct1.resolutionMode =kADC_SingleDiff12or13;
ADC_InitStruct1.triggerMode = kADC_TriggerSoftware; /* 软件触发转换 */
ADC_InitStruct1.singleOrDiffMode = kADC_Single; /*单端模式 */
ADC_InitStruct1.continueMode = kADC_ContinueConversionEnable; /* 启动连续转换 转换一次后 自动开始下一次转换*/
ADC_InitStruct1.hardwareAveMode =kADC_HardwareAverage_4; /*禁止 硬件平均 功能 */
ADC_InitStruct1.vref = kADC_VoltageVREF; /* 使用外部VERFH VREFL 作为模拟电压参考 */
ADC_Init(&ADC_InitStruct1);
ADC_InitStruct1.instance = HW_ADC1;
ADC_Init(&ADC_InitStruct1);
PORT_PinMuxConfig(HW_GPIOE,1,kPinAlt0); //ADC1 PE1
PORT_PinMuxConfig(HW_GPIOC,2,kPinAlt0); //ADC0 PC2
ADC_ChlMuxConfig(HW_ADC0,kADC_ChlMuxB);// ADC0_SE4B_PC2 通道是B就用B通道触发
ADC_ChlMuxConfig(HW_ADC1,kADC_ChlMuxA);//ADC1 ADC1_SE5_PE1 通道是A就用A通道触发
/* 启动一次ADC转换 */
ADC_StartConversion(HW_ADC0, 4, kADC_MuxA);//ADC0 ADC0_SE4B_PC2 是4通道 A通道软硬触发。
ADC_StartConversion(HW_ADC1, 5, kADC_MuxA);//ADC1 ADC1_SE5_PE1 是5通道 A通道软硬触发。
FTM_PWM_QuickInit( FTM1_CH0_PA12, kPWM_EdgeAligned, 1000);//应用后轮是100万何止FTM1_CH0_PA12 较高比较好
FTM_PWM_QuickInit( FTM0_CH3_PA06, kPWM_EdgeAligned, 50);//舵机
FTM_PWM_ChangeDuty(HW_FTM1, HW_FTM_CH0, 4200 ); /* 0-10000 对应 0-100% 380 750 */ //4200稳定
while(1)
{
in1=1;
in2=0;
d=PIDCalc();
d=d*0.8;
FTM_PWM_ChangeDuty(HW_FTM0, HW_FTM_CH3, 750+d); /* 0-10000 对应 0-100% */
if((zuo<=600)&&(you<=600))
{
in1=0;
in2=0;
}
/* 如果ADC转换完成 */
if(ADC_IsConversionCompleted(HW_ADC1, kADC_MuxA) == 0)
{
/* 读取ADC的值 kADC_MuxA是每个ADC通道的转换器 默认都是 kADC_MuxA MuxB 一般不能用于软件触发 */
printf("[ADC1 5 PE1]zuo:%04d [ADC0 5 PC2]you:%04d d:%04d\r", ADC_ReadValue(HW_ADC1, kADC_MuxA) , ADC_ReadValue(HW_ADC0, kADC_MuxA) , d );
}
// DelayMs(5);
}
}