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

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

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

The result of the compare can be used by the waveform generator to generate a PWM or variable frequency output on the Output ComparePin (OC0). See “Output Compare Unit” on page 92. for details. The compare matchevent will also set the compare flag (OCF0) which can be used to generate an outputcompare interrupt request.DefinitionsMany register and bit references in this document are written in general form. A lowercase “n” replaces the Timer/Counter number, in this case 0. However, when using theregister or bit defines in a program, the precise form must be used (i.e., TCNT0 foraccessing Timer/Counter0 counter value and so on).The definitions in Table 51 are also used extensively throughout the document.Table 51.

DefinitionsBOTTOMThe counter reaches the BOTTOM when it becomes zero (0x00).MAXThe counter reaches its MAXimum when it becomes 0xFF (decimal 255).TOPThe counter reaches the TOP when it becomes equal to the highestvalue in the count sequence. The TOP value can be assigned to be thefixed value 0xFF (MAX) or the value stored in the OCR0 Register. Theassignment is dependent on the mode of operation.Timer/Counter ClockSourcesThe Timer/Counter can be clocked by an internal synchronous or an external asynchronous clock source. The clock source clkT0 is by default equal to the MCU clock, clkI/O.When the AS0 bit in the ASSR Register is written to logic one, the clock source is takenfrom the Timer/Counter Oscillator connected to TOSC1 and TOSC2. For details onasynchronous operation, see “Asynchronous Status Register – ASSR” on page 104.

Fordetails on clock sources and prescaler, see “Timer/Counter Prescaler” on page 107.Counter UnitThe main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit.Figure 35 shows a block diagram of the counter and its surrounding environment.Figure 35. Counter Unit Block DiagramDATA BUSTOVn(Int.Req.)TOSC1countTCNTnclearclk TnControl LogicPrescalerT/COscillatordirectionbottomTOSC2topclkI/O912467M–AVR–11/04Signal description (internal signals):countIncrement or decrement TCNT0 by 1.directionSelects between increment and decrement.clearClear TCNT0 (set all bits to zero).clkT0Timer/Counter clock.topSignalizes that TCNT0 has reached maximum value.bottomSignalizes that TCNT0 has reached minimum value (zero).Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT0). clkT0 can be generated from an external or internalclock source, selected by the clock select bits (CS02:0).

When no clock source isselected (CS02:0 = 0) the timer is stopped. However, the TCNT0 value can be accessedby the CPU, regardless of whether clkT0 is present or not. A CPU write overrides (haspriority over) all counter clear or count operations.The counting sequence is determined by the setting of the WGM01 and WGM00 bitslocated in the Timer/Counter Control Register (TCCR0). There are close connectionsbetween how the counter behaves (counts) and how waveforms are generated on theoutput compare output OC0.

For more details about advanced counting sequences andwaveform generation, see “Modes of Operation” on page 95.The Timer/Counter overflow (TOV0) flag is set according to the mode of operationselected by the WGM01:0 bits. TOV0 can be used for generating a CPU interrupt.Output Compare Unit92The 8-bit comparator continuously compares TCNT0 with the Output Compare Register(OCR0). Whenever TCNT0 equals OCR0, the comparator signals a match. A match willset the output compare flag (OCF0) at the next timer clock cycle. If enabled (OCIE0 = 1),the output compare flag generates an output compare interrupt. The OCF0 flag is automatically cleared when the interrupt is executed. Alternatively, the OCF0 flag can becleared by software by writing a logical one to its I/O bit location.

