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

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

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

Alternatively, OCF1C can be cleared by writing a logic one to its bit location.1412467M–AVR–11/04Timer/Counter3,Timer/Counter2, andTimer/Counter1PrescalersTimer/Counter3, Timer/Counter1, and Timer/Counter2 share the same prescaler module, but the Timer/Counters can have different prescaler settings. The description belowapplies to all of the mentioned Timer/Counters.Internal Clock SourceThe Timer/Counter can be clocked directly by the System Clock (by setting the CSn2:0= 1). This provides the fastest operation, with a maximum Timer/Counter clock frequency equal to system clock frequency (fCLK_I/O).

Alternatively, one of four taps fromthe prescaler can be used as a clock source. The prescaled clock has a frequency ofeither fCLK_I/O/8, fCLK_I/O/64, fCLK_I/O/256, or fCLK_I/O/1024.Prescaler ResetThe prescaler is free running, i.e., operates independently of the clock select logic of theTimer/Counter, and it is shared by Timer/Counter1, Timer/Counter2, andTimer/Counter3. Since the prescaler is not affected by the Timer/Counter’s clock select,the state of the prescaler will have implications for situations where a prescaled clock isused. One example of prescaling artifacts occurs when the timer is enabled and clockedby the prescaler (6 > CSn2:0 > 1).

The number of system clock cycles from when thetimer is enabled to the first count occurs can be from 1 to N+1 system clock cycles,where N equals the prescaler divisor (8, 64, 256, or 1024).It is possible to use the Prescaler Reset for synchronizing the Timer/Counter to programexecution. However, care must be taken if the other Timer/Counter that shares thesame prescaler also use prescaling. A Prescaler Reset will affect the prescaler periodfor all Timer/Counters it is connected to.External Clock SourceAn external clock source applied to the Tn pin can be used as Timer/Counter clock(clkT1/clkT2/clkT3). The Tn pin is sampled once every system clock cycle by the pin synchronization logic.

The synchronized (sampled) signal is then passed through the edgedetector. Figure 59 shows a functional equivalent block diagram of the Tn synchronization and edge detector logic. The registers are clocked at the positive edge of theinternal system clock (clkI/O). The latch is transparent in the high period of the internalsystem clock.The edge detector generates one clkT1/clkT2/clkT3 pulse for each positive (CSn2:0 = 7) ornegative (CSn2:0 = 6) edge it detects.Figure 59.

Tn Pin SamplingTnD QD QDTn_sync(To ClockSelect Logic)QLEclk I/OSynchronizationEdge DetectorThe synchronization and edge detector logic introduces a delay of 2.5 to 3.5 systemclock cycles from an edge has been applied to the Tn pin to the counter is updated.Enabling and disabling of the clock input must be done when Tn has been stable for atleast one system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulseis generated.142ATmega1282467M–AVR–11/04ATmega128Each half period of the external clock applied must be longer than one system clockcycle to ensure correct sampling.

The external clock must be guaranteed to have lessthan half the system clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Sincethe edge detector uses sampling, the maximum frequency of an external clock it candetect is half the sampling frequency (Nyquist sampling theorem). However, due to variation of the system clock frequency and duty cycle caused by Oscillator source (crystal,resonator, and capacitors) tolerances, it is recommended that maximum frequency of anexternal clock source is less than fclk_I/O/2.5.An external clock source can not be prescaled.Figure 60. Prescaler for Timer/Counter1, Timer/Counter2, and Timer/Counter3CKT3T20T100CS30CS20CS31CS21CS11CS32CS22CS12TIMER/COUNTER3 CLOCK SOURCEclkT3Note:Special Function IO Register –SFIORCK/1024CK/64CK/8PSR321CK/25610-BIT T/C PRESCALERClearCS10TIMER/COUNTER2 CLOCK SOURCEclkT2TIMER/COUNTER1 CLOCK SOURCEclkT1The synchronization logic on the input pins (T3/T2/T1) is shown in Figure 59.Bit76543210TSM–––ACMEPUDPSR0PSR321Read/WriteR/WRRRR/WR/WR/WR/WInitial Value00000000SFIOR• Bit 7 – TSM: Timer/Counter Synchronization ModeWriting the TSM bit to one activates the Timer/Counter Synchronization mode.

