直流电机驱动PWM

 正接时正转,反接时反转

 

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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值