gpt4 book ai didi

c - 定时器计数器为0并制作真正的第二个问题

转载 作者:行者123 更新时间:2023-11-30 16:13:44 25 4
gpt4 key购买 nike

我想在 portuse 中模拟一段代码。我有一个 LED 连接到频率为 2MHZ 的微型引脚。我想在timer0 中使用presclare 64 进行编码。我算了一下,定时器需要计数31128。但timer0只能计算到255。所以我决定使用溢出中断并定义一个变量来计算溢出。如果超跌达到122.07一秒关。我用的是122溢出中断。但对于剩下的 0.07,我需要在 tcnt 中数到 18。所以我决定首先使用 OCR。

我的问题是:这个方法是真是假?Abd 我应该如何编写这段代码?

最佳答案

问题是:您是否希望您的计数器长期计算时间间隔?或者您希望每秒发生一些事件?容忍度如何?

例如,如果您想计数(假设为 10 分钟),在显示屏上显示秒计数器,则可接受 10-20 毫秒的抖动,即显示屏上的第二个计数器将提前或晚更新 10 毫秒, 没关系。在这种情况下,您可以使用 Bresenham 算法来纠正错误。您可以将某个变量增加定时器溢出间隔 (256) 的量。当变量超过一秒值(即 2000000/64 = 31250)时,您可以将其减少该值并处理每秒事件。从长远来看,第二个计数器将精确计算秒数。显然,您可以将两个数字除以相同的数量。 IE。分别使用 128 和 15625。

uint16_t second_counter = 0;
uint16_t counter_error = 0;

ISR(TIMER0_OVF_vect) {
counter_error += 128; // Increase the error counter;
if (counter_error >= 15625) { // On overflow
counter_error -= 15625; // Decrease the error counter;

second_counter++; // Increase the second counter, or do any other once-per-second action
}
}

在 122 或 123 计时器溢出后,条件内的每秒事件将不完全在秒边界上触发。但平均而言,每秒恰好一次。当计时器同时用于其他用途并且无法更改其分辨率时,此方法非常有用。

但是,如果您希望每秒恰好发生第二个事件,则在 CTC 模式下使用计数器,以每秒整数溢出的方式限制其最高值。

假设您可以选择 64 个预分频器,并将 TOP 值设置为 249(从而使定时器周期等于 250),这样每秒正好有 125 次溢出。

uint8_t overflow_counter = 0;
uint16_t second_counter = 0;
ISR(TIMER0_OVF_vect) {
overflow_counter++;
if (overflow_counter >= 125) { // waiting for 125th overflow;
overflow_counter = 0; // reset the counter;

second_counter++; // Increase the second counter, or do any other once-per-second action
}
}

OCR0A = 249; // from 0 to 249 = 250 counts.
TIMSK0 = (1 << TOIE0); // Allow overflow interrupt
TCCR0A = (1 << WGM01); // Enable CTC mode. OCRA defines the top value
TCCR0B = (1 << CS01) | (1 << CS00); // Start with 1:64 prescaler
sei(); // Enable interrupts

关于c - 定时器计数器为0并制作真正的第二个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57933535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com