EDN首页   博客首页

日志档案

发表于 2007-6-19 10:18:46

2

标签: 无标签

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

 

//ICC-AVR application builder // Target : M16 

// Crystal: 4.0000Mhz 

 

#include <iom16v.h> 

#include <macros.h> 

 

#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<t;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的主频是8MT01024分频的话,那么T0每加1,需要的时间就是1024/8000000,加255次的总共延时就是1024/8000000*255,依次类推。

系统分类: 单片机   |   用户分类: AVR单片机学习   |   来源: 转贴   |   【推荐给朋友】   |   【添加到收藏夹】

    阅读(670)    回复(0)  

投一票您将和博主都有获奖机会!