#include
#include
//声明本模块中所调用的函数类型
void delay(unsigned int endcount); //延时函数,延时为endcount*0.5毫秒
void run(); //步进电机运行控制函数
void stop(); //步进电机停止函数
//定义变量
unsigned int count; //延时函数用计数器
static int step_index; //步进索引数,值为0-7
static bit turn; //步进电机转动方向
static bit stop_flag; //步进电机停止标志
static int speedlevel; //步进电机转速参数,数值越大速度越慢,最小值为1,速度最快
static int steptimecount; //步进电机每步时长倒计数
static unsigned char powertimecount; //步进电机每步已通电时间计数
void main(void)
{
ADCON1=0B00000110; //设置RE端口为普通I/O口
TRISE2=0;
TRISC2=0;
TRISC0=0;
TRISC1=0;
step_index = 0;
stop_flag = 0;
steptimecount = 0;
stop(); //步进电机停止
T0CS=0; //选择内部指令周期信号为TMR0的时钟源
PSA=0; //TMR0使用预分频器
PS2=0; //预分频器分频比1:16
PS1=1;
PS0=1;
T0IF=0; //清除TMR0中断标记
TMR0=0X65; //TMR0设置初值
T0IE=1; //TMR0中断允许
GIE=1; //全局中断使能
do{
stop_flag=0;
turn = 0;
speedlevel =7;
delay(1000); //延时2.5秒
speedlevel = 3;
delay(1000);
stop_flag=1;
delay(1000);
stop_flag=0;
turn = 1;
speedlevel = 7;
delay(1000);
speedlevel =3;
delay(1000);
stop_flag=1;
delay(1000);
}while(1);
}
//定时器0中断处理
void interrupt clkint(void)
{
TMR0=0X65; //设定时每隔2.5MS中断一次
T0IF=0; //清除TMR0中断标记
count++;
steptimecount--;
if(powertimecount<=1) //每步最短通电时间5ms
{
powertimecount++; //未达最大值时加1
}
if(powertimecount==1)
{
stop();
}
else if (steptimecount<=0)
{
powertimecount=0;
if (stop_flag==1)
{
stop();
}
else
{
steptimecount = speedlevel;
run();
}
}
}
void delay(unsigned int endcount)
{
count=0;
do{}while(count
void run()
{
switch(step_index)
{
case 0: RC2=1; RC0=0; RC1=0; RE2=0; break;
case 1: RC2=1; RC0=1; RC1=0; RE2=0; break;
case 2: RC2=0; RC0=1; RC1=0; RE2=0; break;
case 3: RC2=0; RC0=1; RC1=1; RE2=0; break;
case 4: RC2=0; RC0=0; RC1=1; RE2=0; break;
case 5: RC2=0; RC0=0; RC1=1; RE2=1; break;
case 6: RC2=0; RC0=0; RC1=0; RE2=1; break;
case 7: RC2=1; RC0=0; RC1=0; RE2=1;
}
if (turn==0)
{
step_index++;
if (step_index>7)
step_index=0;
}
else
{
step_index--;
if (step_index<0)
step_index=7;
}
}
void stop() //使步进电机处于停机状态
{
RC2=0; //M1
RC0=0; //M3
RC1=0; //M2
RE2=0; //M4
}
上一篇:PIC入门5,1602ALCD显示实验
下一篇:PIC入门3,SPI通信和串口调试实验
推荐阅读最新更新时间:2024-03-16 15:18