利用定时器产生不同占空比的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; } // } } } |
单片机定时器产生pwm
最新推荐文章于 2025-01-25 09:45:00 发布