28BYJ-48四相步进电机手动调速 (单步+加减速)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include
#include
#define uchar unsigned char
#define uint unsigned int
#define fosc 8000000 //晶振:8MHZ
#define baud 9600 //波特率
const unsigned char ctrl_table1[8]={0x08,0x0c,0x04,0x06,0x02,0x03,0x01,0x09};//正转脉冲
const unsigned char anti_ctrl_table1[8]={0x09,0x01,0x03,0x02,0x06,0x04,0x0c,0x08};//反转脉冲
//const unsigned char ctrl_table2[4]={0x03,0x06,0x0c,0x09};//正
//const unsigned char anti_ctrl_table2[4]={0x09,0x0c,0x06,0x03};//反
volatile unsigned char direction=0;//0为正向,1为反向
volatile unsigned char ctrl_step=0;//驱动表步位
volatile unsigned char delay_value=0;//延时变量,用于步进电机的调速(通过延时长短进行调速)
volatile unsigned char key;//键盘控制变量
volatile unsigned char series_flag=0;//连续自转标志
//----------------------ms延时函数---------------------------
void delay_ms(unsigned int ms)
{
uint i,j;
for(i=ms;i>0;i--)
for(j=1141;j>0;j--);
}
//----------------------定时器0初始化----------------------
void timer0_init()
{
TCCR0=((1<
TIMSK=(1<
}
//----------------------IO口初始化----------------------
void PORT_INIT()
{
PORTA=0x00;//所有口初始化为上拉输入
DDRA=0xFF;
PORTB=0x00;
DDRB=0xFF;
PORTC=0x00;
DDRC=0xFF;
PORTD=0x00;
DDRD=0xFF;
}
//-------------------------定时器0溢出中断--------------------------
ISR(TIMER0_OVF_vect)
{
TCNT0=delay_value;//重装初值200(0xC8)
if(direction==0)//正向
{
if(ctrl_step==8)
{
ctrl_step=0;
PORTB=ctrl_table1[ctrl_step];
if(series_flag)
{ctrl_step++;}
}
else
{
PORTB=ctrl_table1[ctrl_step];
if(series_flag)
{ctrl_step++;}
}
}
else //反向
{
if(ctrl_step==8)
{
ctrl_step=0;
PORTB=anti_ctrl_table1[ctrl_step];
if(series_flag)
{ctrl_step++;}
}
else
{
PORTB=anti_ctrl_table1[ctrl_step];
if(series_flag)
{ctrl_step++;}
}
}
}
//-------------------------------串口初始化-------------------------------------
void usart_init(void)
{
UCSRB=0x00;
UCSRA=0X00;
UBRRL=(fosc/16/baud-1)%256;
UBRRH=(fosc/16/baud-1)/256;
UCSRC=(1<
//------------------------------串口发送----------------------------------------
void usart_char_send(uchar data)
{
while(!(UCSRA&(1<
}
//---------------------main函数----------------------
int main()
{
usart_init();
cli();//关全局中断
timer0_init();
sei();//开全局中断
PORT_INIT();
PORTB=0x00;
DDRB=0xFF;
PORTD=0xFF;
DDRD=0xFF;
// uchar i=0;
while(1)
{
//usart_char_send(0x88);
/*if(i>0)
{
PORTB|=(1<
7);//断点调试灯
//DDRB|=(1<
key=PIND;
key&=0xF0;
if(key!=0xF0)
{
delay_ms(5);//延时消抖
key=PIND;
key&=0xF0;
if(key!=0xF0)
{
switch(key)
{
case 0x70:
delay_value=delay_value-5;
usart_char_send(delay_value);
break;
case 0xB0:
delay_value=delay_value+5;
usart_char_send(delay_value);
break;
case 0xD0:
series_flag=0;
ctrl_step++;
break;
case 0xE0:
series_flag=1;
break;
}
while((PIND&0xFF)!=0xFF);//松键消抖
}
}
}
}