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

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

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

The remaining bits are described in theirrespective timer sections.• Bit 5 – TICIE1: Timer/Counter1, Input Capture Interrupt EnableWhen this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Input Capture Interrupt is enabled. Thecorresponding Interrupt Vector (see “Interrupts” on page 44) is executed when the ICF1Flag, located in TIFR, is set.• Bit 4 – OCIE1A: Timer/Counter1, Output Compare A Match Interrupt EnableWhen this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Output Compare A match interrupt is enabled. Thecorresponding Interrupt Vector (see “Interrupts” on page 44) is executed when theOCF1A Flag, located in TIFR, is set.• Bit 3 – OCIE1B: Timer/Counter1, Output Compare B Match Interrupt EnableWhen this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Output Compare B match interrupt is enabled.

Thecorresponding Interrupt Vector (see “Interrupts” on page 44) is executed when theOCF1B Flag, located in TIFR, is set.• Bit 2 – TOIE1: Timer/Counter1, Overflow Interrupt EnableWhen this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Overflow Interrupt is enabled. The correspondingInterrupt Vector (see “Interrupts” on page 44) is executed when the TOV1 Flag, locatedin TIFR, is set.100ATmega8(L)2486O–AVR–10/04ATmega8(L)Timer/Counter Interrupt FlagRegister – TIFR(1)Bit76543210OCF2TOV2ICF1OCF1AOCF1BTOV1–TOV0Read/WriteR/WR/WR/WR/WR/WR/WRR/WInitial Value00000000Note:TIFR1.

This register contains flag bits for several Timer/Counters, but only Timer1 bits aredescribed in this section. The remaining bits are described in their respective timersections.• Bit 5 – ICF1: Timer/Counter1, Input Capture FlagThis flag is set when a capture event occurs on the ICP1 pin. When the Input CaptureRegister (ICR1) is set by the WGM13:0 to be used as the TOP value, the ICF1 Flag isset when the counter reaches the TOP value.ICF1 is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively, ICF1 can be cleared by writing a logic one to its bit location.• Bit 4 – OCF1A: Timer/Counter1, Output Compare A Match FlagThis flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output Compare Register A (OCR1A).Note that a Forced Output Compare (FOC1A) strobe will not set the OCF1A Flag.OCF1A is automatically cleared when the Output Compare Match A Interrupt Vector isexecuted. Alternatively, OCF1A can be cleared by writing a logic one to its bit location.• Bit 3 – OCF1B: Timer/Counter1, Output Compare B Match FlagThis flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output Compare Register B (OCR1B).Note that a Forced Output Compare (FOC1B) strobe will not set the OCF1B Flag.OCF1B is automatically cleared when the Output Compare Match B Interrupt Vector isexecuted.

Alternatively, OCF1B can be cleared by writing a logic one to its bit location.• Bit 2 – TOV1: Timer/Counter1, Overflow FlagThe setting of this flag is dependent of the WGM13:0 bits setting. In normal and CTCmodes, the TOV1 Flag is set when the timer overflows. Refer to Table 39 on page 97 forthe TOV1 Flag behavior when using another WGM13:0 bit setting.TOV1 is automatically cleared when the Timer/Counter1 Overflow Interrupt Vector isexecuted.

Alternatively, TOV1 can be cleared by writing a logic one to its bit location.1012486O–AVR–10/048-bit Timer/Counter2with PWM andAsynchronousOperationTimer/Counter2 is a general purpose, single channel, 8-bit Timer/Counter module. Themain features are:• Single Channel Counter• Clear Timer on Compare Match (Auto Reload)• Glitch-free, phase Correct Pulse Width Modulator (PWM)• Frequency Generator• 10-bit Clock Prescaler• Overflow and Compare Match Interrupt Sources (TOV2 and OCF2)• Allows Clocking from External 32 kHz Watch Crystal Independent of the I/O ClockOverviewA simplified block diagram of the 8-bit Timer/Counter is shown in Figure 45.

For theactual placement of I/O pins, refer to “Pin Configurations” on page 2. CPU accessibleI/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific I/ORegister and bit locations are listed in the “8-bit Timer/Counter Register Description” onpage 115.Figure 45. 8-bit Timer/Counter Block DiagramTCCRncountTOVn(Int. Req.)clearControl LogicdirectionclkTnTOSC1BOTTOMTOPPrescalerT/COscillatorTOSC2Timer/CounterTCNTn=0= 0xFFOCn(Int.

Req.)WaveformGeneration=clkI/OOCnDATA BUSOCRnSynchronized Status FlagsclkI/OSynchronization UnitclkASYStatus FlagsASSRnasynchronous ModeSelect (ASn)102ATmega8(L)2486O–AVR–10/04ATmega8(L)RegistersThe Timer/Counter (TCNT2) and Output Compare Register (OCR2) are 8-bit registers.Interrupt request (shorten as Int.Req.) signals are all visible in the Timer Interrupt FlagRegister (TIFR). All interrupts are individually masked with the Timer Interrupt MaskRegister (TIMSK). TIFR and TIMSK are not shown in the figure since these registers areshared by other timer units.The Timer/Counter can be clocked internally, via the prescaler, or asynchronouslyclocked from the TOSC1/2 pins, as detailed later in this section. The asynchronousoperation is controlled by the Asynchronous Status Register (ASSR). The Clock Selectlogic block controls which clock source the Timer/Counter uses to increment (or decrement) its value.

