// Cpu ATTiny13
// 频率: 内部9.6000Mhz 不分频
// winavr gcc 优化级别O0
#include
#define nop() __asm__ __volatile__("nop") //空语句
unsigned char PWM[]={0x20,0x40,0x60,0x80,0xA0,0xC0,0xE0,0xFF};
unsigned char PWMON;
unsigned char PWMVal;
//IO引脚初始化
void port_init(void)
{
PORTB = 0x08; //PB3接按键设置为输出上拉
DDRB = 0x37; //PB0为PWM输出 上电置0
}
//Timer0初始化
//快速PWM模式 频率37.500KHz
void timer0_init(void)
{
OCR0A = 0x00;
TCNT0 = 0x01; //设计数
TCCR0A = 0x03; //设置Timer0为快速PWM模式
TCCR0B = 0x01; //启动Timer0
}
//延时N毫秒
void delay_ms(void)
{
unsigned char TempCycA;
unsigned char TempCycB;
for (TempCycA=0; TempCycA<10; TempCycA++)
for (TempCycB=0; TempCycB<90; TempCycB++)
nop();
}
//主函数
int main(void)
{
unsigned int tempval=0;
unsigned int keytime=0;
port_init();
timer0_init();
PWMON = 1; //初始为PWM开启
PWMVal = 0; //第一档
OCR0A = PWM[PWMVal]; //更改占空比
TCCR0A = 0x83; //开启PWM
while(1)
{
if (!(PINB&0x08))
{
keytime = 0;
for (tempval=0; tempval<4000; tempval++)
{
if (!(PINB&0x08)) //键采样、防抖
{
keytime++;
delay_ms();
}
else
break;
}
}
if (PWMON) //PWM开启的状态下
{
if ((keytime>100)&&(keytime<1000)) //短按100-1000ms则调节
{
PWMVal++;
if (PWMVal>7) //循环
PWMVal = 0;
keytime = 0;
OCR0A = PWM[PWMVal]; //更改占空比
}
if (keytime>2999) //长按3秒则关
{
PWMON = 0;
keytime = 0;
TCCR0A = 0x03; //关闭PWM
delay_ms(); //延时
}
}
else //PWM关闭的状态下
{
if (keytime>2999) //长按3秒则开
{
PWMON = 1;
keytime = 0;
TCCR0A = 0x83; //开启PWM
}
}
}
}
相关文章