【蓝桥杯单片机】PWM(LED亮度调节)

实验开发板为CT107D蓝桥官方板,编译环境为MDK5

  •  按键实现不同亮度的灯光
#include

sbit L1 = P0^0;
sbit S4 = P3^3;
typedef unsigned char u8;
typedef unsigned int  u16;
typedef unsigned long u32;

void delay(u16 i)
{
	while(i --);
}

void Select573(u8 channel)
{
		switch(channel)
		{
			case 4:
				P2 = (P2 & 0x1F) | 0x80;
			break;
			case 5:
				P2 = (P2 & 0x1F) | 0xA0;
			break;
			case 6:
				P2 = (P2 & 0x1F) | 0xC0;
			break;
			case 7:
				P2 = (P2 & 0x1F) | 0xE0;
			break;
		}
}

void InitSystem()
{
	Select573(5);
	P0 = 0x00;
	Select573(4);
	P0 = 0xFF;
}

void Timer0()
{
	TMOD = 0x01;
	TH0  = (65535 - 100) / 256;	//0.1ms
	TL0  = (65535 - 100) % 256;
	
	ET0 = 1;
	EA = 1;;
}

u8 PWM_count = 0;
u8 PWM_Duty  = 0;

void Service_Timer0()	interrupt 1
{
	TH0 = (65535 - 100) / 256;	//0.1ms
	TL0 = (65535 - 100) % 256;
	
	PWM_count ++;
	if(PWM_count == PWM_Duty)
	{
		L1 = 1;
	}
	else if(PWM_count == 100)
	{
		L1 = 0;
		PWM_count = 0;
	}
}

u8 Key_count = 0;

void Switch_PWM()
{
	if(S4 == 0)
	{		
		delay(100);
		if(S4 == 0)
		{
			switch(Key_count)
			{
				case 0:
					L1 = 0;
					TR0 = 1;
					PWM_Duty  = 10;
					Key_count = 1;
					PWM_count = 0;
				break;
					case 1:
					PWM_Duty  = 50;
					Key_count = 2;
					PWM_count = 0;
				break;
					case 2:
					PWM_Duty  = 90;
					Key_count = 3;
					PWM_count = 0;
				break;
					case 3:
					L1 = 1;
					TR0 = 0;
					Key_count = 0;
					PWM_count = 0;
				break;	
			}
			while(S4 == 0);
		}
	}
}
void main()
{
	InitSystem();
	Timer0();
	while(1)
	{
		Switch_PWM();
	}
}

 

你可能感兴趣的:(蓝桥杯单片机)