簡體   English   中英

帶ATMega164PA的PWM

[英]PWM with ATMega164PA

我試圖在ATMega164PA上使用帶有Timer0的PWM來增加LED的亮度。 在代碼下方運行我的代碼后,LED只會保持發光狀態,並且不會改變其亮度。

請查看我的代碼,並告訴我是否做錯了什么:

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

int dutycycle = 0;  // Variable for dutycycle 

/********************************************** MAIN ****************************************************/
int main(void)
{
    DDRB |= (1 << PB3); // Make pins output and OC0A pin for PWM 

    TCCR0A |= (1 << COM0A1) | (1<<WGM01) | (1<<WGM00);  // Clear OC0A on comare match and set OC0A at BOTTOM

    TIMSK0 |= (1<<TOIE0);   // Overflow Interrupt Enabled 

    TCNT0 = 0;  // Set Counter Value Register for comparison with OCR0A

    OCR0A = (dutycycle / 100) * 255;    // Set duty cycle ON period

    sei();      // Enable global interrupts 

    TCCR0B |= (1 << CS00);  // Prescale of 1 - start timer 

    while (1)
    {
        _delay_ms(500);

        dutycycle += 10;        // increase duty cycle by 10% every 500ms 

        if (dutycycle > 100)    // if duty cycle is greater than 100% set to 0
        {
            dutycycle = 0; 
        }
    }
}

ISR(TIMER0_OVF_vect)
{
    OCR0A = (dutycycle / 100) * 255;    // Set duty cycle ON period
}

我不確定您采用這種方法的邏輯,但是我可以看到一個明顯的問題正在給您帶來麻煩。

整數除法不會產生分數。 而是將結果四舍五入到最接近的整數。 這意味着dutycycle / 100確保dutycycle / 100幾乎始終為0,因為您確保dutycycle <= 100 因此, OCR0A幾乎始終為0。一個例外是dutycycle完全為100時,它將OCR0A設置為255。

解決此問題的一種方法是使用OCR0A = dutycycle * 255 / 100; 代替。 我不知道這是否可以解決所有問題,只是我看到的第一個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM