AVR單片機(jī)(學(xué)習(xí)ing)—(四)、ATMEGA16的定時(shí)/計(jì)數(shù)器—04
掃描二維碼
隨時(shí)隨地手機(jī)看文章
四、ATMEGA16的定時(shí)/計(jì)數(shù)器
四—(04)、0~5V數(shù)字電壓調(diào)整器
PWM數(shù)字電壓調(diào)整器
由于定時(shí)器2(就是上一個(gè)實(shí)驗(yàn))只能構(gòu)成8位的PWM,作為數(shù)字電壓調(diào)整器其精度不夠,這里用定時(shí)器1構(gòu)成10位PWM來實(shí)現(xiàn)0~5V的數(shù)字電壓調(diào)整值
顯然精度提高了嗎~你看看后面的小數(shù)點(diǎn)就懂得了~~呵呵,按鍵按的我手疼~~就不按了~~
下面的是程序:(我以后只給出主程序~~)
//------------------------------------------------------------------------------
//PWM數(shù)字電壓調(diào)整器
//由于定時(shí)器2只能構(gòu)成8位的PWM,作為數(shù)字電壓調(diào)整器其精度不夠,這里用定時(shí)器1構(gòu)成10位PWM來實(shí)現(xiàn)0~5V的數(shù)字電壓調(diào)整值
#include"ioavr.h"
#include"intrinsics.h"
#include"lcdinit.h"
#include"delayics.h"
#include"bitics.h"
//------------------------------------------------------------------------------
uchar __flash title[]={"PWM Test"};
uchar __flash test[]={"OCR1:0000 0.000V"};
uintwide;
//------------------------------------------------------------------------------
//端口初始化函數(shù)
voidport_init()
{
DDRA=0XFF;
PORTA=0X00;
DDRB=0XFF;
PORTB=0X00;
DDRD=0XF0;
PORTD=0X0F;
}
//------------------------------------------------------------------------------
//T1初始化函數(shù)
voidtimer1_init()
{
TCCR1A=0X83;//選中通道A,工作在十位相位修正PWM模式下,8分頻
TCCR1B=0X02;
}
//------------------------------------------------------------------------------
//芯片初始化函數(shù)
voiddevice_init()
{
port_init();
timer1_init();
}
//------------------------------------------------------------------------------
//按鍵INT0檢測(cè)函數(shù)
voidint0_scan()
{
if(GET_BIT(PIND,2)==0)
{
delay_ms(4);
{
if(GET_BIT(PIND,2)==0)
{
if(wide<1023)
wide++;
while(!GET_BIT(PIND,2));//等待松手?。?!
}
}
}
}
//------------------------------------------------------------------------------
//按鍵INT1檢測(cè)函數(shù)
voidint1_scan()
{
if(GET_BIT(PIND,3)==0)
{
delay_ms(4);
if(GET_BIT(PIND,3)==0)
{
if(wide>0)
wide--;
while(!GET_BIT(PIND,3));//等待松手~~~~
}
}
}
//------------------------------------------------------------------------------
//main
voidmain()
{
long x;
uintvoltage,temple;
device_init();
lcd_init();
delay_s(1);
lcd_display_chars(0x80,title,8);
lcd_display_chars(0x80+0x40,test,16);
while(1)
{
voltage=wide;
temple=wide;
OCR1AH=(uchar)(wide>>8);//給OCR1AH,OCR1AL裝數(shù)值
OCR1AL=(uchar)(wide&0x00ff);
int0_scan();
int1_scan();
lcd_display_onechar(0x80+0x40+5,(temple/1000)+0x30);
lcd_display_onechar(0x80+0x40+6,(temple00/100)+0x30);
lcd_display_onechar(0x80+0x40+7,(temple0/10)+0x30);
lcd_display_onechar(0x80+0x40+8,(temple)+0x30);
x=(long)voltage;
x=(x*5000)/1023;
voltage=(uint)x;
lcd_display_onechar(0x80+0x40+10,(voltage/1000)+0x30);
lcd_display_onechar(0x80+0x40+12,(voltage00/100)+0x30);
lcd_display_onechar(0x80+0x40+13,(voltage0/10)+0x30);
lcd_display_onechar(0x80+0x40+14,(voltage)+0x30);
}
}