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

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

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

Compare Output Mode, Fast PWM Mode(1)COM21COM2000Normal port operation, OC2 disconnected.01Reserved10Clear OC2 on Compare Match, set OC2 at TOP11Set OC2 on Compare Match, clear OC2 at TOPNote:Description1. A special case occurs when OCR2 equals TOP and COM21 is set. In this case, theCompare Match is ignored, but the set or clear is done at TOP. See “Fast PWMMode” on page 110 for more details.Table 45 shows the COM21:0 bit functionality when the WGM21:0 bits are set to phasecorrect PWM mode.Table 45.

Compare Output Mode, Phase Correct PWM Mode(1)COM21COM2000Normal port operation, OC2 disconnected.01Reserved10Clear OC2 on Compare Match when up-counting. Set OC2 on CompareMatch when downcounting.11Set OC2 on Compare Match when up-counting. Clear OC2 on CompareMatch when downcounting.Note:116Description1. A special case occurs when OCR2 equals TOP and COM21 is set. In this case, theCompare Match is ignored, but the set or clear is done at TOP. See “Phase CorrectPWM Mode” on page 111 for more details.ATmega8(L)2486O–AVR–10/04ATmega8(L)• Bit 2:0 – CS22:0: Clock SelectThe three clock select bits select the clock source to be used by the Timer/Counter, seeTable 46.Table 46.

Clock Select Bit DescriptionTimer/Counter Register –TCNT2CS22CS21CS20000No clock source (Timer/Counter stopped).001clkT2S/(No prescaling)010clkT2S/8 (From prescaler)011clkT2S/32 (From prescaler)100clkT2S/64 (From prescaler)101clkT2S/128 (From prescaler)110clkT2S/256 (From prescaler)111clkT2S/1024 (From prescaler)Bit7Description6543210TCNT2[7:0]TCNT2Read/WriteR/WR/WR/WR/WR/WR/WR/WR/WInitial Value00000000The Timer/Counter Register gives direct access, both for read and write operations, tothe Timer/Counter unit 8-bit counter. Writing to the TCNT2 Register blocks (removes)the Compare Match on the following timer clock. Modifying the counter (TCNT2) whilethe counter is running, introduces a risk of missing a Compare Match between TCNT2and the OCR2 Register.Output Compare Register –OCR2Bit76543210OCR2[7:0]OCR2Read/WriteR/WR/WR/WR/WR/WR/WR/WR/WInitial Value00000000The Output Compare Register contains an 8-bit value that is continuously comparedwith the counter value (TCNT2).

A match can be used to generate an Output Compareinterrupt, or to generate a waveform output on the OC2 pin.Asynchronous Operationof the Timer/CounterAsynchronous StatusRegister – ASSRBit76543210––––AS2TCN2UBOCR2UBTCR2UBRead/WriteRRRRR/WRRRInitial Value00000000ASSR• Bit 3 – AS2: Asynchronous Timer/Counter2When AS2 is written to zero, Timer/Counter 2 is clocked from the I/O clock, clkI/O. WhenAS2 is written to one, Timer/Counter 2 is clocked from a crystal Oscillator connected tothe Timer Oscillator 1 (TOSC1) pin. When the value of AS2 is changed, the contents ofTCNT2, OCR2, and TCCR2 might be corrupted.1172486O–AVR–10/04• Bit 2 – TCN2UB: Timer/Counter2 Update BusyWhen Timer/Counter2 operates asynchronously and TCNT2 is written, this bit becomesset. When TCNT2 has been updated from the temporary storage register, this bit iscleared by hardware.

A logical zero in this bit indicates that TCNT2 is ready to beupdated with a new value.• Bit 1 – OCR2UB: Output Compare Register2 Update BusyWhen Timer/Counter2 operates asynchronously and OCR2 is written, this bit becomesset. When OCR2 has been updated from the temporary storage register, this bit iscleared by hardware. A logical zero in this bit indicates that OCR2 is ready to beupdated with a new value.• Bit 0 – TCR2UB: Timer/Counter Control Register2 Update BusyWhen Timer/Counter2 operates asynchronously and TCCR2 is written, this bit becomesset. When TCCR2 has been updated from the temporary storage register, this bit iscleared by hardware.

