×
单片机 > 单片机程序设计 > 详情

avr利用pwm控制led光暗及峰鳴器音量大小

发布时间:2020-08-24 发布时间:
|
//ICC-AVR application builder // Target : M16  

// Crystal: 4.0000Mhz  

#include   

#include   

#define uchar unsigned char

#define uint unsigned int

void port_init(void);

void timer0_init(void);

void init_devices(void);

void delay_short(uint t);

uchar scan_key(void);

void port_init(void)  

{  

PORTA = 0x00;  

DDRA   = 0x00;  

PORTB = BIT(PB3);  

DDRB   = BIT(PB3);  

PORTC = 0x00; //m103 output only  

DDRC   = 0x00;  

PORTD = 0x00;  

DDRD   = 0x00;  

}  

// WGM: PWM Phase correct

// desired value: 1KHz

// actual value:   0.980KHz (-2.0%)

void timer0_init(void)  

{  

TCCR0 = 0x00; //stop  

TCNT0 = 0x01; //set count  

OCR0   = 0xFF;   //set compare  

TCCR0 = 0x62; //start timer ; 相位修正, 8分頻

}  

//call this routine to initialize all peripherals  

void init_devices(void)  

{  

//stop errant interrupts until set up  

CLI(); //disable all interrupts  

port_init();  

timer0_init();  

MCUCR = 0x00;  

GICR   = 0x00;  

TIMSK = 0x00; //timer interrupt sources  

SEI(); //re-enable interrupts  

//all peripherals are now initialized  

}

void delay_short(uint t) // 短延時

{

   uint i;

   for (i=0;i

}

uchar scan_key(void)   // 按鍵掃瞄

{  

   uchar v;

   v = 0;      

   if ((PIND & 0x07) != 0x07)

   {

   if ((PIND & 0x01) == 0)  

   {

    v = 1;

     delay_short(1000);   

   }

   if ((PIND & 0x2) == 0)  

   {

     v = 2;

     delay_short(1000);   

   }

   if ((PIND & 0x4) == 0)  

   {

     v = 3;

     delay_short(1000);   

   }

   };

   while((PIND & 0x07) != 0x07);    // 判斷按鍵是不是放開    

   return v;   

}

void main(void)  

{   

uchar key, OCR0_V;

init_devices();  

OCR0_V = 0xff;

while(1)

{

    key = scan_key();

    if (key > 0)

    {

      if (key==1) // 減少佔空比

     {  

       OCR0_V -= 10;

       OCR0 = OCR0_V;

     };

      if (key==2) // 增加佔空比

     {  

       OCR0_V += 10;

       OCR0 = OCR0_V;

     };     

      if (key==3) // 全黑,佔空比為100%  

     {  

       OCR0_V = 0xff;

       OCR0 = OCR0_V;

     };       

    }

};  

}  

實驗板接線:

PB3 -----> JA.1 及 JM

PD0 -----> K1

PD1 -----> K2

PD2 -----> K3

TCNT0的初始值的计算和设置,

根据myhk007 提供的算法

最原始的方法:

以T0记到255溢出为例,如果AVR的主频是8M,T0为1024分频的话,那么T0每加1,需要的时间就是1024/8000000,加255次的总共延时就是1024/8000000*255,依次类推。


『本文转载自网络,版权归原作者所有,如有侵权请联系删除』

热门文章 更多
C51 特殊功能寄存器SFR的名称和地址