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

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

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

Req.)WaveformGeneration=OCnADATA BUSOCRnAOCFnB(Int.Req.)FixedTOPValuesWaveformGeneration=OCRnBOCnB( From AnalogComparator Ouput )ICFn (Int.Req.)EdgeDetectorICRnNoiseCancelerICPnTCCRnANote:RegistersTCCRnB1. Refer to “Pin Configurations” on page 2, Table 22 on page 56, and Table 28 on page61 for Timer/Counter1 pin placement and description.The Timer/Counter (TCNT1), Output Compare Registers (OCR1A/B), and Input CaptureRegister (ICR1) are all 16-bit registers. Special procedures must be followed whenaccessing the 16-bit registers.

These procedures are described in the section “Accessing 16-bit Registers” on page 77. The Timer/Counter Control Registers (TCCR1A/B) are8-bit registers and have no CPU access restrictions. Interrupt requests (abbreviated toInt.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR).All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK).TIFR and TIMSK are not shown in the figure since these registers are shared by othertimer units.The Timer/Counter can be clocked internally, via the prescaler, or by an external clocksource on the T1 pin.

The Clock Select logic block controls which clock source and edgethe Timer/Counter uses to increment (or decrement) its value. The Timer/Counter isinactive when no clock source is selected. The output from the clock select logic isreferred to as the timer clock (clkT1).The double buffered Output Compare Registers (OCR1A/B) are compared with theTimer/Counter value at all time. The result of the compare can be used by the waveformgenerator to generate a PWM or variable frequency output on the Output Compare Pin(OC1A/B).

See “Output Compare Units” on page 83. The Compare Match event will also752486O–AVR–10/04set the Compare Match Flag (OCF1A/B) which can be used to generate an OutputCompare interrupt request.The Input Capture Register can capture the Timer/Counter value at a given external(edge triggered) event on either the Input Capture Pin (ICP1) or on the Analog Comparator pins (see “Analog Comparator” on page 190). The Input Capture unit includes adigital filtering unit (Noise Canceler) for reducing the chance of capturing noise spikes.The TOP value, or maximum Timer/Counter value, can in some modes of operation bedefined by either the OCR1A Register, the ICR1 Register, or by a set of fixed values.When using OCR1A as TOP value in a PWM mode, the OCR1A Register can not beused for generating a PWM output.

However, the TOP value will in this case be doublebuffered allowing the TOP value to be changed in run time. If a fixed TOP value isrequired, the ICR1 Register can be used as an alternative, freeing the OCR1A to beused as PWM output.DefinitionsThe following definitions are used extensively throughout the document:Table 35. DefinitionsCompatibilityBOTTOMThe counter reaches the BOTTOM when it becomes 0x0000.MAXThe counter reaches its MAXimum when it becomes 0xFFFF (decimal65535).TOPThe counter reaches the TOP when it becomes equal to the highestvalue in the count sequence.

The TOP value can be assigned to be oneof the fixed values: 0x00FF, 0x01FF, or 0x03FF, or to the value stored inthe OCR1A or ICR1 Register. The assignment is dependent of the modeof operation.The 16-bit Timer/Counter has been updated and improved from previous versions of the16-bit AVR Timer/Counter. This 16-bit Timer/Counter is fully compatible with the earlierversion regarding:•All 16-bit Timer/Counter related I/O Register address locations, including TimerInterrupt Registers.•Bit locations inside all 16-bit Timer/Counter Registers, including Timer InterruptRegisters.•Interrupt Vectors.The following control bits have changed name, but have same functionality and registerlocation:•PWM10 is changed to WGM10.•PWM11 is changed to WGM11.•CTC1 is changed to WGM12.The following bits are added to the 16-bit Timer/Counter Control Registers:•FOC1A and FOC1B are added to TCCR1A.•WGM13 is added to TCCR1B.The 16-bit Timer/Counter has improvements that will affect the compatibility in somespecial cases.76ATmega8(L)2486O–AVR–10/04ATmega8(L)Accessing 16-bitRegistersThe TCNT1, OCR1A/B, and ICR1 are 16-bit registers that can be accessed by the AVRCPU via the 8-bit data bus.

The 16-bit register must be byte accessed using two read orwrite operations. The 16-bit timer has a single 8-bit register for temporary storing of theHigh byte of the 16-bit access. The same temporary register is shared between all 16-bitregisters within the 16-bit timer. Accessing the Low byte triggers the 16-bit read or writeoperation. When the Low byte of a 16-bit register is written by the CPU, the High bytestored in the temporary register, and the Low byte written are both copied into the 16-bitregister in the same clock cycle. When the Low byte of a 16-bit register is read by theCPU, the High byte of the 16-bit register is copied into the temporary register in thesame clock cycle as the Low byte is read.Not all 16-bit accesses uses the temporary register for the High byte. Reading theOCR1A/B 16-bit registers does not involve using the temporary register.To do a 16-bit write, the High byte must be written before the Low byte.

