这是大二时的程序,利用51单片机和7279芯片 控制小车,程序比较低级,是刚学单片机写得,给新人参考,毕竟里面加入了 外部中断,定时器。
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
# define DECODE1 0XC8 //方式1译码指令
# define DECODE0 0X80 //方式0译码指令
sfr T2MOD=0X9C;
int num,num2,num1,t=0;
uchar count,num3,di,gao,y;
uint ge,shi;
sbit pwm=P0^3;
sbit dianji1=P0^4;
sbit dianji2=P0^5;
sbit duoji1=P3^6;
sbit duoji2=P3^7;
sbit hongwai=P3^0;
sbit cs=P2^0;
sbit dat=P2^1;
sbit clk=P2^2;
void long_delay(void)
{
unsigned char i;
for(i=0;i<0x30;i++);
}
void short_delay(void)
{
unsigned char i;
for(i=0;i<8;i++);
}
void send_byte(unsigned char out_byte)
{
unsigned char j;
cs=0;
long_delay();
for(j=0;j<8;j++)
{
if(out_byte&0x80)
{
dat=1;
}
else
{
dat=0;
}
clk=1;
short_delay();
out_byte=out_byte*2;
}
dat=0;
}
void write7279(uchar cmd,uchar dta)
{
send_byte(cmd);
send_byte(dta);
}
void display(shi,ge)
{
write7279(DECODE0+2,shi);
write7279(DECODE0+1,ge);
}
void Time0_Int() interrupt 1
{
uchar x;
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
x++;
if(x>=20)
{
y++;
x=0;
ge=y/10;
shi=y%10;
}
display( shi, ge);
}
void int_0() interrupt 0
{
if(hongwai==0)
{
if(hongwai==0)
num2++;
}
if(duoji1==0)
{
if(duoji1==0)
num1=num1+1;
}
if(duoji2==0)
{
if(duoji2==0)
num1=num1-1;
}
}
void time_1() interrupt 5
{
TF2=0;
count++;//0.1ms次数加1
count=count%200;
if(count<num1)
pwm=1;
else
{
pwm=0;
if(count==100)
{
num3++;
if(num3>=60) //舵机角度延时
{
num1=15;
num3=0;
}
}
}
}
uchar dianjikongzhi(uchar num2)//直流电机数据处理
{
switch(num2)
{
case 0:
di=5;
gao=200;
break;
case 1:
di=5;
gao=250;
TR0=1;
break;
case 2:
di=5;
gao=200;
break;
case 3:
di=200;
gao=50;
break;
case 4:
di=5;
gao=200;
break;
case 5:
di=200;
gao=5;
break;
case 7:
di=5;
gao=200;
break;
case 8:
di=5;
gao=200;
break;
case 9:
di=200;
gao=50;
break;
case 10:
di=0;
gao=200;
break;
case 11:
di=20;
gao=200;
case 12:
di=10;
gao=100;
break;
}
return(num2);
}
void qudong()
{ uchar j,i;
if(num2<6)
{
dianji2=0;
for(i=0;i<di;i++)
{
dianji1=0;
}
for(i=0;i<gao;i++)
{
dianji1=1;
}
}
if(num2==6)
{
int t0=0;
dianji1=0;
dianji2=0;
t0=y;
for(; ;)
{ if ((y-t0)>=2 )
break;
}
dianji1=0;
dianji2=1;
for(; ;)
{
if(num2==7)
break;
}
}
if(num2>6&&num2<12)
{
uchar i;
dianji1=0;
for(i=0;i<di;i++)
{
dianji2=0;
}
for(i=0;i<gao;i++)
{
dianji2=1;
}
}
if(num2==12)
{
dianji1=0;
dianji2=0;
TR1=0;
TR0=0;
EA=0;
display(shi,ge);
for(j=1000;j>0;j--);
}
}
main()
{
TMOD=0x11;//设置T1计时,T0计时;都工作在方式1
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
RCAP2H=(65536-100)/256;
RCAP2L=(65536-100)%256;
y=0;
TH1 = 0xfe;
TL1 = 0x33;
EA=1;
EX0=1;
IT0=1;
ET0=1;
ET1=1;
EX1=1;
IT1=1;
TR2=1;
ET2=1;
PX1=1;
PT1=0;
num1=15;
num2=0;
while(1)
{
dianjikongzhi(num2);
qudong();
}
}