单片机定时器产生pwm

 
利用定时器产生不同占空比的PWM波形输出.
//ICC-AVR application builder : 2006-7-14 16:54:48
// Target : M128
// Crystal: 14.7456Mhz

#include <iom128v.h>
#include <macros.h>

//#define PWM_select  (PINC&3)

void port_init(void)
{
 PORTA = 0xFF;
 DDRA  = 0x00;
 PORTB = 0xFF;
 DDRB  = 0xFF;
 PORTC = 0x03; //输入,上拉电阻使能
 DDRC  = 0xFf;
 PORTD = 0xFF;
 DDRD  = 0x00;
 PORTE = 0xFF;
 DDRE  = 0x00;
 PORTF = 0xFF;
 DDRF  = 0x00;
 PORTG = 0x1F;
 DDRG  = 0x00;
}

//TIMER1 initialisation - prescale:8
// WGM: 0) Normal, TOP=0xFFFF
// desired value: 1Hz
// actual value: Out of range
void timer1_init(void)
{
 TCCR1B = 0x00; //stop
 TCNT1H = 0x00 /*INVALID SETTING*/; //setup
 TCNT1L = 0x00 /*INVALID SETTING*/;
 OCR1AH = 0x00 /*INVALID SETTING*/;
 OCR1AL = 0x00 /*INVALID SETTING*/;
 OCR1BH = 0x00 /*INVALID SETTING*/;
 OCR1BL = 0x00 /*INVALID SETTING*/;
 OCR1CH = 0x00 /*INVALID SETTING*/;
 OCR1CL = 0x00 /*INVALID SETTING*/;
 ICR1H  = 0x00 /*INVALID SETTING*/;
 ICR1L  = 0x00 /*INVALID SETTING*/;
 TCCR1A = 0x91;//8位PWM,
 TCCR1B = 0x02; //预分频8
}

//call this routine to initialise all peripherals
void init_devices(void)
{
 //stop errant interrupts until set up
 CLI(); //disable all interrupts
 XDIV  = 0x00; //xtal divider
 XMCRA = 0x00; //external memory
 port_init();
 timer1_init();

 MCUCR = 0x00;
 EICRA = 0x00; //extended ext ints
 EICRB = 0x00; //extended ext ints
 EIMSK = 0x00;
 TIMSK = 0x00; //timer interrupt sources
 ETIMSK = 0x00; //extended timer interrupt sources
 SEI(); //re-enable interrupts
 //all peripherals are now initialised
}

void main(void)

  unsigned int oldtogs; //storage for past walue of input
unsigned int PWM_select=3;
  port_init();
  timer1_init();
  init_devices();
 
  while(1)
  {
 //   if (PWM_select !=oldtogs)
// {
//    oldtogs=PWM_select;
   switch (PWM_select)
   {
     case 0:
    OCR1A=25;  //10%
break;
     case 1:
    OCR1A=51;  //20%
break;
 case 2:
    OCR1A=76;  //30%
break;
 case 3:
    OCR1A=102;  //40%
break;
}
// }
   }
}  
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值