void ADC1_Init(void)
{
TRISA0=1; //模拟通道0设置为输入
ADCON1=0b10000010;//配置引脚工作方式,转换结果右对齐
ADCON0=0b00000001;//使用单片机主频二分频作为转换时钟,选择通道0进行AD转换
}
void InitAPWM()
{
TRISC2=0;//RC2作为PWM模式输出引脚
T2CKPS1=0;
T2CKPS0=0;//TMR2预分频比为1:1,且使能TMR2模块
PR2=249;//PR2=(1/16KHZ)/(4*(1/16MHZ)-1=249(PWM模式周期/(4*Tosc*TMR2预分频值))-1
CCPR1L=((uint8)(wide>>2))&0x0FF;
if((((uint8)(wide>>1))&0x01)==1) CCP1X=1;
else CCP1X=0;
if((((uint8)wide)&0x01)==1) CCP1Y=1;
else CCP1Y=0;
CCP1M3=1;
CCP1M2=1;
CCP1M1=0;
CCP1M0=0;
TMR2ON=1;
}
void InitBPWM()
{
TRISC1=0;//RC2作为PWM模式输出引脚
T2CKPS1=0;
T2CKPS0=0;//TMR2预分频比为1:1,且使能TMR2模块
PR2=249;
CCPR2L=((uint8)(wide>>2))&0x0FF;
if((((uint8)(wide>>1))&0x01)==1) CCP2X=1;
else CCP2X=0;
if((((uint8)wide)&0x01)==1) CCP2Y=1;
else CCP2Y=0;
CCP2M3=1;
CCP2M2=1;
CCP2M1=0;
CCP2M0=0;
TMR2ON=1;
}
void interrupt ISR(void) //定时中断服务程序
{
double rOut;
double rIn;
if(T0IF==1)
{
T0IF=0; //清空标志
g_ACC++;
if(g_ACC==500) //等于500说明1s了
{
RB4=~bFlag; //RB2口求反
bFlag=RB4;
g_ACC=0; //累加器清零
//EEPROM_Write(0x00,(uint8)spid.Proportion);//写0x00地址
//EEPROM_Write(0x01,(uint8)spid.Integral); //写0x01地址
//EEPROM_Write(0x02,(uint8)spid.Derivative);//写0x02地址
//EEPROM_Write(0x00,0x55);
//EEPROM_Write(0x01,0x11);
//EEPROM_Write(0x02,0x22);
}
ADGO=1; //启动AD转换
while(ADGO){}
torque=0;
torque=(((uint16)ADRESH)<<8)+ADRESL; //获得十位转换结果
//spid.Setpoint=(double)torque; //r(t)
//ADC2_Init();
//ADGO=1; //启动AD转换
//while(ADGO){}
//current=(((uint16)ADRESH)<<8)+ADRESL; //获得十位转换结果
//rOut=(double)current; //y(t)
//rIn=PIDCalc (&spid,rOut); //u(t)
if(torque<=(512-10))//电机反转
{
uint16 motor_left=0;
motor_left=512-10-torque;
wide=(uint16)((long)motor_left*1000/502);
InitAPWM();
wide=0;
InitBPWM();
}
else if(torque>=(512+10))//电机正转
{
uint16 motor_right=0;
motor_right=torque-512-10;
wide=(uint16)((long)motor_right*1000/502);
InitBPWM();
wide=0;
InitAPWM();
}
else//电机停止
{
wide=0;
InitAPWM();
InitBPWM();
}
}
}
部分代码 |