四、代码设计
#include "sys.h"
#include "func_handler.h"
sbit PWM = P1^4;
xdata angle_1,angle_2;
xdata vate;
idata u32 cnt = 0;
idata u16 cnt_1 = 0;
idata u16 turn=1;
idata s16 PWM_count = 0;
#define T0_PERIOD_1MS 0xFF41
//#define T0_PERIOD_1MS 0xFCA4 //11.1us的定时周期
#define ANGLE_WIN_NUM_VP 0x2000
#define VATE_WIN_NUM_VP 0x2010
#define TURN_WIN_NUM_VP 0x2070
//IO引脚初始化
void io_init()
{
PORTDRV = 0x02;//驱动电流为8mA
P1MDOUT |= 0xFF;//将P1设置为输出
}
//定时器0初始化
void timer0_init()
{
//16位定时器工作模式
TMOD &= 0xFC;
TMOD |= 0x01;
//定时周期为 11.1 us
TH0 = (u8)(T0_PERIOD_1MS>>8);
TL0 = (u8)T0_PERIOD_1MS;
ET0 = 1;//使能定时器0中断
EA = 1;//使能总中断
TR0 = 1;//启动定时器0
}
//定时器0的中断服务程序
void timer0_isr() interrupt 1
{
//重新装载周期值
TH0 = (u8)(T0_PERIOD_1MS>>8);
TL0 = (u8)T0_PERIOD_1MS;
cnt++; //统计溢出的次数
if(cnt_1==5)
{
cnt_1=0;
vate=angle_1-angle_2;angle_2=angle_1;
}
//控制PWM波
if(cnt>=0&&cnt < 45.025){
PWM = 1;
}
if(cnt < PWM_count){
PWM = 1;
}else{
PWM = 0;
}
if(cnt == 1801){ //当溢出1801次,经过了20ms ,周期到了
cnt=0;
cnt_1++;
PWM = 1;
}
}
void main(void)
{
sys_init();//系统初始化
timer0_init();//定时器0初始化
io_init();//IO引脚初始化
sys_delay_ms(1);
angle_1=0;
angle_2=0;
vate=0;
cnt = 0;
PWM = 1;//一开始从高电平开始
while(1)
{ sys_read_vp(ANGLE_WIN_NUM_VP,(u8*)&angle_1,1);
PWM_count = (angle_1+90)*1.00056+45.025;
sys_write_vp(VATE_WIN_NUM_VP,(u8*)&vate,1);
}
}
五、接口连接
棕色线连接GND红色线连接VCC黄色线连接P1.4