In thismode, the value that is written to the PSR0 and PSR321 bits is kept, hence keeping thecorresponding prescaler reset signals asserted. This ensures that the correspondingTimer/Counters are halted and can be configured to the same value without the risk ofone of them advancing during configuration. When the TSM bit is written to zero, thePSR0 and PSR321 bits are cleared by hardware, and the Timer/Counters start countingsimultaneously.• Bit 0 – PSR321: Prescaler Reset Timer/Counter3, Timer/Counter2, andTimer/Counter1When this bit is one, the Timer/Counter3, Timer/Counter1, and Timer/Counter2 prescaler will be reset. This bit is normally cleared immediately by hardware, except if theTSM bit is set.

Note that Timer/Counter3, Timer/Counter1, and Timer/Counter2 sharethe same prescaler and a reset of this prescaler will affect all three timers.1432467M–AVR–11/048-bit Timer/Counter2with PWMTimer/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• External Event Counter• 10-bit Clock Prescaler• Overflow and Compare Match Interrupt Sources (TOV2 and OCF2)OverviewA simplified block diagram of the 8-bit Timer/Counter is shown in Figure 61.

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 156.Figure 61. 8-Bit Timer/Counter Block DiagramTCCRncountTOVn(Int.Req.)clearControl Logicdirectionclk TnClock SelectEdgeDetectorDATA BUSBOTTOMTnTOP( From Prescaler )Timer/CounterTCNTn==0= 0xFFOCn(Int.Req.)WaveformGenerationOCnOCRnRegistersThe Timer/Counter (TCNT2) and Output Compare Register (OCR2) are 8-bit registers.Interrupt request (abbreviated to Int.Req.

in the figure) signals are all visible in the TimerInterrupt Flag Register (TIFR). All interrupts are individually masked with the TimerInterrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure sincethese registers are shared by other timer units.The Timer/Counter can be clocked internally, via the prescaler, or by an external clocksource on the T2 pin. The Clock Select logic block controls which clock source and edgethe Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is144ATmega1282467M–AVR–11/04ATmega128inactive when no clock source is selected.

The output from the clock select logic isreferred 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).

See “Output Compare Unit” on page 146. for details. 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 63 are also used extensively throughout the document.Table 63. DefinitionsBOTTOMThe counter reaches the BOTTOM when it becomes 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.Timer/Counter ClockSourcesThe Timer/Counter can be clocked by an internal or an external clock source. The clocksource is selected by the clock select logic which is controlled by the clock select(CS22:0) bits located in the Timer/Counter Control Register (TCCR2).

For details onc l oc k s ou r c e s a n d p re s c al er , s e e “ T i m e r/ C o u nt e r3 , Ti me r /C ou n te r 2, a n dTimer/Counter1 Prescalers” on page 142.Counter UnitThe main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit.Figure 62 shows a block diagram of the counter and its surroundings.Figure 62. Counter Unit Block DiagramTOVn(Int.Req.)DATA BUSClock SelectcountTCNTnclearControl LogicclkTnEdgeDetectorTndirection( From Prescaler )bottomtopSignal description (internal signals):countIncrement or decrement TCNT2 by 1.directionSelect between increment and decrement.1452467M–AVR–11/04clearClear TCNT2 (set all bits to zero).clkTnTimer/Counter clock, referred to as clkT0 in the following.topSignalize that TCNT2 has reached maximum value.bottomSignalize that TCNT2 has reached minimum value (zero).Depending of 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 WGM01 and WGM00 bitslocated in the Timer/Counter Control Register (TCCR2).

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

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

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

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