For a 16-bitread, the Low byte must be read before the High byte.The following code examples show how to access the 16-bit Timer Registers assumingthat no interrupts updates the temporary register. The same principle can be useddirectly for accessing the OCR1A/B and ICR1 Registers. Note that when using “C”, thecompiler handles the 16-bit access.Assembly Code Example(1)...; Set TCNT1 to 0x01FFldi r17,0x01ldi r16,0xFFout TCNT1H,r17out TCNT1L,r16; Read TCNT1 into r17:r16in r16,TCNT1Lin r17,TCNT1H...C Code Example(1)unsigned int i;.../* Set TCNT1 to 0x01FF */TCNT1 = 0x1FF;/* Read TCNT1 into i */i = TCNT1;...Note:1. The example code assumes that the part specific header file is included.The assembly code example returns the TCNT1 value in the r17:r16 Register pair.It is important to notice that accessing 16-bit registers are atomic operations.

If an interrupt occurs between the two instructions accessing the 16-bit register, and the interruptcode updates the temporary register by accessing the same or any other of the 16-bitTimer Registers, then the result of the access outside the interrupt will be corrupted.Therefore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access.772486O–AVR–10/04The following code examples show how to do an atomic read of the TCNT1 Registercontents.

Reading any of the OCR1A/B or ICR1 Registers can be done by using thesame principle.Assembly Code Example(1)TIM16_ReadTCNT1:; Save Global Interrupt Flagin r18,SREG; Disable interruptscli; Read TCNT1 into r17:r16in r16,TCNT1Lin r17,TCNT1H; Restore Global Interrupt Flagout SREG,r18retC Code Example(1)unsigned int TIM16_ReadTCNT1( void ){unsigned char sreg;unsigned int i;/* Save Global Interrupt Flag */sreg = SREG;/* Disable interrupts */_CLI();/* Read TCNT1 into i */i = TCNT1;/* Restore Global Interrupt Flag */SREG = sreg;return i;}Note:1. The example code assumes that the part specific header file is included.The assembly code example returns the TCNT1 value in the r17:r16 Register pair.78ATmega8(L)2486O–AVR–10/04ATmega8(L)The following code examples show how to do an atomic write of the TCNT1 Registercontents.

Writing any of the OCR1A/B or ICR1 Registers can be done by using thesame principle.Assembly Code Example(1)TIM16_WriteTCNT1:; Save Global Interrupt Flagin r18,SREG; Disable interruptscli; Set TCNT1 to r17:r16out TCNT1H,r17out TCNT1L,r16; Restore Global Interrupt Flagout SREG,r18retC Code Example(1)void TIM16_WriteTCNT1( unsigned int i ){unsigned char sreg;unsigned int i;/* Save Global Interrupt Flag */sreg = SREG;/* Disable interrupts */_CLI();/* Set TCNT1 to i */TCNT1 = i;/* Restore Global Interrupt Flag */SREG = sreg;}Note:1. The example code assumes that the part specific header file is included.The assembly code example requires that the r17:r16 Register pair contains the value tobe written to TCNT1.Reusing the Temporary HighByte RegisterIf writing to more than one 16-bit register where the High byte is the same for all registers written, then the High byte only needs to be written once.

However, note that thesame rule of atomic operation described previously also applies in this case.792486O–AVR–10/04Timer/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(CS12:0) bits located in the Timer/Counter Control Register B (TCCR1B).

For details onclock sources and prescaler, see “Timer/Counter0 and Timer/Counter1 Prescalers” onpage 72.Counter UnitThe main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directionalcounter unit. Figure 33 shows a block diagram of the counter and its surroundings.Figure 33. Counter Unit Block DiagramDATA BUS(8-bit)TOVn(Int.

Req.)TEMP (8-bit)Clock SelectcountTCNTnH (8-bit) TCNTnL (8-bit)TCNTn (16-bit Counter)cleardirectionControl LogicEdgeDetectorclkTnTn( From Prescaler )TOPBOTTOMSignal description (internal signals):countIncrement or decrement TCNT1 by 1.directionSelect between increment and decrement.clearClear TCNT1 (set all bits to zero).clkT1Timer/Counter clock.TOPSignalize that TCNT1 has reached maximum value.BOTTOMSignalize that TCNT1 has reached minimum value (zero).The 16-bit counter is mapped into two 8-bit I/O memory locations: counter high(TCNT1H) containing the upper eight bits of the counter, and Counter Low (TCNT1L)containing the lower eight bits.

The TCNT1H Register can only be indirectly accessedby the CPU. When the CPU does an access to the TCNT1H I/O location, the CPUaccesses the High byte temporary register (TEMP). The temporary register is updatedwith the TCNT1H value when the TCNT1L is read, and TCNT1H is updated with thetemporary register value when TCNT1L is written. This allows the CPU to read or writethe entire 16-bit counter value within one clock cycle via the 8-bit data bus.

It is important to notice that there are special cases of writing to the TCNT1 Register when thecounter is counting that will give unpredictable results. The special cases are describedin the sections where they are of importance.Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT1). The clkT1 can be generated from an external orinternal clock source, selected by the clock select bits (CS12:0).

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

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

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

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