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

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

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

In normal operation the Timer/Counter OverflowFlag (TOV0) will be set in the same timer clock cycle as the TCNT0 becomes zero. TheTOV0 Flag in this case behaves like a ninth bit, except that it is only set, not cleared.However, combined with the timer overflow interrupt that automatically clears the TOV0Flag, the timer resolution can be increased by software. A new counter value can bewritten anytime.ATmega8(L)2486O–AVR–10/04ATmega8(L)Timer/Counter TimingDiagramsThe Timer/Counter is a synchronous design and the timer clock (clkT0) is thereforeshown as a clock enable signal in the following figures.

The figures include informationon when Interrupt Flags are set. Figure 28 contains timing data for basic Timer/Counteroperation. The figure shows the count sequence close to the MAX value.Figure 28. Timer/Counter Timing Diagram, No PrescalingclkI/OclkTn(clkI/O /1)TCNTnMAX - 1MAXBOTTOMBOTTOM + 1TOVnFigure 29 shows the same timing data, but with the prescaler enabled.Figure 29. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)clkI/OclkTn(clkI/O /8)TCNTnMAX - 1MAXBOTTOMBOTTOM + 1TOVn692486O–AVR–10/048-bit Timer/CounterRegister DescriptionTimer/Counter ControlRegister – TCCR0Bit76543210–––––CS02CS01CS00Read/WriteRRRRRR/WR/WR/WInitial Value00000000TCCR0• Bit 2:0 – CS02:0: Clock SelectThe three clock select bits select the clock source to be used by the Timer/Counter.Table 34.

Clock Select Bit DescriptionCS02CS01CS00Description000No clock source (Timer/Counter stopped).001clkI/O/(No prescaling)010clkI/O/8 (From prescaler)011clkI/O/64 (From prescaler)100clkI/O/256 (From prescaler)101clkI/O/1024 (From prescaler)110External clock source on T0 pin. Clock on falling edge.111External clock source on T0 pin. Clock on rising edge.If external pin modes are used for the Timer/Counter0, transitions on the T0 pin willclock the counter even if the pin is configured as an output.

This feature allows softwarecontrol of the counting.Timer/Counter Register –TCNT0Bit76543210TCNT0[7:0]TCNT0Read/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.Timer/Counter Interrupt MaskRegister – TIMSKBit76543210OCIE2TOIE2TICIE1OCIE1AOCIE1BTOIE1–TOIE0Read/WriteR/WR/WR/WR/WR/WR/WR/WR/WInitial Value00000000TIMSK• 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.70ATmega8(L)2486O–AVR–10/04ATmega8(L)Timer/Counter Interrupt FlagRegister – TIFRBit76543210OCF2TOV2ICF1OCF1AOCF1BTOV1–TOV0Read/WriteR/WR/WR/WR/WR/WR/WR/WR/WInitial Value00000000TIFR• 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. Alternatively,TOV0 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE0(Timer/Counter0 Overflow Interrupt Enable), and TOV0 are set (one), theTimer/Counter0 Overflow interrupt is executed.712486O–AVR–10/04Timer/Counter0 andTimer/Counter1PrescalersTimer/Counter1 and Timer/Counter0 share the same prescaler module, but theTimer/Counters can have different prescaler settings. The description below applies toboth Timer/Counter1 and Timer/Counter0.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 frequencyequal to system clock frequency (fCLK_I/O). Alternatively, one of four taps from the prescaler can be used as a clock source. The prescaled clock has a frequency of eitherfCLK_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 and Timer/Counter0.

Since the prescaler is not affected by the Timer/Counter’s clock select, the state of the prescaler willhave implications for situations where a prescaled clock is used. One example of prescaling artifacts occurs when the timer is enabled and clocked by the prescaler(6 > CSn2:0 > 1). The number of system clock cycles from when the timer is enabled tothe first count occurs can be from 1 to N+1 system clock cycles, where N equals theprescaler 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 uses 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 T1/T0 pin can be used as Timer/Counter clock(clkT1/clkT0). The T1/T0 pin is sampled once every system clock cycle by the pin synchronization logic.

The synchronized (sampled) signal is then passed through the edgedetector. Figure 30 shows a functional equivalent block diagram of the T1/T0 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/clkT0 pulse for each positive (CSn2:0 = 7) or negative (CSn2:0 = 6) edge it detects.Figure 30.

T1/T0 Pin SamplingTnD QDQTn_sync(To ClockSelect Logic)D 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 T1/T0 pin to the counter is updated.Enabling and disabling of the clock input must be done when T1/T0 has been stable forat least one system clock cycle, otherwise it is a risk that a false Timer/Counter clockpulse is generated.72ATmega8(L)2486O–AVR–10/04ATmega8(L)Each 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 31.

Prescaler for Timer/Counter0 and Timer/Counter1(1)clk I/OClearPSR10T0SynchronizationT1SynchronizationclkT1Note:Special Function IO Register –SFIORclkT01. The synchronization logic on the input pins (T1/T0) is shown in Figure 30.Bit76543210––––ACMEPUDPSR2PSR10Read/WriteRRRRR/WR/WR/WR/WInitial Value00000000SFIOR• Bit 0 – PSR10: Prescaler Reset Timer/Counter1 and Timer/Counter0When this bit is written to one, the Timer/Counter1 and Timer/Counter0 prescaler will bereset.

The bit will be cleared by hardware after the operation is performed. Writing azero to this bit will have no effect. Note that Timer/Counter1 and Timer/Counter0 sharethe same prescaler and a reset of this prescaler will affect both timers. This bit willalways be read as zero.732486O–AVR–10/0416-bitTimer/Counter1The 16-bit Timer/Counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. The main features are:• True 16-bit Design (i.e., allows 16-bit PWM)• Two Independent Output Compare Units• Double Buffered Output Compare Registers• One Input Capture Unit• Input Capture Noise Canceler• Clear Timer on Compare Match (Auto Reload)• Glitch-free, Phase Correct Pulse Width Modulator (PWM)• Variable PWM Period• Frequency Generator• External Event Counter• Four Independent Interrupt Sources (TOV1, OCF1A, OCF1B, and ICF1)OverviewMost register and bit references in this section are written in general form.

A lower case“n” replaces the Timer/Counter number, and a lower case “x” replaces the Output Compare unit channel. However, when using the register or bit defines in a program, theprecise form must be used i.e., TCNT1 for accessing Timer/Counter1 counter value andso on.A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 32. 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 “16-bit Timer/Counter Register Description”on page 95.74ATmega8(L)2486O–AVR–10/04ATmega8(L)Figure 32. 16-bit Timer/Counter Block Diagram(1)CountClearDirectionTOVn(Int. Req.)Control LogicclkTnClock SelectEdgeDetectorTOPTnBOTTOM( From Prescaler )Timer/CounterTCNTn==0OCFnA(Int.

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

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

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

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