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

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

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

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. If the TOP value is lowerthan any of the compare registers, a compare match will never occur between theTCNTn and the OCRnx. Note that when using fixed TOP values the unused bits aremasked to zero when any of the OCRnx Registers are written.The procedure for updating ICRn differs from updating OCRnA when used for definingthe TOP value. The ICRn Register is not double buffered. This means that if ICRn ischanged to a low value when the counter is running with none or a low prescaler value,there is a risk that the new ICRn value written is lower than the current value of TCNTn.The result will then be that the counter will miss the compare match at the TOP value.The counter will then have to count to the MAX value (0xFFFF) and wrap around start-1232467M–AVR–11/04ing at 0x0000 before the compare match can occur.

The OCRnA Register however, isdouble buffered. This feature allows the OCRnA I/O location to be written anytime.When the OCRnA I/O location is written the value written will be put into the OCRnAbuffer Register. The OCRnA Compare Register will then be updated with the value inthe buffer register at the next timer clock cycle the TCNTn matches TOP.

The update isdone at the same timer clock cycle as the TCNTn is cleared and the TOVn flag is set.Using the ICRn Register for defining TOP works well when using fixed TOP values. Byusing ICRn, the OCRnA Register is free to be used for generating a PWM output onOCnA. However, if the base PWM frequency is actively changed (by changing the TOPvalue), using the OCRnA as TOP is clearly a better choice due to its double bufferfeature.In fast PWM mode, the compare units allow generation of PWM waveforms on theOCnx pins.

Setting the COMnx1:0 bits to 2 will produce a non-inverted PWM and aninverted PWM output can be generated by setting the COMnx1:0 to 3 (See Table 59 onpage 132). The actual OCnx value will only be visible on the port pin if the data directionfor the port pin is set as output (DDR_OCnx).

The PWM waveform is generated bysetting (or clearing) the OCnx Register at the compare match between OCRnx andTCNTn, and clearing (or setting) the OCnx Register at the timer clock cycle the counteris cleared (changes from TOP to BOTTOM).The PWM frequency for the output can be calculated by the following equation:f clk_I/Of OCnxPWM = ---------------------------------N ⋅ ( 1 + TOP )The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).The extreme values for the OCRnx Register represents special cases when generatinga PWM waveform output in the fast PWM mode. If the OCRnx is set equal to BOTTOM(0x0000) the output will be a narrow spike for each TOP+1 timer clock cycle.

Setting theOCRnx equal to TOP will result in a constant high or low output (depending on the polarity of the output set by the COMnx1:0 bits.)A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achievedby setting OCnA to toggle its logical level on each compare match (COMnA1:0 = 1).This applies only if OCRnA is used to define the TOP value (WGMn3:0 = 15). The waveform generated will have a maximum frequency of fOCnA = fclk_I/O/2 when OCRnA is set tozero (0x0000).

This feature is similar to the OCnA toggle in CTC mode, except the double buffer feature of the output compare unit is enabled in the fast PWM mode.Phase Correct PWM ModeThe phase correct Pulse Width Modulation or phase correct PWM mode (WGMn3:0 = 1,2, 3, 10, or 11) provides a high resolution phase correct PWM waveform generationoption. The phase correct PWM mode is, like the phase and frequency correct PWMmode, based on a dual-slope operation.

The counter counts repeatedly from BOTTOM(0x0000) to TOP and then from TOP to BOTTOM. In non-inverting compare outputmode, the output compare (OCnx) is cleared on the compare match between TCNTnand OCRnx while counting up, and set on the compare match while downcounting. Ininverting Output Compare mode, the operation is inverted. The dual-slope operation haslower maximum operation frequency than single slope operation. However, due to thesymmetric feature of the dual-slope PWM modes, these modes are preferred for motorcontrol applications.The PWM resolution for the phase correct PWM mode can be fixed to 8-, 9-, or 10-bit, ordefined by either ICRn or OCRnA.

The minimum resolution allowed is 2 bit (ICRn or124ATmega1282467M–AVR–11/04ATmega128OCRnA set to 0x0003), and the maximum resolution is 16 bit (ICRn or OCRnA set toMAX). The PWM resolution in bits can be calculated by using the following equation:log ( TOP + 1 )R PCPWM = ----------------------------------log ( 2 )In phase correct PWM mode the counter is incremented until the counter value matcheseither one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGMn3:0 = 1, 2, or 3), thevalue in ICRn (WGMn3:0 = 10), or the value in OCRnA (WGMn3:0 = 11). The counterhas then reached the TOP and changes the count direction.

The TCNTn value will beequal to TOP for one timer clock cycle. The timing diagram for the phase correct PWMmode is shown on Figure 53. The figure shows phase correct PWM mode when OCRnAor ICRn is used to define TOP. The TCNTn value is in the timing diagram shown as ahistogram for illustrating the dual-slope operation. The diagram includes non-invertedand inverted PWM outputs. The small horizontal line marks on the TCNTn slopes represent compare matches between OCRnx and TCNTn.

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

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

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

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