谁可以帮我编一个51单片机型号为STC89C52RC 舵机型号为mg995的转向程序?

2024-12-21 23:42:11
推荐回答(1个)
回答1:

#include
#define uchar unsigned char
#define uint unsigned int
uchar count,jd;
sbit pwm=P1^0;
sbit jia=P3^2;
sbit jian=P3^3;
uchar code table[10] = {0x3f,0x06,0x5b,
0x4f,0x66,0x6d,
0x7d,0x07,0x7f,0x6f};
//延时函数
void delay(uchar x)
{
uchar i,j;
for(i=x;i>0;i--)
for(j=125;j>0;j--);
}
//定时器初始化
void Time0_init()
{
TMOD=0x01; //定时器0工作方式1
IE=0x82;
TH0=0xfe;
TL0=0x33; //11.0592MHZ晶振,0.5ms
TR0=1;
}
//定时器0中断程序
void Time0() interrupt 1
{
TH0=0xfe;
TL0=0x33;
if(count pwm=1; //是,pwm输出高电平
else
pwm=0; //否,输出低电平
count=count+1;
count=count%40; //次数始终保持为40,即保持周期为20ms
}
//按键扫描
void keyscan()
{
if(jia==0)
{
delay(10);
if(jia==0)
{
jd++; //角度增加 1
count=0; //按键按下则20ms周期重新开始计时
if(jd==6)
jd=5; //已经是180度,保持
while(jia==0);
}
}
if(jian==0)
{
delay(10);
if(jian==0)
{
jd--;
count=0;
if(jd==0)
jd=1; //已经0度,保持
while(jian==0);
}
}
}
//数码管显示
void display()
{
uchar bai ,shi,ge ;
switch(jd)
{
case 1:
bai=0;
shi=0;
ge=0;
break;
case 2:
bai=0;
shi=4;
ge=5;
break;
case 3:
bai=0;
shi=9;
ge=0;
break;
case 4:
bai=1;
shi=3;
ge=5;
break;
case 5:
bai=1;
shi=8;
ge=0;
break;
}
P0=table[bai];
P2=1;
delay(5);
P0=table[shi];
P2=2;
delay(5);
P0=table[ge];
P2=3;
delay(5);
}
void main()
{
//jd=1;
count=0;
Time0_init();
while(1)
{
keyscan();
display();
}
}