按键控制步进电机正反转一定设置的角度,比如一圈360度,按一次30度,一起12档。分两路控制,4个加减按键,一个按键控制复位,每路控制输出tb6600驱动器驱动两个42电机同步。同时数码管显示出来每次按键加减后的档数数值。
最好可以再增加一个可以初始化的按键可以初始化电机的行程,担心每步不够精准,按多了差步太大,这样可以初始化电机行程。因为电机控制的物件是有一圈多的行程。到顶会卡位的。
#include<reg52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit jia1=P1^4;
sbit jian1=P1^5;
sbit jia2=P1^6;
sbit jian2=P1^7;
sbit fuwei=P3^2;
sbit Motor1PWM=P3^3;
sbit Motor1Dir=P3^4;
sbit Motor2PWM=P3^5;
sbit Motor2Dir=P3^6;
uchar led[16]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F,0x77,0x7C,0x39,0x5E,0x79,0x71}; //共阴字形码表【实验】
uchar Stepper1Value, Stepper2Value;
uint Stepper1Sum, Stepper2Sum;
uint Stepper1Set, Stepper2Set;
uint Dsteps;//转动30度对应的步数
void delay(uint t) //延时函数
{
uchar i;
while(t--) for(i=0;i<200;i++);
}
void buttonValue(void)
{
if(jia1==0&&Stepper1Value<12) {
Stepper1Value++;
delay(100);
}
if(jian1==0&&Stepper1Value>1) {
Stepper1Value--;
delay(100);
}
if(jia2==0&&Stepper2Value<12) {
Stepper2Value++;
delay(100);
}
if(jian2==0&&Stepper2Value>1){
Stepper2Value--;
delay(100);
}
if(fuwei==0){ //复位
Stepper1Value=1;
Stepper2Value=1;
}
Stepper1Set=Stepper1Value*Dsteps;
Stepper2Set=Stepper2Value*Dsteps;
}
void display(void)
{
uchar ge,shi;
ge=Stepper1Value%10;
shi=Stepper1Value/10;
P2=led[shi];
P1=0xfe;
delay(3);
P1=0xff;
delay(1);
P2=led[ge];
P1=0xfd;
delay(3);
P1=0xff;
delay(1);
ge=Stepper2Value%10;
shi=Stepper2Value/10;
P2=led[shi];
P1=0xfb;
delay(3);
P1=0xff;
delay(1);
P2=led[ge];
P1=0xf7;
delay(3);
P1=0xff;
delay(1);
}
void main(void)
{
// uchar i,j;
Stepper1Value=1; //电机1初始档位
Stepper2Value=2; //电机2初始档位
Dsteps=100; //假设转动30度需要100步
Stepper1Sum=Stepper1Value*Dsteps;
Stepper2Sum=Stepper2Value*Dsteps;
Stepper1Set=Stepper1Sum;
Stepper2Set=Stepper2Sum;
TMOD=0x01;
TH0= 0xEC ; //脉冲半周期5ms,频率100Hz
TL0= 0x78 ;
TR0=1;
ET0=1;
EA=1;
while(1)
{
buttonValue();
display();
}
}
void Timer0(void) interrupt 1
{
if(Motor1PWM){
if(Stepper1Set>Stepper1Sum){
Stepper1Sum++; //电机1正转
Motor1Dir=1;
Motor1PWM=0;
}
if(Stepper1Set<Stepper1Sum){
Stepper1Sum--; //电机1反转
Motor1Dir=0;
Motor1PWM=0;
}
}else Motor1PWM=1;
if(Motor2PWM){
if(Stepper2Set>Stepper2Sum){
Stepper2Sum++; //电机2正转
Motor2Dir=1;
Motor2PWM=0;
}
if(Stepper2Set<Stepper2Sum){
Stepper2Sum--; //电机2反转
Motor2Dir=0;
Motor2PWM=0;
}
}else Motor2PWM=1;
TH0= 0xEC ; //脉冲半周期5ms,频率100Hz
TL0= 0x78 ;
}