ATmega128 (961723), страница 31

Файл №961723 ATmega128 (Скамко) 31 страницаATmega128 (961723) страница 312013-09-29СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 31)

There are close connectionsbetween how the counter behaves (counts) and how waveforms are generated on theoutput compare output OC2. For more details about advanced counting sequences andwaveform generation, see “Modes of Operation” on page 149.The Timer/Counter overflow (TOV2) flag is set according to the mode of operationselected by the WGM21:0 bits. TOV2 can be used for generating a CPU interrupt.Output Compare Unit146The 8-bit comparator continuously compares TCNT2 with the Output Compare Register(OCR2). Whenever TCNT2 equals OCR2, the comparator signals a match. A match willset the output compare flag (OCF2) at the next timer clock cycle.

If enabled (OCIE2 = 1and global interrupt flag in SREG is set), the output compare flag generates an outputcompare interrupt. The OCF2 flag is automatically cleared when the interrupt is executed. Alternatively, the OCF2 flag can be cleared by software by writing a logical one toits I/O bit location. The waveform generator uses the match signal to generate an outputaccording to operating mode set by the WGM21:0 bits and compare output mode(COM21:0) bits.

The max and bottom signals are used by the waveform generator forhandling the special cases of the extreme values in some modes of operation (see“Modes of Operation” on page 149). Figure 63 shows a block diagram of the outputcompare unit.ATmega1282467M–AVR–11/04ATmega128Figure 63. Output Compare Unit, Block DiagramDATA BUSOCRnTCNTn= (8-bit Comparator )OCFn (Int.Req.)topbottomWaveform GeneratorOCnFOCnWGMn1:0COMn1:0The OCR2 Register is double buffered when using any of the pulse width modulation(PWM) modes. For the normal and Clear Timer on Compare (CTC) modes of operation,the double buffering is disabled. The double buffering synchronizes the update of theOCR2 Compare Register to either top or bottom of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, therebymaking the output glitch-free.The OCR2 Register access may seem complex, but this is not case.

When the doublebuffering is enabled, the CPU has access to the OCR2 buffer Register, and if doublebuffering is disabled the CPU will access the OCR2 directly.Force Output CompareIn non-PWM Waveform Generation modes, the match output of the comparator can beforced by writing a one to the force output compare (FOC2) bit. Forcing compare matchwill not set the OCF2 flag or reload/clear the timer, but the OC2 pin will be updated as ifa real compare match had occurred (the COM21:0 bits settings define whether the OC2pin is set, cleared or toggled).Compare Match Blocking byTCNT2 WriteAll CPU write operations to the TCNT2 Register will block any compare match thatoccur in the next timer clock cycle, even when the timer is stopped. This feature allowsOCR2 to be initialized to the same value as TCNT2 without triggering an interrupt whenthe Timer/Counter clock is enabled.Using the Output CompareUnitSince writing TCNT2 in any mode of operation will block all compare matches for onetimer clock cycle, there are risks involved when changing TCNT2 when using the outputcompare channel, independently of whether the Timer/Counter is running or not.

If thevalue written to TCNT2 equals the OCR2 value, the compare match will be missed,resulting in incorrect waveform generation. Similarly, do not write the TCNT2 valueequal to BOTTOM when the counter is downcounting.The setup of the OC2 should be performed before setting the Data Direction Register forthe port pin to output. The easiest way of setting the OC2 value is to use the Force Out-1472467M–AVR–11/04put Compare (FOC2) strobe bits in normal mode. The OC2 Register keeps its valueeven when changing between waveform generation modes.Be aware that the COM21:0 bits are not double buffered together with the comparevalue. Changing the COM21:0 bits will take effect immediately.Compare Match OutputUnitThe Compare Output mode (COM21:0) bits have two functions.

The waveform generator uses the COM21:0 bits for defining the output compare (OC2) state at the nextcompare match. Also, the COM21:0 bits control the OC2 pin output source. Figure 64shows a simplified schematic of the logic affected by the COM21:0 bit setting. The I/Oregisters, I/O bits, and I/O pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers (DDR and PORT) that are affected by the COM21:0 bitsare shown. When referring to the OC2 state, the reference is for the internal OC2 Register, not the OC2 pin. If a System Reset occur, the OC2 Register is reset to “0”.Figure 64.

Compare Match Output Unit, SchematicCOMn1COMn0FOCnWaveformGeneratorDQ1OCnDATA BUSD0OCnPinQPORTDQDDRclk I/OThe general I/O port function is overridden by the output compare (OC2) from the waveform generator if either of the COM21:0 bits are set. However, the OC2 pin direction(input or output) is still controlled by the Data Direction Register (DDR) for the port pin.The Data Direction Register bit for the OC2 pin (DDR_OC2) must be set as outputbefore the OC2 value is visible on the pin.