The Timer/Counter is inactive when no clock source is selected. Theoutput from the clock select logic is referred to as the timer clock (clkT2).The double buffered Output Compare Register (OCR2) is compared with theTimer/Counter value at all times. The result of the compare can be used by the waveform generator to generate a PWM or variable frequency output on the Output ComparePin (OC2).

For details, see “Output Compare Unit” on page 105. The Compare Matchevent will also set the Compare Flag (OCF2) 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 2.

However, when using theregister or bit defines in a program, the precise form must be used (i.e., TCNT2 foraccessing Timer/Counter2 counter value and so on).The definitions in Table 41 are also used extensively throughout the document.Table 41. DefinitionsTimer/Counter ClockSourcesBOTTOMThe 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 OCR2 Register. Theassignment is dependent on the mode of operation.The Timer/Counter can be clocked by an internal synchronous or an external asynchronous clock source. The clock source clkT2 is by default equal to the MCU clock, clkI/O.When the AS2 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 117. Fordetails on clock sources and prescaler, see “Timer/Counter Prescaler” on page 121.1032486O–AVR–10/04Counter UnitThe main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit.Figure 46 shows a block diagram of the counter and its surrounding environment.Figure 46. Counter Unit Block DiagramTOVn(Int. Req.)DATA BUSTOSC1countTCNTnclearControl Logicclk TnPrescalerT/COscillatordirectionBOTTOMTOSC2TOPclkI/OSignal description (internal signals):countIncrement or decrement TCNT2 by 1.directionSelects between increment and decrement.clearClear TCNT2 (set all bits to zero).clkT2Timer/Counter clock.TOPSignalizes that TCNT2 has reached maximum value.BOTTOMSignalizes that TCNT2 has reached minimum value (zero).Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT2).

clkT2 can be generated from an external or internalclock source, selected by the clock select bits (CS22:0). When no clock source isselected (CS22:0 = 0) the timer is stopped. However, the TCNT2 value can be accessedby the CPU, regardless of whether clkT2 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 WGM21 and WGM20 bitslocated in the Timer/Counter Control Register (TCCR2).

There are close connectionsbetween how the counter behaves (counts) and how waveforms are generated on theOutput Compare Output OC2. For more details about advanced counting sequencesand waveform generation, see “Modes of Operation” on page 108.The Timer/Counter Overflow (TOV2) Flag is set according to the mode of operationselected by the WGM21:0 bits. TOV2 can be used for generating a CPU interrupt.104ATmega8(L)2486O–AVR–10/04ATmega8(L)Output Compare UnitThe 8-bit comparator continuously compares TCNT2 with the Output Compare Register(OCR2). Whenever TCNT2 equals OCR2, the comparator signals a match.

A match willset the Output Compare Flag (OCF2) at the next timer clock cycle. If enabled (OCIE2 =1), the Output Compare Flag generates an Output Compare interrupt. The OCF2 Flag isautomatically cleared when the interrupt is executed. Alternatively, the OCF2 Flag canbe cleared 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 bythe WGM21:0 bits and Compare Output mode (COM21:0) bits. The max and bottom signals are used by the waveform generator for handling the special cases of the extremevalues in some modes of operation (see “Modes of Operation” on page 108).Figure 47 shows a block diagram of the Output Compare unit.Figure 47.

Output Compare Unit, Block DiagramDATA BUSOCRnTCNTn= (8-bit Comparator )OCFn (Int. Req.)TOPBOTTOMWaveform GeneratorOCxyFOCnWGMn1:0COMn1:0The OCR2 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 theOCR2 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 OCR2 Register access may seem complex, but this is not case. When the doublebuffering is enabled, the CPU has access to the OCR2 Buffer Register, and if doublebuffering is disabled the CPU will access the OCR2 directly.1052486O–AVR–10/04Force Output CompareIn non-PWM Waveform Generation modes, the match output of the comparator can beforced by writing a one to the Force Output Compare (FOC2) bit. Forcing CompareMatch will not set the OCF2 Flag or reload/clear the timer, but the OC2 pin will beupdated as if a real Compare Match had occurred (the COM21:0 bits settings definewhether the OC2 pin is set, cleared or toggled).Compare Match Blocking byTCNT2 WriteAll CPU write operations to the TCNT2 Register will block any Compare Match thatoccurs in the next timer clock cycle, even when the timer is stopped.

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

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

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

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