单片机驱动步进电机

//======================//
//注释代码为角度控制模式//
//======================//
#include <reg52.h>
#define uint unsigned int
#define uchar unsigned char

uchar code forward[] = {0x01,0x03,0x02,0x06,0x04,0x0c,0x08,0x09}; //单双相八拍 === 四相八拍  使用P1.0~P1.3连接
uchar code reverse[] = {0x08,0x0c,0x04,0x06,0x02,0x03,0x01,0x09};  

// 4096pulse/r    0.087890625 degree/pulse    11.37778 pulse/degree   按11pulse/dgr误差 少0.0332度   -3.32%
uchar speed = 2;    //  8.192s/r     0.122r/s    43.945 degree/s
bit directionFlag = 0;   //转向
//uint pulseCount = 0;
//uint degree = 90;  //转动角度
//uint totalPulseCount = 1;


uchar index = 0;
uchar key = 0;

void key_scan();
void delay_10ms(uint z)
{
	uint x,y;
	for(x=z;x>0;x--)
		for(y = 110;y>0;y--);
}

main()
{

	TMOD = 0x01;
	TH0=(65536-(speed*1000))/256;  //ms
	TL0=(65530-(speed*1000))%256;
	EA = 1;
	//ET0 = 1;
	TR0 = 1;
	
	while(1)
	{
		
		key_scan();

	}
	
}

void timer0() interrupt 1
{
	/*  
	pulseCount++;
	if(pulseCount >= totalPulseCount)
	{
		ET0 = 0;
		pulseCount = 0;
	}
	*/
	TH0=(65536-(speed*1000))/256;
	TL0=(65530-(speed*1000))%256;
	if(directionFlag == 0)
		P1 = forward[index];
	else
		P1 = reverse[index];
	index++;
	if(index == 8)
			index = 0;
}




void key_scan()  //键盘扫描  四个独立按键配P3.0~P3.3
{
		key = P3&0x0f;   //一定是要按位与&,而不能&&  《《=========
		if(key != 0x0f)
		{
			delay_10ms(5);  
			key = P3&0x0f;   //再判断时也要重新赋key值 <<----------------
			if(key != 0x0f)
			{
				switch(key)
				{
					case 0x0e:    //减速
					speed+=2;
					if(speed == 12) speed = 2;  //共5档
						break;
					
					case 0x0d:
					speed-=2;		//加速
					if(speed == 0) speed = 10; 
						break;
					
					case 0x0b:
					ET0 = ~ET0;		// 启动停止,角度控制模式没有这句
					//totalPulseCount = degree*(4096/360);
					//ET0 = 1;
						break;
					
					case 0x07:
					directionFlag = ~directionFlag;  //反向
						break;
				}
				while(key != 0x0f)  // 判断按键是否松开
				{
					//delay_10ms(1);    //这里可以不用消抖,因为进入判断前已经消抖
					key = P3&0x0f;	 
				}
			}
		}
}
单片机驱动步进电机单片机驱动步进电机 stephon_100 发布了7 篇原创文章 · 获赞 2 · 访问量 95 私信 关注
上一篇:基于单片机的盆栽自动浇花系统-毕设课设protues仿真全套资料


下一篇:Canny边缘检测及实现