#include
#define uchar unsigned char
#define uint unsigned int
sbit KEY1 = P3^2; //步进电机逆时针方向转
sbit KEY2 = P3^3; //步进电机顺时针方向转
sbit KEY3 = P3^4; //步进电机调速
uchar step = 0;
bit AB_flag = 0;
unsigned char code A_Rotation[8]={0x08,0x18,0x10,0x30,0x20,0x60,0x40,0x48}; //顺时针转表格
unsigned char code B_Rotation[8]={0x48,0x40,0x60,0x20,0x30,0x10,0x18,0x08}; //逆时针转表格
/********************************************************************
* 名称 : Delay_1ms()
* 功能 : 延时子程序,延时时间为 1ms * x
* 输入 : x (延时一毫秒的个数)
* 输出 : 无
***********************************************************************/
void Delay(uint i)
{
uchar x,j;
for(j=0;j for(x=0;x<=148;x++);
}
void KEY(void)
{
if(KEY1 == 0) //按P3.2,实现步进电机的逆时针转动
{
Delay(15);
if(KEY1 == 0)
{
while(1)
{
if(KEY1 == 1)
{
Delay(15);
if(KEY1 == 1)
{
AB_flag = 0;
break;
}
}
}
}
}
if(KEY2 == 0) //按P3.3,实现步进电机的顺时针转动
{
Delay(15);
if(KEY2 == 0)
{
while(1)
{
if(KEY2 == 1)
{
Delay(15);
if(KEY2 == 1)
{
AB_flag = 1;
break;
}
}
}
}
}
if(KEY3 == 0) //按P3.4,实现步进电机的调速
{
Delay(15);
if(KEY3 == 0)
{
while(1)
{
if(KEY3 == 1)
{
Delay(15);
if(KEY3 == 1)
{
step++;
if(step == 3)
{
step = 0;
}
break;
}
}
}
}
}
}
main()
{
uchar i;
while(1)
{
KEY(); //按键处理函数
for(i=0;i<8;i++) //因为有8路的控制时序
{
if(AB_flag == 0)
{
P1 = A_Rotation[i]; //逆时针转动
}
else
{
P1 = B_Rotation[i]; //顺时针转动
}
Delay(2+step); //改变这个参数可以调整电机转速
}
}
}
#include
#define uchar unsigned char
sbit dula=P2^6;//数码管段选
sbit wela=P2^7;//数码管位选
sbit jia_key=P3^6;///加速键
sbit jian_key=P3^7;//减速键
sbit zf_key=P3^5;//正反转键
bit flag=0;//正反转标志位
uchar num=0,show_num=2,maichong=4,table_begin=0;
uchar code table[]={
0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71};
uchar code table1[]={0x01,0x02,0x04,0x08,0x04,0x02,0x01};//电机正反转I/O口电平对应表
void delay(uchar i)
{
uchar j,k;
for(j=i;j>0;j--)
for(k=125;k>0;k--);
}
void display()
{
dula=0;
P0=table[show_num];
dula=1;
dula=0;
wela=0;
P0=0xfe;
wela=1;
wela=0;
delay(5);
P0=table[0];
dula=1;
dula=0;
P0=0xfd;
wela=1;
wela=0;
delay(5);
}
void key()
{
if(jia_key==0)
{
delay(5);
if(jia_key==0)
{
num++;
if(num==4)
num=3;
while(jia_key==0);
}
}
if(jian_key==0)
{
delay(5);
if(jian_key==0)
{
if(num!=0)
num--;
else
num=0;
while(jian_key==0);
}
}
if(zf_key==0)
{
delay(5);
if(zf_key==0)
{
flag=~flag;
while(zf_key==0);
}
}
}
void dispose()
{
switch(num)
{
case 0: show_num=2;
maichong=5;
break;
case 1: show_num=4;
maichong=4;
break;
case 2: show_num=6;
maichong=3;
break;
case 3: show_num=8;
maichong=2;
break;
}
if(flag==0)
{
table_begin=0;
}
else
table_begin=4;
}
void qudong()
{
uchar i,j;
for(j=0+table_begin;j<4+table_begin;j++)
{
P1=table1[j];
for(i=0;i
display();
}
}
}
void main()
{
while(1)
{
key();
dispose();
qudong();
}
}
这是郭天祥老师的51单片机C语言配套的实验板的步进电机控制程序,看能不能参考一下。
控制的是六线制四相步进电机。
用什么传感器呢,需要可以加我,我这里有一些资料,可以交流一下,多谢。