管理员
- 积分
- 165352
- 金钱
- 165352
- 注册时间
- 2010-12-1
- 在线时间
- 2108 小时
|
在OC1A上输出PWM,通过按键调节PWM的占空比,源码如下:
#include <mega16.h>
#include <delay.h>
#define KEY PINA.0
#define KEY1 PINA.1
#define KEY2 PINA.2
#define KEY3 PINA.3
bit juder=0;
uchar key_scan(void)
{
if(juder)
{
juder=0;
if(!KEY)return 0;
if(!KEY1)return 1;
if(!KEY2)return 2;
if(!KEY3)return 3;
}
if(KEY&&KEY1&&KEY2&&KEY3)juder=1;
return 4;
}
void display(unsigned char number,unsigned char position)//digtial show function
{
DDRB=0Xff;//set PORTA output
 ORTB=0XFF;//set PORTA output in high level
switch(position)//choice the position
{
case 1:{PORTB&=0xf8;break;}
case 2:{PORTB&=0xf9;break;}
case 3:{PORTB&=0Xfa;break;}
case 4:{PORTB&=0Xfb;break;}
case 5:{PORTB&=0Xfc;break;}
case 6:{PORTB&=0Xfd;break;}
case 7:{PORTB&=0Xfe;break;}
case 8:{PORTB&=0Xff;break;}
}
switch(number)//show number
{
case 0:{PORTB&=0x87;break;} //0
case 1:{PORTB&=0x8f;break;} //1
case 2:{PORTB&=0x97;break;} //2
case 3:{PORTB&=0x9f;break;} //3
case 4:{PORTB&=0xa7;break;} //4
case 5:{PORTB&=0xaf;break;} //5
case 6:{PORTB&=0xb7;break;} //6
case 7:{PORTB&=0xbf;break;} //7
case 8:{PORTB&=0xc7;break;} //8
case 9:{PORTB&=0xcf;break;} //9
default:{PORTB=0xff;break;} //null
}
}
void main(void)
{
uchar t=0;
uchar b1,b2,b3;
uchar key;
DDRA=0X00;
PORTA=0XFF;
PORTD=0x00;
DDRD=0x20;
TCCR1A=0x81;
TCCR1B=0x01;
//OCR1AH=0x00;
OCR1AL=0x44;
while (1)
{
b1=t%10;display(b1,8);delay_us(1000);
b2=(t/10)%10;display(b2,7);delay_us(1000);
b3=(t/100)%10;display(b3,6);delay_us(800);
key=key_scan();
if(key==0){t++;OCR1AL=t;}
if(key==1){t--;OCR1AL=t;}
};
}
|
|