- #include <reg52.h> //头文件
- #define uchar unsigned char
- #define uint unsigned int
- uchar code CCW[8]={0x08,0x0c,0x04,0x06,0x02,0x03,0x01,0x09}; //逆时钟旋转相序表
- uchar code CW[8]={0x09,0x01,0x03,0x02,0x06,0x04,0x0c,0x08}; //正时钟旋转相序表
- sbit S2=P3^0;
- sbit S3=P3^1;
- void delaynms(uint aa)
- {
- uchar bb;
- while(aa--)
- {
- for(bb=0;bb<115;bb++) //1ms基准延时程序
- {
- ;
- }
- }
- }
- void motor_ccw(void) //正转每次转5.625度
- {
- uchar i,j;
- for(j=0;j<64;j++)//电机旋转一周,不是外面所看到的一周,是里面的传动轮转了一周
- {
- for(i=0;i<8;i++) //旋转45度
- {
- P1=CCW[i];
- delaynms(2); //调节转速
- }
- }
- }
- void motor_cw(void)//反转每次转5.625度
- {
- uchar i,j;
- for(j=0;j<64;j++)
- {
- for(i=0;i<8;i++) //旋转45度
- {
- P1=CW[i];
- delaynms(2); //调节转速
- }
- }
- }
- //停止转动
- void MotorStop(void)
- {
- P1=0x00;
- }
- void main(void)
- {
- uchar r;
- uchar N=4; //因为步进电机是减速步进电机,减速比的1/64 ,所以N=64时,步进电机主轴转一圈 64*5.625=360
- while(1)
- {
- // if(S2==0)
- {
- for(r=0;r<N;r++)
- {
- motor_ccw(); //电机正转
- delaynms(100);
- MotorStop();
- delaynms(100);
- }
- MotorStop(); //停止转动
- delaynms(500);
- }
- // if(S3==0)
- {
- for(r=0;r<N;r++)
- {
- motor_cw(); //电机反转
- delaynms(100);
- MotorStop();
- delaynms(100);
- }
- MotorStop(); //停止转动
- delaynms(500);
- }
- }
- }
复制代码 |