The waveform generator uses the match signal to generate an output according to operating mode set by theWGM01:0 bits and compare output mode (COM01:0) bits. The max and bottom signalsare used by the waveform generator for handling the special cases of the extreme values in some modes of operation (“Modes of Operation” on page 95). Figure 36 shows ablock diagram of the output compare unit.ATmega1282467M–AVR–11/04ATmega128Figure 36. Output Compare Unit, Block DiagramDATA BUSOCRnTCNTn= (8-bit Comparator )OCFn (Int.Req.)topbottomWaveform GeneratorOCxyFOCnWGMn1:0COMn1:0The OCR0 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 theOCR0 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 OCR0 Register access may seem complex, but this is not case. When the doublebuffering is enabled, the CPU has access to the OCR0 buffer Register, and if doublebuffering is disabled the CPU will access the OCR0 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 (FOC0) bit. Forcing comparematch will not set the OCF0 flag or reload/clear the timer, but the OC0 pin will beupdated as if a real compare match had occurred (the COM01:0 bits settings definewhether the OC0 pin is set, cleared or toggled).Compare Match Blocking byTCNT0 WriteAll CPU write operations to the TCNT0 Register will block any compare match thatoccurs in the next timer clock cycle, even when the timer is stopped.

This feature allowsOCR0 to be initialized to the same value as TCNT0 without triggering an interrupt whenthe Timer/Counter clock is enabled.Using the Output CompareUnitSince writing TCNT0 in any mode of operation will block all compare matches for onetimer clock cycle, there are risks involved when changing TCNT0 when using the outputcompare channel, independently of whether the Timer/Counter is running or not. If thevalue written to TCNT0 equals the OCR0 value, the compare match will be missed,resulting in incorrect waveform generation.

Similarly, do not write the TCNT0 valueequal to BOTTOM when the counter is downcounting.932467M–AVR–11/04The setup of the OC0 should be performed before setting the Data Direction Register forthe port pin to output. The easiest way of setting the OC0 value is to use the force outputcompare (FOC0) strobe bit in normal mode. The OC0 Register keeps its value evenwhen changing between waveform generation modes.Be aware that the COM01:0 bits are not double buffered together with the comparevalue.

Changing the COM01:0 bits will take effect immediately.Compare Match OutputUnitThe Compare Output mode (COM01:0) bits have two functions. The waveform generator uses the COM01:0 bits for defining the Output Compare (OC0) state at the nextcompare match. Also, the COM01:0 bits control the OC0 pin output source. Figure 37shows a simplified schematic of the logic affected by the COM01: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 COM01:0 bitsare shown. When referring to the OC0 state, the reference is for the internal OC0 Register, not the OC0 pin.Figure 37.

Compare Match Output Unit, SchematicCOMn1COMn0FOCnWaveformGeneratorDQ1OCnDATA BUSD0OCnPinQPORTDQDDRclk I/OThe general I/O port function is overridden by the output compare (OC0) from the waveform generator if either of the COM01:0 bits are set. However, the OC0 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 OC0 pin (DDR_OC0) must be set as outputbefore the OC0 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 OC0 state beforethe output is enabled. Note that some COM01:0 bit settings are reserved for certainmodes of operation. See “8-bit Timer/Counter Register Description” on page 101.Compare Output Mode andWaveform Generation94The waveform generator uses the COM01:0 bits differently in normal, CTC, and PWMmodes. For all modes, setting the COM01:0 = 0 tells the Waveform Generator that noaction on the OC0 Register is to be performed on the next compare match.

For compareoutput actions in the non-PWM modes refer to Table 53 on page 102. For fast PWMmode, refer to Table 54 on page 102, and for phase correct PWM refer to Table 55 onpage 103.ATmega1282467M–AVR–11/04ATmega128A change of the COM01: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 FOC0 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 (WGM01:0) andCompare Output mode (COM01:0) bits. The Compare Output mode bits do not affectthe counting sequence, while the Waveform Generation mode bits do. The COM01:0bits control whether the PWM output generated should be inverted or not (inverted ornon-inverted PWM).

For non-PWM modes the COM01:0 bits control whether the outputshould be set, cleared, or toggled at a compare match (See “Compare Match OutputUnit” on page 94.).For detailed timing information refer to “Timer/Counter Timing Diagrams” on page 99.Normal ModeThe simplest mode of operation is the normal mode (WGM01: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).

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

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

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

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