單片機(jī)定時/計數(shù)器設(shè)計輸出PWM
8000000Hz / 510 =
15686Hz。每16次輸出構(gòu)成一個周期正弦波,正弦波的頻率為980.4Hz。PWM由OC0(PB4)引腳輸出。參考程序如下(ICCAVR)。
//ICC-AVR application builder : 2004-08
// Target : M128
// Crystal: 8.0000Mhz
#include
#include
#pragma data:code
// 128點(diǎn)正弦波樣本表
const unsigned char auc_SinParam[128] = {
64,67,70,73,76,79,82,85,88,91,94,96,99,102,104,106,109,111,113,115,117,118,120,121,
123,124,125,126,126,127,127,127,127,127,127,127,126,126,125,124,123,121,120,118,
117,115,113,111,109,106,104,102,99,96,94,91,88,85,82,79,76,73,70,67,64,60,57,54,51,48,
45,42,39,36,33,31,28,25,23,21,18,16,14,12,10,9,7,6,4,3,2,1,1,0,0,0,0,0,0,0,1,1,2,3,4,6,
7,9,10,12,14,16,18,21,23,25,28,31,33,36,39,42,45,48,51,54,57,60};
#pragma data:data
unsigned char x_SW = 8,X_LUT = 0;
#pragma interrupt_handler timer0_ovf_isr:17
void timer0_ovf_isr(void)
{
X_LUT += x_SW; // 新樣點(diǎn)指針
if (X_LUT > 127) X_LUT -= 128; // 樣點(diǎn)指針調(diào)整
OCR0 = auc_SinParam[X_LUT]; // 取樣點(diǎn)指針到比較匹配寄存器
}
void main(void)
{
DDRB |= 0x10; // PB4(OC0)輸出
TCCR0 = 0x71; // 相位調(diào)整PWM模式,分頻系數(shù)=1,正向控制OC0
TIMSK = 0x01; // T/C0溢出中斷允許
SEI(); // 使能全局中斷
while(1)
{……};
}
每次計數(shù)器溢出中斷的服務(wù)中取出一個正弦波的樣點(diǎn)值到比較匹配寄存器中,用于調(diào)整下一個PWM的脈沖寬度,這樣在PB4引腳上輸出了按正弦波調(diào)制的PWM方波。當(dāng)PB4的輸出通過一個低通濾波器后,便得到一個980.4Hz的正弦波了。如要得到更精確的1KHz的正弦波,可使用定時/計數(shù)器T/C1,選擇工作模式10,設(shè)置ICR1=250為計數(shù)器的上限值。
pwm相關(guān)文章:pwm原理
塵埃粒子計數(shù)器相關(guān)文章:塵埃粒子計數(shù)器原理
評論