- //单片机控制步进电机驱动器的程序2007-05-11 23:00#include <reg52.h>
- #define INITIAL 0xff //INPUT INITIAL POSITION
- #define END 0x001ef //THE END OF THE WORK ROUTE
- #define SPEED 500 //IT IS THE NUMBER OF THE CIRCLES.
- #define HIGHSPEED_H 0xef //THE MOVING SPEED OF THE PLANT CORRESDING TO T0 TIMER
- #define HIGHSPEED_L 0xdd
- #define WORKSPEED_H 0xda //THE WORK SPEED OF THE PLANT CORRESDING TO T0 TIMER
- #define WORKSPEED_L 0xdd
- unsigned int position;
- //speed is the current T0
- unsigned int speed;
- //direction is a sbit, 1 means up, 0 means down
- bit direction;
- //idle indicates whether the plant is moving, 0 map moving, 1 means idle.
- bit idle;
- //desired_position indicate the position which is desired.
- unsigned int desired_position;
- //move_mode currently represent the two desired moving style
- //0 means work speed(low speed), 1 means move style(high speed).
- bit move_mode;
- void initialize(void)
- {
- P1_4 = 0;
- while (P1_5)
- {
- unsigned int i;
- for (i=0; i < SPEED; i++)
- {
- }
- P1_2 = !P1_2;
- }
- position = INITIAL;
- desired_position = INITIAL;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////
- void T0int(void) interrupt 1
- {
- TR0 = 0; //Need to check if it is necessary.
- if (P1_2 && direction)
- {
- position++;
- }
- if (P1_2 && (!direction))
- {
- position--;
- }
- if (position != desired_position)
- {
- if (direction)
- {
- P1_4 = 1;
- }
- else
- {
- P1_4 = 0;
- }
- if (move_mode)
- {
- TH0 = HIGHSPEED_H;
- TL0 = HIGHSPEED_L;
- TR0 = 1;
- }
- else
- {
- TH0 = WORKSPEED_H;
- TL0 = WORKSPEED_L;
- TR0 = 1;
- }
- }
- P1_2 = ! P1_2;
- }
- //////////////////////////////////////////////////////////////////////////
- ///////////////////////////////////////////////////////////////////////////////
- void ready(void)
- {
- desired_position = INITIAL;
- move_mode = 1;
- if (desired_position > position)
- direction = 1;
- else if (desired_position < position)
- direction = 0;
- }
- ///////////////////////////////////////////////////////////////////////////////
- void work(void)
- {
- desired_position = END;
- direction = 1;
- move_mode = 0;
- }
- ///////////////////////////////////////////////////////////////////////////////
- void main (void)
- {
- initialize();
- IE = 0xfa;
- TMOD = 0x11;
- while (1)
- {
- if (!P0_0)
- {
- unsigned char i;
- unsigned char ms;
- ms = 10;
- while(ms--)
- {
- for(i = 0; i < 200; i++);
- }
- if (!P0_0)
- {
- while(!P0_0){}
- ready();
- if ( position != desired_position)
- {
- TH0 = HIGHSPEED_H;
- TL0 = HIGHSPEED_L;
- TR0 = 1;
- }
- }
- }
- if (!P0_3)
- {
- unsigned char i;
- unsigned char ms;
- ms=10;
- while(ms--)
- {
- for(i = 0; i < 200; i++);
- }
- if (!P0_3)
- {
- while(!P0_3){}
- work();
- if (position != desired_position)
- {
- TH0 = WORKSPEED_H;
- TL0 = WORKSPEED_L;
- TR0 = 1;
- }
- }
- }
- }
- }