ATmega8 (961722), страница 18

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

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

High fre-872486O–AVR–10/04quency allows physically small sized external components (coils, capacitors), hencereduces total system cost.The PWM resolution for fast PWM can be fixed to 8-, 9-, or 10-bit, or defined by eitherICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to0x0003), and the maximum resolution is 16-bit (ICR1 or OCR1A 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 (WGM13:0 = 5, 6, or 7), the value inICR1 (WGM13:0 = 14), or the value in OCR1A (WGM13:0 = 15).

The counter is thencleared at the following timer clock cycle. The timing diagram for the fast PWM mode isshown in Figure 38. The figure shows fast PWM mode when OCR1A or ICR1 is used todefine TOP. The TCNT1 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 TCNT1 slopes represent comparematches between OCR1x and TCNT1.

The OC1x Interrupt Flag will be set when a Compare Match occurs.Figure 38. 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 (TOV1) is set each time the counter reaches TOP. Inaddition the OCF1A or ICF1 Flag is set at the same timer clock cycle as TOV1 is setwhen either OCR1A or ICR1 is used for defining the TOP value.

If one of the interruptsare enabled, the interrupt handler routine can be used for updating the TOP and compare values.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 theTCNT1 and the OCR1x. Note that when using fixed TOP values the unused bits aremasked to zero when any of the OCR1x Registers are written.The procedure for updating ICR1 differs from updating OCR1A when used for definingthe TOP value.

The ICR1 Register is not double buffered. This means that if ICR1 ischanged to a low value when the counter is running with none or a low prescaler value,there is a risk that the new ICR1 value written is lower than the current value of TCNT1.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 start88ATmega8(L)2486O–AVR–10/04ATmega8(L)ing at 0x0000 before the Compare Match can occur. The OCR1A Register, however, isdouble buffered. This feature allows the OCR1A I/O location to be written anytime.When the OCR1A I/O location is written the value written will be put into the OCR1ABuffer Register. The OCR1A Compare Register will then be updated with the value inthe Buffer Register at the next timer clock cycle the TCNT1 matches TOP.

The update isdone at the same timer clock cycle as the TCNT1 is cleared and the TOV1 Flag is set.Using the ICR1 Register for defining TOP works well when using fixed TOP values. Byusing ICR1, the OCR1A Register is free to be used for generating a PWM output onOC1A. However, if the base PWM frequency is actively changed (by changing the TOPvalue), using the OCR1A 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 theOC1x pins. Setting the COM1x1:0 bits to 2 will produce a non-inverted PWM and aninverted PWM output can be generated by setting the COM1x1:0 to 3.

See Table 37 onpage 96. The actual OC1x value will only be visible on the port pin if the data directionfor the port pin is set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x Register at the Compare Match between OCR1x andTCNT1, and clearing (or setting) the OC1x 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 OCR1x Register represents special cases when generatinga PWM waveform output in the fast PWM mode. If the OCR1x is set equal to BOTTOM(0x0000) the output will be a narrow spike for each TOP+1 timer clock cycle.

Setting theOCR1x equal to TOP will result in a constant high or low output (depending on the polarity of the output set by the COM1x1:0 bits.)A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achievedby setting OC1A to toggle its logical level on each Compare Match (COM1A1:0 = 1).This applies only if OCR1A is used to define the TOP value (WGM13:0 = 15). The waveform generated will have a maximum frequency of fOC1A = fclk_I/O/2 when OCR1A is set tozero (0x0000).

This feature is similar to the OC1A 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 (WGM13: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 (OC1x) is cleared on the Compare Match between TCNT1and OCR1x while upcounting, 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 ICR1 or OCR1A.

The minimum resolution allowed is 2-bit (ICR1 or892486O–AVR–10/04OCR1A set to 0x0003), and the maximum resolution is 16-bit (ICR1 or OCR1A 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 (WGM13:0 = 1, 2, or 3), thevalue in ICR1 (WGM13:0 = 10), or the value in OCR1A (WGM13:0 = 11).

The counterhas then reached the TOP and changes the count direction. The TCNT1 value will beequal to TOP for one timer clock cycle. The timing diagram for the phase correct PWMmode is shown on Figure 39. The figure shows phase correct PWM mode when OCR1Aor ICR1 is used to define TOP. The TCNT1 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 TCNT1 slopes represent compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will beset when a Compare Match occurs.Figure 39.

Phase Correct PWM Mode, Timing DiagramOCRnx / TOP Update andOCnA Interrupt Flag Setor ICFn Interrupt Flag Set(Interrupt on TOP)TOVn Interrupt Flag Set(Interrupt on Bottom)TCNTnOCnx(COMnx1:0 = 2)OCnx(COMnx1:0 = 3)Period1234The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches BOTTOM. When either OCR1A or ICR1 is used for defining the TOP value, the OC1A orICF1 Flag is set accordingly at the same timer clock cycle as the OCR1x Registers areupdated with the double buffer value (at TOP).

The Interrupt Flags can be used to generate an interrupt each time the counter reaches the TOP or BOTTOM value.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 theTCNT1 and the OCR1x.

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

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

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

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