51单片机 步进电机的驱动和旋转角度控制

#include 

typedef unsigned char uint8_t;
typedef unsigned int uint16_t;
typedef unsigned long uint32_t;
//1-2ÏàÀø´Å£¬µÍµçƽÓÐЧ
uint8_t code beatCode[8] = {  
    0xE, 0xC, 0xD, 0x9, 0xB, 0x3, 0x7, 0x6  
};
uint32_t beats = 0;
uint8_t T0RH = 0, T0RL = 0;

void configTmr0(uint16_t ms);
void setTurningAngle(uint32_t angle);
void turnStepper();

void main() {
    configTmr0(2);
    setTurningAngle(2 * 360 + 180);
    while (1);
}

void setTurningAngle(uint32_t angle) {
    EA = 0;	//¹Ø×ÜÖжÏ
    beats = angle * 4076 / 360;
    EA = 1;
}
//1-2ÏàÀø´Å·½Ê½
void turnStepper() {
	static uint8_t index = 0;
	uint8_t tmp; 
	
	tmp = P1;  
    tmp &= 0xF0;  
    tmp |= beatCode[index];  
    P1 = tmp;  
    index = ++index & 0x07;
}

void configTmr0(uint16_t ms) {
    uint32_t tmp;

    tmp = 11059326 / 12;
    tmp = tmp * ms / 1000;
    tmp = 65536 - tmp;
    tmp += 28;
    T0RL = tmp;
    T0RH = tmp >> 8;

    EA = 1;
    TMOD = 0x01;
    TH0 = T0RH;
    TL0 = T0RL;
    ET0 = 1;
    TR0 = 1;
}

void tmr0IntSrv() interrupt 1 {
    TH0 = T0RH;
    TL0 = T0RL;
    if (beats) {
        turnStepper();
        beats--;
    } else {
        //P1 |= 0x0F;     //0ÓÐЧ
    }
}



下面是使用库函数循环左移实现的:

#include 
#include 

typedef unsigned char uint8_t;
typedef unsigned int uint16_t;
typedef unsigned long uint32_t;

uint32_t beats = 0;
uint8_t T0RH = 0, T0RL = 0;

void configTmr0(uint16_t ms);
void setTurningAngle(uint32_t angle);
void turnStepper();

void main() {
    configTmr0(2);
    setTurningAngle(2 * 360 + 180);
    while (1);
}

void setTurningAngle(uint32_t angle) {
    EA = 0;    //1??¡§¨º¡À?¡Â0?D??
    beats = angle * 4076 / 360;
    EA = 1;
}
//1-2?¨¤¨¤?¡ä?¡¤?¨º?
void turnStepper() {
    static uint8_t beatCode1 = 0xEE;      //11101110
    static uint8_t beatCode2 = 0xDD;      //11001100
    static bit flag = 0;
    uint8_t tmp;

    tmp = P1;
    tmp &= 0xF0;
    if (flag == 0) {
        tmp |= (beatCode1 & 0x0F);
        beatCode1 = _crol_(beatCode1, 1);
    } else {
        tmp |= (beatCode2 & 0x0F);
        beatCode2 = _crol_(beatCode2, 1);
    }
    P1 = tmp;
    flag = ~flag;
}

void configTmr0(uint16_t ms) {
    uint32_t tmp;

    tmp = 11059326 / 12;
    tmp = tmp * ms / 1000;
    tmp = 65536 - tmp;
    tmp += 28;
    T0RL = tmp;
    T0RH = tmp >> 8;

    EA = 1;
    TMOD = 0x01;
    TH0 = T0RH;
    TL0 = T0RL;
    ET0 = 1;
    TR0 = 1;
}

void tmr0IntSrv() interrupt 1 {
    TH0 = T0RH;
    TL0 = T0RL;
    if (beats) {
        turnStepper();
        beats--;
    } else {
        //P1 |= 0x0F;     //0¨®DD¡ì
    }
}


你可能感兴趣的:(51单片机)