标题: STC12单片机按键控制PWM程序 [打印本页]

作者: 2545010433    时间: 2021-11-10 14:42
标题: STC12单片机按键控制PWM程序
  1. #include <reg52.h>
  2. typedef unsigned char uchar;
  3. typedef unsigned int uint;

  4. sbit Key1=P3^0;
  5. sbit Key2=P3^1;
  6. sbit PWM=P1^0;
  7. uchar  code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
  8. uchar count,time,i;

  9. void delayms(uint k)
  10. {
  11.         uint i,j;
  12.         for(i=k;i>0;i--)
  13.                 for(j=110;j>0;j--);
  14. }
  15. void Timer0Init()                //100微秒@12.000MHz
  16. {
  17.         TMOD |= 0x02;                //设置定时器模式
  18.         TL0 = 0x9C;                //设置定时初值
  19.         TH0 = 0x9C;                //设置定时重载值
  20.         TF0 = 0;                //清除TF0标志
  21.         TR0 = 1;                //定时器0开始计时
  22.         EA=1;
  23.         ET0=1;
  24. }
  25. void display()
  26. {
  27.         static bit num=0;
  28.         P0 = 0x00;
  29.         if(num)
  30.         {
  31.                 P2=~0xfe;
  32.                 P0=table[i/10];
  33.                 num=~num;
  34.         }
  35.         else
  36.         {
  37.                 P2=~0xfd;
  38.                 P0=table[i%10];
  39.                 num=~num;
  40.         }
  41. }

  42. void main( )
  43. {
  44.         Timer0Init();      
  45.         count=99;
  46.         i=100-count;
  47.         while(1)
  48.         {
  49.           if(!Key1)   //
  50.             {
  51.              delayms(10);
  52.              if(!Key1)
  53.                {
  54.                  if(count>1)
  55.                     count--;               
  56.                     while(!Key1);
  57.                     i=100-count;
  58.                 }
  59.              }
  60.           if(!Key2)
  61.            {
  62.              delayms(10);
  63.               if(!Key2)
  64.                 {
  65.                  if(count<99)
  66.                     count++;               
  67.                    while(!Key2);
  68.                    i=100-count;
  69.                  }
  70.            }
  71.        }
  72. }
  73. void timer0() interrupt        1  
  74. {
  75.         time++;
  76.         if(count>=time)
  77.                 PWM=1;
  78.         else   PWM=0;
  79.         if(time>99)
  80.                 time=0;
  81.         if(time%10==0)
  82.                 display();
  83. }
复制代码







欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1