A logical zero in this bit indicates that TCCR2 is ready to beupdated with a new value.If a write is performed to any of the three Timer/Counter2 Registers while its updatebusy flag is set, the updated value might get corrupted and cause an unintentional interrupt to occur.The mechanisms for reading TCNT2, OCR2, and TCCR2 are different. When readingTCNT2, the actual timer value is read. When reading OCR2 or TCCR2, the value in thetemporary storage register is read.Asynchronous Operation ofTimer/Counter2When Timer/Counter2 operates asynchronously, some considerations must be taken.•Warning: When switching between asynchronous and synchronous clocking ofTimer/Counter2, the Timer Registers TCNT2, OCR2, and TCCR2 might becorrupted. A safe procedure for switching clock source is:1. Disable the Timer/Counter2 interrupts by clearing OCIE2 and TOIE2.2.

Select clock source by setting AS2 as appropriate.3. Write new values to TCNT2, OCR2, and TCCR2.4. To switch to asynchronous operation: Wait for TCN2UB, OCR2UB, andTCR2UB.5. Clear the Timer/Counter2 Interrupt Flags.6. Enable interrupts, if needed.118•The Oscillator is optimized for use with a 32.768 kHz watch crystal. Applying anexternal clock to the TOSC1 pin may result in incorrect Timer/Counter2 operation.The CPU main clock frequency must be more than four times the Oscillatorfrequency.•When writing to one of the registers TCNT2, OCR2, or TCCR2, the value istransferred to a temporary register, and latched after two positive edges on TOSC1.The user should not write a new value before the contents of the temporary registerhave been transferred to its destination. Each of the three mentioned registers havetheir individual temporary register, which means that e.g.

writing to TCNT2 does notdisturb an OCR2 write in progress. To detect that a transfer to the destinationregister has taken place, the Asynchronous Status Register – ASSR has beenimplemented.•When entering Power-save mode after having written to TCNT2, OCR2, or TCCR2,the user must wait until the written register has been updated if Timer/Counter2 isused to wake up the device. Otherwise, the MCU will enter sleep mode before theATmega8(L)2486O–AVR–10/04ATmega8(L)changes are effective. This is particularly important if the Output Compare2 interruptis used to wake up the device, since the Output Compare function is disabled duringwriting to OCR2 or TCNT2. If the write cycle is not finished, and the MCU enterssleep mode before the OCR2UB bit returns to zero, the device will never receive aCompare Match interrupt, and the MCU will not wake up.•If Timer/Counter2 is used to wake the device up from Power-save mode,precautions must be taken if the user wants to re-enter one of these modes: Theinterrupt logic needs one TOSC1 cycle to be reset.

If the time between wake-up andre-entering sleep mode is less than one TOSC1 cycle, the interrupt will not occur,and the device will fail to wake up. If the user is in doubt whether the time before reentering Power-save or Extended Standby mode is sufficient, the following algorithmcan be used to ensure that one TOSC1 cycle has elapsed:1. Write a value to TCCR2, TCNT2, or OCR2.2.

Wait until the corresponding Update Busy Flag in ASSR returns to zero.3. Enter Power-save or Extended Standby mode.•When the asynchronous operation is selected, the 32.768 kHZ Oscillator forTimer/Counter2 is always running, except in Power-down and Standby modes. Aftera Power-up Reset or Wake-up from Power-down or Standby mode, the user shouldbe aware of the fact that this Oscillator might take as long as one second to stabilize.The user is advised to wait for at least one second before using Timer/Counter2after Power-up or Wake-up from Power-down or Standby mode. The contents of allTimer/Counter2 Registers must be considered lost after a wake-up from Powerdown or Standby mode due to unstable clock signal upon start-up, no matterwhether the Oscillator is in use or a clock signal is applied to the TOSC1 pin.•Description of wake up from Power-save or Extended Standby mode when the timeris clocked asynchronously: When the interrupt condition is met, the wake upprocess is started on the following cycle of the timer clock, that is, the timer isalways advanced by at least one before the processor can read the counter value.After wake-up, the MCU is halted for four cycles, it executes the interrupt routine,and resumes execution from the instruction following SLEEP.•Reading of the TCNT2 Register shortly after wake-up from Power-save may give anincorrect result.

