专注电子技术学习与研究
当前位置:单片机教程网 >> MCU设计实例 >> 浏览文章

实现LED分级亮度的简便算法

作者:佚名   来源:本站原创   点击数:  更新时间:2011年02月22日   【字体:

#include"reg52.h"
unsigned char code table[]={0xfe,0xfc,0xf0,0xe0,0xc0,0x80,0x00};
void main()
{
  unsigned char i;
  while(1)
   {
     i++;
     i&=0x07;
     P1=table;
    }
}

低电平点亮LED,i=0到7;
while循环周期*8=PWM的周期
当i=0时,D0亮
当i=1时,D0,D1亮
当i=2时,D0,D1,D2亮
。。。。。。
当i=7时,D0,D1,D2,D3,D4,D5,D6,D7全亮
也就是说,在while的8个循环中,D0一直亮,D1则只有7次亮。。。。。。D7则只有1次亮

按照这个算法,只要定义一个一维表格,就可以静态现实LED的8个不同亮度,且亮度次序任意
如果定义一个二维表格,则可以动态现实LED亮度,几乎可以任意定义次序花样

 

下面来看一个完整的二维数组渐变程序
完整代码下载地址:http://www.51hei.com/f/jianb.rar

#include "reg52.h" 
unsigned char code table[37][8]=   //定义一个2维数组 
{0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,//off 
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfe,//D0亮度等级1/8 
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfc,//D1亮度等级1/8 
0xff,0xff,0xff,0xff,0xff,0xff,0xfd,0xfc,//D1亮度等级2/8 
0xff,0xff,0xff,0xff,0xff,0xff,0xfd,0xf8,//D2亮度等级1/8 
0xff,0xff,0xff,0xff,0xff,0xff,0xf9,0xf8,//D2亮度等级2/8 
0xff,0xff,0xff,0xff,0xff,0xfb,0xf9,0xf8,//D2亮度等级3/8 
0xff,0xff,0xff,0xff,0xff,0xfb,0xf9,0xf0,//D3 
0xff,0xff,0xff,0xff,0xff,0xfb,0xf1,0xf0, 
0xff,0xff,0xff,0xff,0xff,0xf3,0xf1,0xf0, 
0xff,0xff,0xff,0xff,0xf7,0xf3,0xf1,0xf0, 
0xff,0xff,0xff,0xff,0xf7,0xf3,0xf1,0xe0,//D4 
0xff,0xff,0xff,0xff,0xf7,0xf3,0xe1,0xe0, 
0xff,0xff,0xff,0xff,0xf7,0xe3,0xe1,0xe0, 
0xff,0xff,0xff,0xff,0xe7,0xe3,0xe1,0xe0, 
0xff,0xff,0xff,0xef,0xe7,0xe3,0xe1,0xe0, 
0xff,0xff,0xff,0xef,0xe7,0xe3,0xe1,0xc0,//D5 
0xff,0xff,0xff,0xef,0xe7,0xe3,0xc1,0xc0, 
0xff,0xff,0xff,0xef,0xe7,0xc3,0xc1,0xc0, 
0xff,0xff,0xff,0xef,0xc7,0xc3,0xc1,0xc0, 
0xff,0xff,0xff,0xcf,0xc7,0xc3,0xc1,0xc0, 
0xff,0xff,0xdf,0xcf,0xc7,0xc3,0xc1,0xc0, 
0xff,0xff,0xdf,0xcf,0xe7,0xe3,0xc1,0x80,//D6 
0xff,0xff,0xdf,0xcf,0xe7,0xe3,0x81,0x80, 
0xff,0xff,0xdf,0xcf,0xe7,0x83,0x81,0x80, 
0xff,0xff,0xdf,0xcf,0x87,0x83,0x81,0x80, 
0xff,0xff,0xdf,0x8f,0x87,0x83,0x81,0x80, 
0xff,0xff,0x9f,0x8f,0x87,0x83,0x81,0x80, 
0xff,0xbf,0x9f,0x8f,0x87,0x83,0x81,0x80, 
0xff,0xbf,0x9f,0x8f,0x87,0x83,0x81,0x00,//D7 
0xff,0xbf,0x9f,0x8f,0x87,0x83,0x01,0x00, 
0xff,0xbf,0x9f,0x8f,0x87,0x03,0x01,0x00, 
0xff,0xbf,0x9f,0x8f,0x07,0x03,0x01,0x00, 
0xff,0xbf,0x9f,0x0f,0x07,0x03,0x01,0x00, 
0xff,0xbf,0x1f,0x0f,0x07,0x03,0x01,0x00, 
0xff,0x3f,0x1f,0x0f,0x07,0x03,0x01,0x00, 
0x7f,0x3f,0x1f,0x0f,0x07,0x03,0x01,0x00, 
}; 

void main()         
{ 
unsigned char i; 
unsigned int j; 
unsigned int counter; 
bit flag=0; 
while(1) 
{ 
  i++; 
  i&=0x07;       //i=0到7 
  counter++; 
  if(counter==12000)     //延时对j++ 
  { 
   if(flag==0) j++;     
   else j--; 
   counter=0; 
   if(j==36 || j==0) 
   { 
    flag=!flag;     //决定正向扫描还是逆向扫描 
    i=0; 
   } 
  } 
   P1=table[j];     //扫描第i列,扫描第j行 
} 
} 

注意:用2003时,是高电平点亮LED。要对它取反。

关闭窗口

相关文章