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

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

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

(8-bit)OCRnx Buffer (16-bit Register)OCRnxH (8-bit)TCNTnH (8-bit)TCNTnL (8-bit)TCNTn (16-bit Counter)OCRnxL (8-bit)OCRnx (16-bit Register)= (16-bit Comparator )OCFnx (Int.Req.)TOPBOTTOMWaveform GeneratorWGMn3:0118OCnxCOMnx1:0ATmega1282467M–AVR–11/04ATmega128The OCRnx Register is double buffered when using any of the twelve Pulse Width Modulation (PWM) modes. For the normal and Clear Timer on Compare (CTC) modes ofoperation, the double buffering is disabled. The double buffering synchronizes theupdate of the OCRnx Compare Register to either TOP or BOTTOM of the countingsequence. The synchronization prevents the occurrence of odd-length, non-symmetricalPWM pulses, thereby making the output glitch-free.The OCRnx Register access may seem complex, but this is not case. When the doublebuffering is enabled, the CPU has access to the OCRnx buffer register, and if doublebuffering is disabled the CPU will access the OCRnx directly.

The content of the OCR1x(buffer or compare) register is only changed by a write operation (the Timer/Counterdoes not update this register automatically as the TCNTn- and ICRn Register). Therefore OCRnx is not read via the high byte Temporary Register (TEMP).

However, it is agood practice to read the low byte first as when accessing other 16-bit registers. Writingthe OCRnx registers must be done via the TEMP Register since the compare of all 16bits is done continuously. The high byte (OCRnxH) has to be written first. When the highbyte I/O location is written by the CPU, the TEMP Register will be updated by the valuewritten. Then when the low byte (OCRnxL) is written to the lower 8 bits, the high byte willbe copied into the upper 8 bits of either the OCRnx buffer or OCRnx Compare Registerin the same system clock cycle.For more information of how to access the 16-bit registers refer to “Accessing 16-bitRegisters” on page 112.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 (FOCnx) bit.

Forcing comparematch will not set the OCFnx flag or reload/clear the timer, but the OCnx pin will beupdated as if a real compare match had occurred (the COMnx1:0 bits settings definewhether the OCnx pin is set, cleared or toggled).Compare Match Blocking byTCNTn WriteAll CPU writes to the TCNTn Register will block any compare match that occurs in thenext timer clock cycle, even when the timer is stopped. This feature allows OCRnx to beinitialized to the same value as TCNTn without triggering an interrupt when theTimer/Counter clock is enabled.Using the Output CompareUnitSince writing TCNTn in any mode of operation will block all compare matches for onetimer clock cycle, there are risks involved when changing TCNTn when using any of theoutput compare channels, independent of whether the Timer/Counter is running or not.If the value written to TCNTn equals the OCRnx value, the compare match will bemissed, resulting in incorrect waveform generation.

Do not write the TCNTn equal toTOP in PWM modes with variable TOP values. The compare match for the TOP will beignored and the counter will continue to 0xFFFF. Similarly, do not write the TCNTn valueequal to BOTTOM when the counter is downcounting.The setup of the OCnx should be performed before setting the Data Direction Registerfor the port pin to output.

The easiest way of setting the OCnx value is to use the forceoutput compare (FOCnx) strobe bits in normal mode. The OCnx Register keeps itsvalue even when changing between waveform generation modes.Be aware that the COMnx1:0 bits are not double buffered together with the comparevalue. Changing the COMnx1:0 bits will take effect immediately.1192467M–AVR–11/04Compare Match OutputUnitThe Compare Output mode (COMnx1:0) bits have two functions. The waveform generator uses the COMnx1:0 bits for defining the output compare (OCnx) state at the nextcompare match. Secondly the COMnx1:0 bits control the OCnx pin output source. Figure 50 shows a simplified schematic of the logic affected by the COMnx1:0 bit setting.The I/O registers, I/O bits, and I/O pins in the figure are shown in bold.

