转帖手电论坛littleboy: atiny13+AN9926,10段可调带闪,电池电压检测,电池电压检测
XXXXXXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXp?tid=34562&highlight=tiny13
程序如下:
#include <avr/io.h>
#include <avr/signal.h>
#include <avr/interrupt.h>
#include <avr/delay.h>
#include <avr/eeprom.h>
#define key1 PB1
#define key2 PB4
#define set_led_ddrDDRB|=_BV(PB0)
#define clr_led_ddrDDRB&=~_BV(PB0)
#define led_offPORTB&=~_BV(PB0)
#define led_onPORTB|=_BV(PB0)
#define uchar unsigned char
#define uint unsigned int
#define uint8 uint8_t
/* 定义全局变量 */
int light=205;
int inter_count=0;
uchar adc_val;
uint8 power=0,cpu_sta=0x20,flash_sign=0,flash_count=0;
//********** 按键检测 *******************
void check_key(void)
{
if(!(PINB&0X10))
{
power=0;
while(!(PINB&0X10)) ;//按住按键2s进入闪烁模式,以4Hz的频率闪烁
_delay_ms(5);
}
}
//****** 电池电压检测 *****************
void adc_check(void)
{
adc_val=ADCH;
if(adc_val<0x7A)
{
light=0;
DDRB=0X00;
MCUCR=0X20;
inter_count=0;
PORTB=0X02;
}
}
//********** 开灯和关灯 **************
SIGNAL(SIG_INTERRUPT0)
{
inter_count++;
flash_sign=0;
flash_count=0;
if(inter_count==1)//开灯,配置寄存器
{
PORTB=0X13;
power=1;
cpu_sta=0;
set_led_ddr;
light=eeprom_read_byte(0);
_delay_ms(1);
OCR0A=light;//比较匹配值,ledl亮度
TCNT0=0;
TCCR0A=0Xc3;//比较匹配模式,快速PWM模式
TCCR0B=0X01;//64分频,输出频率f=70Hz
TIMSK0=0X02;//开比较匹配中断
ADMUX=0X63;
DIDR0=0X08;
ADCSRB=0X00;
ADCSRA=0Xe3;
while(!(PINB&0X02));
_delay_ms(20);
}
if(inter_count>=2)
{
light+=30;
if(light>250) light=1;
while(!(PINB&0X02));
_delay_ms(5);
}
if(power==0)
{
eeprom_write_byte(0,light);
_delay_ms(1);
cpu_sta=0x20;
clr_led_ddr;
led_off;
TCCR0B=0;
DDRB=0X00;
PORTB=0X02;
flash_count=0;
inter_count=0;
}
}
//*********** 电池电压检测 ***********
SIGNAL(SIG_OVERFLOW0)
{
if(ADCSRA&0X10) adc_check();
if(!(PINB&0X10))
{
flash_count++;
if(flash_count>254) flash_sign=1;
}
else ;
if(flash_sign==1)
{
TCCR0B=0X04;
OCR0A=205;
}
else
{
TCCR0B=0X01;
OCR0A=light;
}
}
//******* 主程序 **************
int main(void)
{
GIMSK=0X40;
PORTB=0x02;
CLKPR=0X80;
CLKPR=0X06;
eeprom_write_byte(0,light);
_delay_ms(1);
sei();
while(1)
{
check_key();
MCUCR=cpu_sta;
if(power==0) asm("sleep");
}
}
功能:按键1为开机加调光,关机时,按下按键1,灯亮,然后按按键1调节亮度,先由亮至暗,然后至亮,循环.
此时按下按键2,然后再按下按键1,关灯.关灯时记录上一次灯的亮度,开灯自动读取..
若在开灯后长按按键2,灯爆闪...频率大概是2Hz.爆闪时按下按键1关灯
功耗(用万用表测量的,不是很准确,不过差不了很远):关灯电流:170uA,按此计算,1天放电=170uA*24=4mAH,10天放电=4*10=40mAH
软件设定锂电保护电压是3.2V左右.档数由软件设定,可更改..