📄 main.c
字号:
#include "main.h"
#include "port.h"
#define PID_KP (0.003f)
#define PID_KI (0.170f)
#define PID_KD (0.100f)
void Port_Init(void);
void Uart_Init(void);
void Spu_Init(void);
void Pwm_Adjust(void);
volatile u08 Send_Buff[4];
volatile u08 Send_Len;
volatile u08 *Send_Ptr;
u08 Target_Spu;
volatile u08 Actual_Spu;
volatile u08 Spu_Number;
volatile u08 Pwm_Adjust_Enable;
void main(void)
{
OSCCAL=0xB7;
__delay_cycles(65530);
Port_Init();
//pwm generate ,cycle is 55.5us
TCCR1A=(1<<COM1B1)|(1<<WGM10);
TCCR1B=(1<<WGM13)|(1<<CS10);
OCR1AH=0;
OCR1AL=222;
OCR1BH=0;
OCR1BL=0;
SPEED_MOTOR_ENABLE();
TCCR0A=(1<<WGM01);
TCCR0B=((1<<CS00)|(1<<CS02));
OCR0A=255; //cycle=(255+1)*0.125*1024us=32768us;
TIMSK0=(1<<OCIE0A);
Uart_Init();
Spu_Init();
Pwm_Adjust_Enable=0;
_SEI();
Target_Spu=100;
while (1)
{
if (Pwm_Adjust_Enable)
{
Pwm_Adjust();
Pwm_Adjust_Enable=0;
}
}
}
void Port_Init(void)
{
DDRB=0x47;
PORTB=0x41;
DDRC=0x00;
PORTC=0x08;
DDRD=0xEE;
PORTD=0x83;
DIDR0=0x07;
}
void Uart_Init(void)
{
UCSR0A =0;
UBRR0H=0;
UBRR0L=51;
UCSR0C = (1<<UCSZ01)|(1<<UCSZ00); // 8 bit
UCSR0B= (1<<RXCIE0)|(1<<RXEN0)|(1<<TXCIE0)|(1<<TXEN0);
UART_RECEIVE_ENABLE();
Send_Len=0;
}
void Spu_Init(void)
{
PCICR = (1 << PCIE0);
PCMSK0 =(1 << PCINT7);
Spu_Number=0;
}
#pragma vector = TIMER0_COMPA_vect
__interrupt void timer0_compa_isr(void)
{
static u08 counter=0;
counter++;
if (counter>4) //163840us
{
counter=0;
PORTD^=1<<_LED;
Actual_Spu=Spu_Number;
Spu_Number=0;
Send_Buff[0]=0x55;
Send_Buff[1]=OCR1BL;
Send_Buff[2]=Actual_Spu;
UART_SEND_ENABLE();
Send_Len=3;
Send_Ptr=Send_Buff;
UDR0=*Send_Ptr++;
Send_Len--;
Pwm_Adjust_Enable=1;
}
}
#pragma vector=USART_RX_vect
__interrupt void uart0_rx_isr(void)
{
}
#pragma vector=USART_TX_vect
__interrupt void uart0_tx_isr(void)
{
if (Send_Len)
{
UDR0=*Send_Ptr++;
Send_Len--;
}
else
{
UART_RECEIVE_ENABLE();
}
}
#pragma vector = PCINT0_vect
__interrupt void pcint0_isr(void)
{
if (TESTBIT(PINB, _SPU))
{
Spu_Number++;
}
}
/*
void Pwm_Adjust(void)
{
float err;
static float Sum=0;
static float last_err=0;
float new_control;
err=(float)Target_Spu-(float)Actual_Spu;
new_control=OCR1BL;
new_control+=err*PID_KP;
Sum+=err;
new_control+=Sum*PID_KI;
new_control+=(err-last_err)*PID_KD;
if (new_control>60)
{
new_control=60;
Sum-=err;
}
else if (new_control<0)
{
new_control=0;
Sum-=err;
}
OCR1BL=ceil(new_control);
last_err=err;
}
*/
void Pwm_Adjust(void)
{
float err;
static float last_err1=0;
static float last_err2=0;
float dlt;
err=(float)Target_Spu-(float)Actual_Spu;
dlt=PID_KP*(err-last_err1)+PID_KI*err+PID_KD*(err-2*last_err1+last_err2);
dlt+=OCR1BL;
if (dlt>100)
{
dlt=100;
}
else if (dlt<0)
{
dlt=0;
}
OCR1BL=dlt+0.5;
last_err2=last_err1;
last_err1=err;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -