我的应用程序的目标是使用ATMEGA328P作为数字直接合成400赫兹正弦发生器的核心。来自微处理器的脉冲被发送到作为全H桥连接的四个高压N-MOSFET的栅极。 16位定时器1使用WGM模式10,并命令Northeast和Northwest MOSFET。 8位定时器0和8位定时器2使用模式5,分别命令Southeast和Southwest MOSFET。我能够生成具有正确宽度的脉冲,但未能使它们正确同步。在Timer1脉冲与来自Timer0和Timer2的相应脉冲之间存在一两个时钟滑移。
尝试通过设置Timer0和Timer2初始计数来补偿此延迟时,我没有成功。
#define CPU_FREQ 16000000UL
#define OUT_FREQ 400UL
#define SAMPLE_FREQ 40000UL
#define SAMPLE_COUNT SAMPLE_FREQ/OUT_FREQ/2
#define SAMPLE_MAX CPU_FREQ/SAMPLE_FREQ/2 - 1
#define TIMER0_MAX 255
#define TIMER2_MAX 255
#define TIMER0_DELAY 1
#define TIMER2_DELAY 1
void setupTimers() {
cli(); // disable global interrupts;
GTCCR = bit(TSM) | bit(PSRASY) | bit( PSRSYNC);
setupTimer0();
setupTimer1();
setupTimer2();
sei(); // enable global interrupts;
GTCCR = 0;
}
void setupTimer0() {
// Waveform Generation Mode 5, PWM, Phase Correct
// TOP = OCR0A, OCR1B updated at TOP, TOV1 Flag set on BOTTOM
// Set OC0B on Compare Match when up-counting.
// Clear OC0B on Compare Match when down-counting
// Clock Source Mode 1, No prescaling
// OCIE0B, OCIE0A, TOIE0 interrupts disaabled
// No Force Output Compare A or B
// TCNT0 initial count compensation for OCR0A as TOP delay
TCCR0A = bit(COM0B1) | bit(COM0B0) | bit(WGM00);
TCCR0B = bit(CS00) | bit(WGM02) ;
TCNT0 = TIMER0_DELAY;
OCR0A = SAMPLE_MAX;
OCR0B = nextOCR0B;
TIMSK0 = 0;
}
void setupTimer1() {
// Waveform Generation Mode 10, PWM, Phase Correct
// TOP = ICR1, OCR1A and OCR1B updated at TOP, TOV1 Flag set on TOP
// Clear OC1A on Compare Match when upcounting.
// Set OC1A on Compare Match when downcounting
// Clear OC1B on Compare Match when upcounting.
// Set OC1B on Compare Match when downcounting
// Clock Source Mode 1, No prescaling
// OCIE1B, OCIE1A, TOIE1 interrupts disaabled
// No Force Output Compare A or B
TCCR1A = bit(COM1A1) | bit(COM1B1) | bit(WGM11) ;
TCCR1B = bit(CS10) | bit(WGM13);
TCCR1C = 0;
TCNT1 = 0;
OCR1A = nextOCR1A;
OCR1B = nextOCR1B;
ICR1 = SAMPLE_MAX;
TIMSK1 = 0;
}
void setupTimer2() {
// Waveform Generation Mode 5, PWM, Phase Correct
// TOP = OCR0A, OCR1B updated at TOP, TOV1 Flag set on BOTTOM
// Set OC0B on Compare Match when up-counting.
// Clear OC0B on Compare Match when down-counting
// Clock Source Mode 1, No prescaling
// OCIE0B, OCIE0A, TOIE0 interrupts disaabled
// No Force Output Compare A or B
// TCNT2 initial count compensation for OCR2A as TOP delay
TCCR2A = bit(COM2B1) | bit(COM2B0) | bit(WGM20);
TCCR2B = bit(CS20) | bit(WGM22) ;
TCNT2 = TIMER2_DELAY;
OCR2A = SAMPLE_MAX;
OCR2B = nextOCR2B;
TIMSK2 = 0;
}
预期结果:同步脉冲 实际结果:非同步脉冲
答案 0 :(得分:0)
通过反复试验,我设法找到了解决我的问题的TIMER0_DELAY,TIMER1_DELAY和TIMER2_DELAY的组合。