Try   HackMD

5.Таймера\Счётчика (TCCR0, TCNT0)

support: Устройство 8 битного таймера

Инфа за 2 часа до экзамена

Как определить время в секундах:
F - тактовая частота
1/f - время выполнения 1 такта
Частота не фиксирована, допустим F = 8Мгц
Тогда период время выполнения одного такта 12.25E-8 c
количество тактов = кол-во секунд/период. Например, 1 секунда это 8000000 тактов. Это больше чем 2 байта, поэтому можно часть закинуть на предделитель.
Получается деление в 256, а оставшееся кол-во тактов - 31250

Wave generation Mode:
Normal mode - The simplest mode of operation is the normal mode (WGM01:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter Overflow Flag (TOV0) will be set in the same timer clock cycle as the TCNT0 becomes zero. The TOV0 Flag in this case behaves like a 9 bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV0 Flag, the timer resolution can be increased by software.
Clear timer on compare match - In Clear Timer on Compare or CTC mode (WGM01:0 = 2), the OCR0 Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value
(TCNT0) matches the OCR0. The OCR0 defines the top value for the counter, hence also its resolution. This mode allows greater control of the compare match output frequency. It also simplifies the operation of counting external events.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Fast PWM - The fast Pulse Width Modulation or fast PWM mode (WGM01:0 = 3). The counter counts from BOTTOM to MAX then restarts from BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC0) is cleared on the compare match between TCNT0 and OCR0, and set at BOTTOM. In inverting Compare Output mode, the output is set on compare match and cleared at BOTTOM. Due to the single-slope operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct PWM mode that use dual-slope operation. This high frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC applications. High frequency allows physically small
sized external components (coils, capacitors), and therefore reduces total system cost.
In fast PWM mode, the counter is incremented until the counter value matches the MAX value. The counter is then cleared at the following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 32. The TCNT0 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. The diagram includes non-inverted and inverted
PWM outputs. The small horizontal line marks on the TCNT0 slopes represent compare matches between OCR0 and TCNT0.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Phase correct PWN -
The phase correct PWM mode (WGM01:0 = 1) provides a high resolution phase correct PWM waveform generation option. The phase correct PWM mode is based on a dual-slope operation.
The counter counts repeatedly from BOTTOM to MAX and then from MAX to BOTTOM. In noninverting Compare Output mode, the Output Compare (OC0) is cleared on the compare match between TCNT0 and OCR0 while upcounting, and set on the compare match while downcounting. In inverting Output Compare mode, the operation is inverted. The dual-slope operation has
lower maximum operation frequency than single slope operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes are preferred for motor control applications.
The PWM resolution for the phase correct PWM mode is fixed to eight bits. In phase correct PWM mode the counter is incremented until the counter value matches MAX. When the counter reaches MAX, it changes the count direction. The TCNT0 value will be equal to MAX for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 33. The TCNT0 value is in the timing diagram shown as a histogram for illustrating the dual-slope
operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent compare matches between OCR0 and TCNT0.
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Чутка теории

Помимо регистров ниже. есть так же и регистр сравнения OC0. Его значение постоянно сравнивается со счетным регистром TCNT0, и в случае совпадения таймер может выполнять какие-то действия - вызывать прерывание, менять состояние вывода OC0 и т.д. в зависимости от режима работы.
Значение OCR0 можно как читать, так и записывать.
У микроконтроллера Atmega16 три таймера-счетчика - два 8-ми разрядных таймера-счетчика Т0 и Т2, и один 16-ти разрядный - Т1

TCNT0 - Счетный регистр - от него забираем данные

TCNTn (n – число 0, 1 или 2) – счетный регистр. Когда таймер работает,по каждому импульсу тактового сигнала значение TCNT0 изменяется на единицу. В зависимости от режима работы таймера счетный регистр может или
увеличиваться, или уменьшаться. Регистр TCNT0 можно как читать, так и записывать.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

TCCR0 - конфигурационный регистр таймера/счетчика

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

TCCR0 – конфигурационный регистр таймера/счетчика Т0 определяет источник тактирования таймера, коэффициент предделителя, режим работы таймера/счетчика Т0 и поведение вывода OC0.

Кратко:
0-2 биты - задают коэффициент предделителя (определяют время таймера)
3,6 - определяют 1 из 4 режимов работы
4-5 - определяют поведение вывда
7 бит - принудительное изменение состояния выывода OC0

Биты CS02, CS01, CS00 (Clock Select) – определяют источник тактовой частоты для таймера Т0 и задают коэффициент предделителя.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Биты WGM10, WGM00 (Wave Generator Mode) определяют режим
работы таймера/счетчика Т0. Всего их может быть четыре – нормальный режим (normal), сброс таймера при совпадении (CTC) и два режима широтно-импульсной модуляции (FastPWM и Phase Correct PWM).

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Биты COM01, COM00 (Compare Match Output Mode) определяют
поведение вывода OC0. Если хоть один из этих битов установлен в 1, то вывод OC0 перестает функционировать как обычный вывод общего назначения и подключается к схеме сравнения таймера счетчика Т0.

Однако при этом он должен быть еще настроен как выход. Поведение вывода OC0 зависит от режима работы таймера/счетчика Т0. В режимах normal и СTC вывод OC0 ведет себя одинаково, а вот в режимах широтно-импульсной модуляции его поведение отличается.

Последний бит регистра TCCR0 – это бит FOC0 (Force Output
Compare). Этот бит предназначен для принудительного изменения состояния вывода OC0. Он работает только для режимов Normal и CTC. При установке бита FOC0 в единицу состояние вывода меняется соответственно значениям битов COM01, COM00. Бит FOC0 не вызывает прерывания и не сбрасывает таймер в CTC-режиме.

Пример кода для TCNT1

для 0, 2 таймеров можно просто из TCNTn брать, так как там 1 байт

CLI #Запрещаем прерывания, в обязательном порядке! OUT TCNT1H,R16 #Старшей байт записался вначале в TEMP OUT TCNT1L,R17 #А теперь записалось и в старший и младший! SEI #Разрешаем прерывания

Это с даташита. Оно довольно схоже с листингом выше

TIM16_ReadTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ; Restore global interrupt flag out SREG,r18 ret