Since TCNT2 is clocked on the asynchronous TOSC clock, readingTCNT2 must be done through a register synchronized to the internal I/O clockdomain. Synchronization takes place for every rising TOSC1 edge. When waking upfrom Power-save mode, and the I/O clock (clkI/O) again becomes active, TCNT2 willread as the previous value (before entering sleep) until the next rising TOSC1 edge.The phase of the TOSC clock after waking up from Power-save mode is essentiallyunpredictable, as it depends on the wake-up time.

The recommended procedure forreading TCNT2 is thus as follows:1. Write any value to either of the registers OCR2 or TCCR2.2. Wait for the corresponding Update Busy Flag to be cleared.3. Read TCNT2.•During asynchronous operation, the synchronization of the Interrupt Flags for theasynchronous timer takes three processor cycles plus one timer cycle. The timer istherefore advanced by at least one before the processor can read the timer valuecausing the setting of the Interrupt Flag. The Output Compare Pin is changed on thetimer clock and is not synchronized to the processor clock.1192486O–AVR–10/04Timer/Counter Interrupt MaskRegister – TIMSKBit76543210OCIE2TOIE2TICIE1OCIE1AOCIE1BTOIE1–TOIE0Read/WriteR/WR/WR/WR/WR/WR/WRR/WInitial Value00000000TIMSK• Bit 7 – OCIE2: Timer/Counter2 Output Compare Match Interrupt EnableWhen the OCIE2 bit is written to one and the I-bit in the Status Register is set (one), theTimer/Counter2 Compare Match interrupt is enabled.

The corresponding interrupt isexecuted if a Compare Match in Timer/Counter2 occurs (i.e., when the OCF2 bit is set inthe Timer/Counter Interrupt Flag Register – TIFR).• Bit 6 – TOIE2: Timer/Counter2 Overflow Interrupt EnableWhen the TOIE2 bit is written to one and the I-bit in the Status Register is set (one), theTimer/Counter2 Overflow interrupt is enabled. The corresponding interrupt is executed ifan overflow in Timer/Counter2 occurs (i.e., when the TOV2 bit is set in theTimer/Counter Interrupt Flag Register – TIFR).Timer/Counter Interrupt FlagRegister – TIFRBit76543210OCF2TOV2ICF1OCF1AOCF1BTOV1–TOV0Read/WriteR/WR/WR/WR/WR/WR/WRR/WInitial Value00000000TIFR• Bit 7 – OCF2: Output Compare Flag 2The OCF2 bit is set (one) when a Compare Match occurs between the Timer/Counter2and the data in OCR2 – Output Compare Register2.

OCF2 is cleared by hardware whenexecuting the corresponding interrupt Handling Vector. Alternatively, OCF2 is clearedby writing a logic one to the flag. When the I-bit in SREG, OCIE2 (Timer/Counter2 Compare Match Interrupt Enable), and OCF2 are set (one), the Timer/Counter2 CompareMatch Interrupt is executed.• Bit 6 – TOV2: Timer/Counter2 Overflow FlagThe TOV2 bit is set (one) when an overflow occurs in Timer/Counter2. TOV2 is clearedby hardware when executing the corresponding interrupt Handling Vector. Alternatively,TOV2 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE2(Timer/Counter2 Overflow Interrupt Enable), and TOV2 are set (one), theTimer/Counter2 Overflow interrupt is executed.

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

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

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

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