吕布圣诞恋歌头像:利用pwm控制led光暗及峰鳴器音量大小(avr-51板的pwm實驗)

来源:百度文库 编辑:偶看新闻 时间:2024/04/28 02:51:26
//ICC-AVR application builder : 2005-4-18 12:46:03 
// 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的初始值的计算和设置
以T0记到255溢出为例,如果AVR的主频是8M,T0为1024分频的话,那么T0每加1,需要的时间就是1024/8000000,加255次的总共延时就是1024/8000000*255,依次类推。