Only the parts ofthe general I/O port control registers (DDR and PORT) that are affected by theCOMnx1:0 bits are shown. When referring to the OCnx state, the reference is for theinternal OCnx Register, not the OCnx pin. If a system Reset occur, the OCnx Register isreset to “0”.Figure 50. Compare Match Output Unit, SchematicCOMnx1COMnx0FOCnxWaveformGeneratorDQ1OCnxDATA BUSD0OCnxPinQPORTDQDDRclk I/OThe general I/O port function is overridden by the output compare (OCnx) from theWaveform Generator if either of the COMnx1:0 bits are set. However, the OCnx pindirection (input or output) is still controlled by the Data Direction Register (DDR) for theport pin. The data direction register bit for the OCnx pin (DDR_OCnx) must be set asoutput before the OCnx value is visible on the pin.

The port override function is generallyindependent of the waveform generation mode, but there are some exceptions. Refer toTable 58, Table 59 and Table 60 for details.The design of the output compare pin logic allows initialization of the OCnx state beforethe output is enabled. Note that some COMnx1:0 bit settings are reserved for certainmodes of operation. See “16-bit Timer/Counter Register Description” on page 131.The COMnx1:0 bits have no effect on the Input Capture unit.Compare Output Mode andWaveform Generation120The waveform generator uses the COMnx1:0 bits differently in normal, CTC, and PWMmodes. For all modes, setting the COMnx1:0 = 0 tells the waveform generator that noaction on the OCnx Register is to be performed on the next compare match.

For compare output actions in the non-PWM modes refer to Table 58 on page 131. For fastPWM mode refer to Table 59 on page 132, and for phase correct and phase and frequency correct PWM refer to Table 60 on page 132.ATmega1282467M–AVR–11/04ATmega128A change of the COMnx1: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 FOCnx 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 (WGMn3:0) andCompare Output mode (COMnx1:0) bits.

The Compare Output mode bits do not affectthe counting sequence, while the waveform generation mode bits do. The COMnx1:0bits control whether the PWM output generated should be inverted or not (inverted ornon-inverted PWM). For non-PWM modes the COMnx1:0 bits control whether theoutput should be set, cleared or toggle at a compare match (See “Compare MatchOutput Unit” on page 120.)For detailed timing information refer to “Timer/Counter Timing Diagrams” on page 128.Normal ModeThe simplest mode of operation is the normal mode (WGMn3: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 16-bit value (MAX = 0xFFFF) andthen restarts from the BOTTOM (0x0000). In normal operation the Timer/Counter Overflow Flag (TOVn) will be set in the same timer clock cycle as the TCNTn becomes zero.The TOVn flag in this case behaves like a 17th bit, except that it is only set, not cleared.However, combined with the timer overflow interrupt that automatically clears the TOVnflag, the timer resolution can be increased by software.

There are no special cases toconsider in the normal mode, a new counter value can be written anytime.The Input Capture unit is easy to use in normal mode. However, observe that the maximum interval between the external events must not exceed the resolution of the counter.If the interval between events are too long, the timer overflow interrupt or the prescalermust be used to extend the resolution for the capture unit.The output compare units 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 (WGMn3:0 = 4 or 12), the OCRnA or ICRnRegister are used to manipulate the counter resolution. In CTC mode the counter iscleared to zero when the counter value (TCNTn) matches either the OCRnA (WGMn3:0= 4) or the ICRn (WGMn3:0 = 12). The OCRnA or ICRn define 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 51. The counter value(TCNTn) increases until a compare match occurs with either OCRnA or ICRn, and thencounter (TCNTn) is cleared.1212467M–AVR–11/04Figure 51. CTC Mode, Timing DiagramOCnA Interrupt Flag Setor ICFn Interrupt Flag Set(Interrupt on TOP)TCNTnOCnA(Toggle)Period(COMnA1:0 = 1)1234An interrupt can be generated at each time the counter value reaches the TOP value byeither using the OCFnA or ICFn flag according to the register used to define the TOPvalue. If the interrupt is enabled, the interrupt handler routine can be used for updatingthe TOP value.

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

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

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

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