LED呼吸灯
main.c
#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; //LED亮Delay(Time); //延时TimeLED=1; //LED灭Delay(100-Time); //延时100-Time}}for(Time=100;Time>0;Time--) //改变亮灭时间,由亮到暗{for(i=0;i<20;i++) //计次延时{LED=0; //LED亮Delay(Time); //延时TimeLED=1; //LED灭Delay(100-Time); //延时100-Time}}}
}
直流电机调速
main.c
#include <REGX52.H>
#include "Delay.h"
#include "Key.h"
#include "Nixie.h"
#include "Timer0.h"sbit Motor=P1^0;unsigned char Counter,Compare; //计数值和比较值,用于输出PWM
unsigned char KeyNum,Speed;void main()
{Timer0_Init();while(1){KeyNum=Key();if(KeyNum==1){Speed++;Speed%=4;if(Speed==0){Compare=0;} //设置比较值,改变PWM占空比if(Speed==1){Compare=50;}if(Speed==2){Compare=75;}if(Speed==3){Compare=100;}}Nixie(1,Speed);}
}void Timer0_Routine() interrupt 1
{TL0 = 0x9C; //设置定时初值TH0 = 0xFF; //设置定时初值Counter++;Counter%=100; //计数值变化范围限制在0~99if(Counter<Compare) //计数值小于比较值{Motor=1; //输出1}else //计数值大于比较值{Motor=0; //输出0}
}
Nixie.c
#include <REGX52.H>
#include "Delay.h"//数码管段码表
unsigned char NixieTable[]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};/*** @brief 数码管显示* @param Location 要显示的位置,范围:1~8* @param Number 要显示的数字,范围:段码表索引范围* @retval 无*/
void Nixie(unsigned char Location,Number)
{switch(Location) //位码输出{case 1:P2_4=1;P2_3=1;P2_2=1;break;case 2:P2_4=1;P2_3=1;P2_2=0;break;case 3:P2_4=1;P2_3=0;P2_2=1;break;case 4:P2_4=1;P2_3=0;P2_2=0;break;case 5:P2_4=0;P2_3=1;P2_2=1;break;case 6:P2_4=0;P2_3=1;P2_2=0;break;case 7:P2_4=0;P2_3=0;P2_2=1;break;case 8:P2_4=0;P2_3=0;P2_2=0;break;}P0=NixieTable[Number]; //段码输出Delay(1); //显示一段时间P0=0x00; //段码清0,消影
}
Nixie.h
#ifndef __NIXIE_H__
#define __NIXIE_H__void Nixie(unsigned char Location,Number);#endif
Timer0.c
#include <REGX52.H>/*** @brief 定时器0初始化,100us@12.000MHz* @param 无* @retval 无*/
void Timer0_Init(void)
{TMOD &= 0xF0; //设置定时器模式TMOD |= 0x01; //设置定时器模式TL0 = 0x9C; //设置定时初值TH0 = 0xFF; //设置定时初值TF0 = 0; //清除TF0标志TR0 = 1; //定时器0开始计时ET0=1;EA=1;PT0=0;
}/*定时器中断函数模板
void Timer0_Routine() interrupt 1
{static unsigned int T0Count;TL0 = 0x9C; //设置定时初值TH0 = 0xFF; //设置定时初值T0Count++;if(T0Count>=1000){T0Count=0;}
}
*/
Timer0.h
#ifndef __TIMER0_H__
#define __TIMER0_H__void Timer0_Init(void);#endif