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

51单片机 专栏收录该内容
68 篇文章 0 订阅
#include <reg52.h>

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 <reg52.h>
#include <intrins.h>

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¡ì
    }
}


  • 2
    点赞
  • 3
    评论
  • 17
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值