The port override function is independent ofthe Waveform Generation mode.The design of the output compare pin logic allows initialization of the OC2 state beforethe output is enabled. Note that some COM21:0 bit settings are reserved for certainmodes of operation. See “8-bit Timer/Counter Register Description” on page 156.Compare Output Mode andWaveform Generation148The waveform generator uses the COM21:0 bits differently in normal, CTC, and PWMmodes. For all modes, setting the COM21:0 = 0 tells the waveform generator that noaction on the OC2 Register is to be performed on the next compare match. For compareoutput actions in the non-PWM modes refer to Table 65 on page 157.

For fast PWMmode, refer to Table 66 on page 157, and for phase correct PWM refer to Table 67 onpage 157.ATmega1282467M–AVR–11/04ATmega128A change of the COM21:0 bits state will have effect at the first compare match after thebits are written. For non-PWM modes, the action can be forced to have immediate effectby using the FOC2 strobe bits.Modes of OperationThe mode of operation, i.e., the behavior of the Timer/Counter and the Output Comparepins, is defined by the combination of the Waveform Generation mode (WGM21:0) andCompare Output mode (COM21:0) bits.

The Compare Output mode bits do not affectthe counting sequence, while the Waveform Generation mode bits do. The COM21:0bits control whether the PWM output generated should be inverted or not (inverted ornon-inverted PWM). For non-PWM modes the COM21:0 bits control whether the outputshould be set, cleared, or toggled at a compare match (see “Compare Match OutputUnit” on page 148).For detailed timing information refer to Figure 68, Figure 69, Figure 70, and Figure 71 in“Timer/Counter Timing Diagrams” on page 154.Normal ModeThe simplest mode of operation is the normal mode (WGM21:0 = 0).

In this mode thecounting direction is always up (incrementing), and no counter clear is performed. Thecounter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and thenrestarts from the bottom (0x00). In normal operation the Timer/Counter overflow flag(TOV2) will be set in the same timer clock cycle as the TCNT2 becomes zero. The TOV2flag in this case behaves like a ninth bit, except that it is only set, not cleared. However,combined with the timer overflow interrupt that automatically clears the TOV2 flag, thetimer resolution can be increased by software. There are no special cases to consider inthe normal mode, a new counter value can be written anytime.The output compare unit can be used to generate interrupts at some given time. Usingthe output compare to generate waveforms in normal mode is not recommended, sincethis will occupy too much of the CPU time.Clear Timer on CompareMatch (CTC) ModeIn Clear Timer on Compare or CTC mode (WGM21:0 = 2), the OCR2 Register is used tomanipulate the counter resolution.

In CTC mode the counter is cleared to zero when thecounter value (TCNT2) matches the OCR2. The OCR2 defines the top value for thecounter, hence also its resolution. This mode allows greater control of the comparematch output frequency. It also simplifies the operation of counting external events.The timing diagram for the CTC mode is shown in Figure 65. The counter value(TCNT2) increases until a compare match occurs between TCNT2 and OCR2 and thencounter (TCNT2) is cleared.Figure 65. CTC Mode, Timing DiagramOCn Interrupt Flag SetTCNTnOCn(Toggle)Period(COMn1:0 = 1)12341492467M–AVR–11/04An interrupt can be generated each time the counter value reaches the TOP value byusing the OCF2 flag.

If the interrupt is enabled, the interrupt handler routine can be usedfor updating the TOP value. However, changing the TOP to a value close to BOTTOMwhen the counter is running with none or a low prescaler value must be done with caresince the CTC mode does not have the double buffering feature. If the new value writtento OCR2 is lower than the current value of TCNT2, the counter will miss the comparematch. The counter will then have to count to its maximum value (0xFF) and wraparound starting at 0x00 before the compare match can occur.For generating a waveform output in CTC mode, the OC2 output can be set to toggle itslogical level on each compare match by setting the compare output mode bits to togglemode (COM21:0 = 1).

The OC2 value will not be visible on the port pin unless the datadirection for the pin is set to output. The waveform generated will have a maximum frequency of fOC2 = fclk_I/O/2 when OCR2 is set to zero (0x00). The waveform frequency isdefined by the following equation:f clk_I/Of OCn = ---------------------------------------------2 ⋅ N ⋅ ( 1 + OCRn )The N variable represents the prescale factor (1, 8, 64, 256, or 1024).As for the normal mode of operation, the TOV2 flag is set in the same timer clock cyclethat the counter counts from MAX to 0x00.Fast PWM ModeThe fast Pulse Width Modulation or fast PWM mode (WGM21:0 = 3) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWMoption by its single-slope operation. The counter counts from BOTTOM to MAX thenrestarts from BOTTOM.

Характеристики

Тип файла
PDF-файл
Размер
3 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов учебной работы

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6367
Авторов
на СтудИзбе
310
Средний доход
с одного платного файла
Обучение Подробнее