|
//20kHz PWM 可调,步进2%。带显示,楼主小菜菜上课溜号了频率不会写,下面代码应该是1khz的,该怎么改呢???还请诸位不吝赐教,先行谢过了- /* Main.c file generated by New Project wizard
- *
- * Created: 周六 5月 30 2020
- * Processor: AT89C51
- * Compiler: Keil for 8051
- */
- #include<reg51.h>
-
-
- #define uint unsigned int
-
- #define uchar unsigned char
- unsigned char num1;
-
- unsigned char dis;
- unsigned char code nondis[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};//0-9
- uchar time;
-
- double count=70; //定义占空比,并初始占空比为70%
-
- sbit PWM=P0^0; //P0^0口输出PWM
-
- sbit key_add=P3^4; //加的按键
-
- sbit key_dec=P3^5; //减的按键
-
-
-
-
- void delayxms(uint z); //延时
-
- void Motor_add(); //增加占空比
-
- void Motor_dec(); //减少占空比
-
- void timer0_init(); //定时器0初始化
- //显示函数
- void display()
- {
-
-
- unsigned char gewei,shiwei,baiwei;
- baiwei=num1/100;
- gewei=num1%10;
- shiwei=(num1/10)%10;
- P2=nondis[gewei];//个位
- P0=0x80;
- delayxms(1);
- P2=0xff;
- P2=nondis[shiwei];//十位
- P0=0x40;
- delayxms(1);
- P2=0xff;
- P2=nondis[baiwei];//百位
- P0=0x20;
- delayxms(1);
- P2=0xff;
-
- }
-
-
-
- void main()
-
- {
-
- timer0_init();
-
- delayxms(5);
-
- while(1)
-
- {
- Motor_add();
-
- Motor_dec();
- num1 = count;
- display();//显示函数
-
- }
-
- }
-
-
- //延时xms程序
- void delayxms(uint z) //延时xms程序
-
- {
-
- uint x,y;
-
- for(y=z;x>0;x--)
-
- for(y=110;y>0;y--);
-
- }
-
-
- //加
- void Motor_add()
-
- {
-
- if(key_add==0)
-
- {
-
- delayxms(2); //此处时间不能太长,否者会的中断产生冲突
-
- if(key_add==0)
-
- {
-
- count+=2; //每按一次加速按键占空比加2
-
- if(count>=98) //限定占空比上限
-
- {
-
- count=98;
-
- }
-
- }
-
- while(!key_add);
-
- }
-
- }
-
- //减
- void Motor_dec()
-
- {
-
- if(key_dec==0)
-
- {
-
- delayxms(2);//此处时间不能太长
-
- if(key_dec==0)
-
- {
-
- count-=2; //每按一次减速按键占空比减2
-
- if(count<=25) //限定占空比下限
-
- {
-
- count=25;
-
- }
-
- }
-
- while(!key_dec);
-
- }
-
- }
-
-
- /***********定时器0初始化***********/
-
- void timer0_init()
-
- {
-
- TMOD=0x01; //定时器0工作于方式1
-
- TH0=(65536-10)/256;
-
- TL0=(65536-10)%256;
-
- TR0=1;
-
- ET0=1;
-
- EA=1;
-
- }
-
-
- /**************定时0中断处理******************/
-
- void timer0_int() interrupt 1
-
- {
-
-
- TR0=0; //设置定时器初值期间,关闭定时器
-
- TH0=(65536-10)/256;
-
- TL0=(65536-10)%256;
-
- TR0=1;
-
-
- time++;
-
- if(time<count) //count为占空比
-
- {
-
- PWM=1; //输出高电平
-
- }
-
- else
-
- PWM=0;
-
- if(time>=100)//20khz
-
- {
-
- time=0;
-
- }
-
- }
复制代码
|
-
888.png
(180.25 KB, 下载次数: 88)
仿真图哥哥们
|