ATmega128 (961732), страница 21

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

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

Modifying the counter (TCNT0) whilethe counter is running, introduces a risk of missing a compare match between TCNT0and the OCR0 Register.Output Compare Register –OCR0Bit76543210OCR0[7:0]OCR0Read/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 (TCNT0). A match can be used to generate an output compareinterrupt, or to generate a waveform output on the OC0 pin.1032467M–AVR–11/04Asynchronous Operationof the Timer/CounterAsynchronous StatusRegister – ASSRBit76543210––––AS0TCN0UBOCR0UBTCR0UBRead/WriteRRRRR/WRRRInitial Value00000000ASSR• Bit 3 – AS0: Asynchronous Timer/Counter0When AS0 is written to zero, Timer/Counter0 is clocked from the I/O clock, clkI/O. WhenAS0 is written to one, Timer/Counter is clocked from a crystal Oscillator connected tothe Timer Oscillator 1 (TOSC1) pin.

When the value of AS0 is changed, the contents ofTCNT0, OCR0, and TCCR0 might be corrupted.• Bit 2 – TCN0UB: Timer/Counter0 Update BusyWhen Timer/Counter0 operates asynchronously and TCNT0 is written, this bit becomesset. When TCNT0 has been updated from the temporary storage register, this bit iscleared by hardware. A logical zero in this bit indicates that TCNT0 is ready to beupdated with a new value.• Bit 1 – OCR0UB: Output Compare Register0 Update BusyWhen Timer/Counter0 operates asynchronously and OCR0 is written, this bit becomesset. When OCR0 has been updated from the temporary storage register, this bit iscleared by hardware.

A logical zero in this bit indicates that OCR0 is ready to beupdated with a new value.• Bit 0 – TCR0UB: Timer/Counter Control Register0 Update BusyWhen Timer/Counter0 operates asynchronously and TCCR0 is written, this bit becomesset. When TCCR0 has been updated from the temporary storage register, this bit iscleared by hardware. A logical zero in this bit indicates that TCCR0 is ready to beupdated with a new value.If a write is performed to any of the three Timer/Counter0 Registers while its updatebusy flag is set, the updated value might get corrupted and cause an unintentional interrupt to occur.The mechanisms for reading TCNT0, OCR0, and TCCR0 are different.

When readingTCNT0, the actual timer value is read. When reading OCR0 or TCCR0, the value in thetemporary storage register is read.Asynchronous Operation ofTimer/Counter0When Timer/Counter0 operates asynchronously, some considerations must be taken.•Warning: When switching between asynchronous and synchronous clocking ofTimer/Counter0, the Timer Registers TCNT0, OCR0, and TCCR0 might becorrupted. A safe procedure for switching clock source is:1. Disable the Timer/Counter0 interrupts by clearing OCIE0 and TOIE0.2. Select clock source by setting AS0 as appropriate.3. Write new values to TCNT0, OCR0, and TCCR0.4.

To switch to asynchronous operation: Wait for TCN0UB, OCR0UB, andTCR0UB.5. Clear the Timer/Counter0 interrupt flags.6. Enable interrupts, if needed.104ATmega1282467M–AVR–11/04ATmega128•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/Counter0 operation.The CPU main clock frequency must be more than four times the Oscillatorfrequency.•When writing to one of the registers TCNT0, OCR0, or TCCR0, 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 TemporaryRegister have been transferred to its destination. Each of the three mentionedregisters have their individual temporary register, which means that e.g., writing toTCNT0 does not disturb an OCR0 write in progress.

To detect that a transfer to thedestination register has taken place, the Asynchronous Status Register – ASSR hasbeen implemented.•When entering Power-save or Extended Standby mode after having written toTCNT0, OCR0, or TCCR0, the user must wait until the written register has beenupdated if Timer/Counter0 is used to wake up the device.

Otherwise, the MCU willenter sleep mode before the changes are effective. This is particularly important ifthe Output Compare0 interrupt is used to wake up the device, since the outputcompare function is disabled during writing to OCR0 or TCNT0. If the write cycle isnot finished, and the MCU enters sleep mode before the OCR0UB bit returns tozero, the device will never receive a compare match interrupt, and the MCU will notwake up.•If Timer/Counter0 is used to wake the device up from Power-save or ExtendedStandby mode, precautions must be taken if the user wants to re-enter one of thesemodes: The interrupt logic needs one TOSC1 cycle to be reset. If the time betweenwake-up and re-entering sleep mode is less than one TOSC1 cycle, the interrupt willnot occur, and the device will fail to wake up.

If the user is in doubt whether the timebefore re-entering Power-save or Extended Standby mode is sufficient, the followingalgorithm can be used to ensure that one TOSC1 cycle has elapsed:1. Write a value to TCCR0, TCNT0, or OCR0.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/Counter0 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/Counter0after power-up or wake-up from Power-down or Standby mode.

The contents of allTimer/Counter0 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 TCNT0 Register shortly after wake-up from Power-save may give anincorrect result.

Since TCNT0 is clocked on the asynchronous TOSC clock, readingTCNT0 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, TCNT0 will1052467M–AVR–11/04read 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 TCNT0 is thus as follows:1.

Write any value to either of the registers OCR0 or TCCR0.2. Wait for the corresponding Update Busy Flag to be cleared.3. Read TCNT0.•Timer/Counter Interrupt MaskRegister – TIMSKDuring 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.Bit76543210OCIE2TOIE2TICIE1OCIE1AOCIE1BTOIE1OCIE0TOIE0Read/WriteR/WR/WR/WR/WR/WR/WR/WR/WInitial Value00000000TIMSK• Bit 1 – OCIE0: Timer/Counter0 Output Compare Match Interrupt EnableWhen the OCIE0 bit is written to one, and the I-bit in the Status Register is set (one), theTimer/Counter0 Compare Match interrupt is enabled.

The corresponding interrupt isexecuted if a compare match in Timer/Counter0 occurs, i.e., when the OCF0 bit is set inthe Timer/Counter Interrupt Flag Register – TIFR.• Bit 0 – TOIE0: Timer/Counter0 Overflow Interrupt EnableWhen the TOIE0 bit is written to one, and the I-bit in the Status Register is set (one), theTimer/Counter0 Overflow interrupt is enabled. The corresponding interrupt is executed ifan overflow in Timer/Counter0 occurs, i.e., when the TOV0 bit is set in theTimer/Counter Interrupt Flag Register – TIFR.Timer/Counter Interrupt FlagRegister – TIFRBit76543210OCF2TOV2ICF1OCF1AOCF1BTOV1OCF0TOV0Read/WriteR/WR/WR/WR/WR/WR/WR/WR/WInitial Value00000000TIFR• Bit 1 – OCF0: Output Compare Flag 0The OCF0 bit is set (one) when a compare match occurs between the Timer/Counter0and the data in OCR0 – Output Compare Register0.

OCF0 is cleared by hardware whenexecuting the corresponding interrupt handling vector. Alternatively, OCF0 is cleared bywriting a logic one to the flag. When the I-bit in SREG, OCIE0 (Timer/Counter0 Compare Match Interrupt Enable), and OCF0 are set (one), the Timer/Counter0 CompareMatch Interrupt is executed.• Bit 0 – TOV0: Timer/Counter0 Overflow FlagThe bit TOV0 is set (one) when an overflow occurs in Timer/Counter0. TOV0 is clearedby hardware when executing the corresponding interrupt handling vector.

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

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

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

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