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

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

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

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.

However, changing the TOP to a value close to BOTTOM when thecounter is running with none or a low prescaler value must be done with care since theCTC mode does not have the double buffering feature. If the new value written toOCRnA or ICRn is lower than the current value of TCNTn, the counter will miss the compare match.

The counter will then have to count to its maximum value (0xFFFF) andwrap around starting at 0x0000 before the compare match can occur. In many casesthis feature is not desirable. An alternative will then be to use the fast PWM mode usingOCRnA for defining TOP (WGMn3:0 = 15) since the OCRnA then will be doublebuffered.For generating a waveform output in CTC mode, the OCnA output can be set to toggleits logical level on each compare match by setting the compare output mode bits to toggle mode (COMnA1:0 = 1). The OCnA value will not be visible on the port pin unless thedata direction for the pin is set to output (DDR_OCnA = 1). The waveform generated willhave a maximum frequency of fOCnA = fclk_I/O/2 when OCRnA is set to zero (0x0000).

Thewaveform frequency is defined by the following equation:f clk_I/Of OCnA = -------------------------------------------------2 ⋅ N ⋅ ( 1 + OCRnA )The N variable represents the prescaler factor (1, 8, 64, 256, or 1024).As for the normal mode of operation, the TOVn flag is set in the same timer clock cyclethat the counter counts from MAX to 0x0000.Fast PWM Mode122The fast Pulse Width Modulation or fast PWM mode (WGMn3:0 = 5,6,7,14, or 15) provides a high frequency PWM waveform generation option.

The fast PWM differs fromthe other PWM options by its single-slope operation. The counter counts from BOTTOMto TOP then restarts from BOTTOM. In non-inverting Compare Output mode, the outputcompare (OCnx) is set on the compare match between TCNTn and OCRnx, and clearedat TOP. In inverting compare output mode output is cleared on compare match and setat TOP.

Due to the single-slope operation, the operating frequency of the fast PWMmode can be twice as high as the phase correct and phase and frequency correct PWMmodes that use dual-slope operation. This high frequency makes the fast PWM modewell suited for power regulation, rectification, and DAC applications. High frequencyallows physically small sized external components (coils, capacitors), hence reducestotal system cost.ATmega1282467M–AVR–11/04ATmega128The PWM resolution for fast PWM can be fixed to 8-, 9-, or 10-bit, or defined by eitherICRn or OCRnA.

The minimum resolution allowed is 2-bit (ICRn or OCRnA set to0x0003), and the maximum resolution is 16-bit (ICRn or OCRnA set to MAX). The PWMresolution in bits can be calculated by using the following equation:log ( TOP + 1 )R FPWM = ----------------------------------log ( 2 )In fast PWM mode the counter is incremented until the counter value matches eitherone of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGMn3:0 = 5, 6, or 7), the value inICRn (WGMn3:0 = 14), or the value in OCRnA (WGMn3:0 = 15). The counter is thencleared at the following timer clock cycle. The timing diagram for the fast PWM mode isshown in Figure 52.

The figure shows fast PWM mode when OCRnA or ICRn is used todefine TOP. The TCNTn value is in the timing diagram shown as a histogram for illustrating the single-slope operation. The diagram includes non-inverted and inverted PWMoutputs. The small horizontal line marks on the TCNTn slopes represent comparematches between OCRnx and TCNTn. The OCnx interrupt flag will be set when a compare match occurs.Figure 52.

Fast PWM Mode, Timing DiagramOCRnx / TOP Updateand TOVn Interrupt FlagSet and OCnA InterruptFlag Set or ICFnInterrupt Flag Set(Interrupt on TOP)TCNTnOCnx(COMnx1:0 = 2)OCnx(COMnx1:0 = 3)Period12345678The Timer/Counter Overflow Flag (TOVn) is set each time the counter reaches TOP. Inaddition the OCnA or ICFn flag is set at the same timer clock cycle as TOVn is set wheneither OCRnA or ICRn is used for defining the TOP value. If one of the interrupts areenabled, the interrupt handler routine can be used for updating the TOP and comparevalues.When changing the TOP value the program must ensure that the new TOP value ishigher or equal to the value of all of the compare registers.

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

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

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

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