正接时正转,反接时反转
IN为低电平时,三极管导通
IN为高电平时,三极管断开
P10口如果给1,就为0
主循环写法
while(1)
{
for(Time=0;Time<100;Time++)
{
for(i=0;i<20;i++){
LED=0;
Delay(Time);//亮的时间
LED=1;
Delay(100-Time);//暗的时间
}
}
}
#include <REGX52.H>
sbit LED=P2^0;
void Delay(unsigned int t)
{
while(t--);
}
void main()
{
unsigned char Time,i;
while(1)
{
for(Time=0;Time<100;Time++)
{
for(i=0;i<20;i++){
LED=0;
Delay(Time);//亮的时间
LED=1;
Delay(100-Time);//暗的时间
}
}
}
}
电机调速:
新思路:
Counter%=100;//相当于if(Counter>=100){Counter=0;}
#include <REGX52.H>
sbit LED=P2^0;
unsigned char Counter,Compare;//计数器,比较
void Timer_Init()
{
TMOD=0x01;
TL0=0x9c;//100us
TH0=0xff;
TR0=1;
ET0=1;
EA=1;
}
void main()
{
Timer_Init();
Compare=1;
while(1)
{
}
}
void Timer0_Routine() interrupt 1
{
TL0=0x9c;//100us
TH0=0xff;
Counter++;
Counter%=100;//相当于if(Counter>=100){Counter=0;}
if(Counter<Compare)
{
LED=0;
}
else
{
LED=1;
}
}
按键控制电机:
#include <REGX52.H>
sbit LED=P2^0;
sbit Motor=P1^0;
void Delay(unsigned int xms)
{
unsigned char i, j;
while(xms--)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
}
}
unsigned char Key(){
unsigned char KeyNumber=0;
if(P3_1==0){Delay(20);while(P3_1==0);Delay(20);KeyNumber=1;}
if(P3_0==0){Delay(20);while(P3_0==0);Delay(20);KeyNumber=2;}
if(P3_2==0){Delay(20);while(P3_2==0);Delay(20);KeyNumber=3;}
if(P3_3==0){Delay(20);while(P3_3==0);Delay(20);KeyNumber=4;}
return KeyNumber;
}
unsigned char Counter,Compare;//计数器,比较
unsigned char KeyNum,Speed;
void Timer_Init()
{
TMOD=0x01;
TL0=0x9c;//100us
TH0=0xff;
TR0=1;
ET0=1;
EA=1;
}
void main()
{
Timer_Init();
while(1)
{
KeyNum=Key();
if(KeyNum==1)
{
Speed++;
Speed%=4;
if(Speed==0){Compare=0;}
if(Speed==1){Compare=5;}
if(Speed==2){Compare=50;}
if(Speed==3){Compare=100;}
}
}
}
void Timer0_Routine() interrupt 1
{
if(KeyNum==1)
{
P2_3=0;
}
TL0=0x9c;//100us
TH0=0xff;
Counter++;
Counter%=100;//相当于if(Counter>=100){Counter=0;}
if(Counter<Compare)
{
Motor=1;
}
else
{
Motor=0;
}
}