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

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

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

Special procedures must be followed whenaccessing the 16-bit registers. These procedures are described in the section “Accessing 16-bit Registers” on page 112. The Timer/Counter Control Registers (TCCRnA/B/C)are 8-bit registers and have no CPU access restrictions. Interrupt requests (shorten asInt.Req.) signals are all visible in the Timer Interrupt Flag Register (TIFR) and ExtendedTimer Interrupt Flag Register (ETIFR).

All interrupts are individually masked with theTimer Interrupt Mask Register (TIMSK) and Extended Timer Interrupt Mask Register(ETIMSK). (E)TIFR and (E)TIMSK are not shown in the figure since these registers areshared by other timer units.The Timer/Counter can be clocked internally, via the prescaler, or by an external clocksource on the Tn 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 (clkTn).The double buffered Output Compare Registers (OCRnA/B/C) are compared with theTimer/Counter value at all time. The result of the compare can be used by the waveform110ATmega1282467M–AVR–11/04ATmega128generator to generate a PWM or variable frequency output on the Output Compare Pin(OCnA/B/C). See “Output Compare Units” on page 118..

The compare match event willalso set the compare match flag (OCFnA/B/C) 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 (ICPn) or on the Analog Comparator pins (See “Analog Comparator” on page 228.) 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 OCRnA Register, the ICRn Register, or by a set of fixed values.When using OCRnA as TOP value in a PWM mode, the OCRnA 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 ICRn Register can be used as an alternative, freeing the OCRnA to beused as PWM output.DefinitionsThe following definitions are used extensively throughout the document:Table 57. DefinitionsCompatibilityBOTTOMThe counter reaches the BOTTOM when it becomes 0x0000.MAXThe counter reaches its MAXimum when it becomes 0xFFFF (decimal 65535).TOPThe counter reaches the TOP when it becomes equal to the highest value in thecount sequence.

The TOP value can be assigned to be one of the fixed values:0x00FF, 0x01FF, or 0x03FF, or to the value stored in the OCRnA or ICRnRegister. The assignment is dependent of the mode of 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:•PWMn0 is changed to WGMn0.•PWMn1 is changed to WGMn1.•CTCn is changed to WGMn2.The following registers are added to the 16-bit Timer/Counter:•Timer/Counter Control Register C (TCCRnC).•Output Compare Register C, OCRnCH and OCRnCL, combined OCRnC.The following bits are added to the 16-bit Timer/Counter Control Registers:•COM1C1:0 are added to TCCR1A.•FOCnA, FOCnB, and FOCnC are added in the new TCCRnC Register.•WGMn3 is added to TCCRnB.Interrupt flag and mask bits for output compare unit C are added.1112467M–AVR–11/04The 16-bit Timer/Counter has improvements that will affect the compatibility in somespecial cases.Accessing 16-bitRegistersThe TCNTn, OCRnA/B/C, and ICRn are 16-bit registers that can be accessed by theAVR CPU via the 8-bit data bus.

The 16-bit register must be byte accessed using tworead or write operations. Each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16-bit access. The same Temporary Register is sharedbetween all 16-bit registers within each 16-bit timer. Accessing the low byte triggers the16-bit read or write operation. When the low byte of a 16-bit register is written by theCPU, the high byte stored in the Temporary Register, and the low byte written are bothcopied into the 16-bit register in the same clock cycle. When the low byte of a 16-bit register is read by the CPU, the high byte of the 16-bit register is copied into the TemporaryRegister in the same clock cycle as the low byte is read.Not all 16-bit accesses uses the Temporary Register for the high byte.

Reading theOCRnA/B/C 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-bit read,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 OCRnA/B/C and ICRn Registers. Note that when using “C”,the compiler handles the 16-bit access.Assembly Code Examples(1)...; Set TCNTn to 0x01FFldi r17,0x01ldi r16,0xFFout TCNTnH,r17out TCNTnL,r16; Read TCNTn into r17:r16in r16,TCNTnLin r17,TCNTnH...C Code Examples(1)unsigned int i;.../* Set TCNTn to 0x01FF */TCNTn = 0x1FF;/* Read TCNTn into i */i = TCNTn;...Note:1. The example code assumes that the part specific header file is included.For I/O registers located in extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and“SBI” instructions must be replaced with instructions that allow access to extendedI/O. Typically “LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”.The assembly code example returns the TCNTn value in the r17:r16 register pair.112ATmega1282467M–AVR–11/04ATmega128It 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.The following code examples show how to do an atomic read of the TCNTn Registercontents.

Reading any of the OCRnA/B/C or ICRn Registers can be done by using thesame principle.Assembly Code Example(1)TIM16_ReadTCNTn:; Save global interrupt flagin r18,SREG; Disable interruptscli; Read TCNTn into r17:r16in r16,TCNTnLin r17,TCNTnH; Restore global interrupt flagout SREG,r18retC Code Example(1)unsigned int TIM16_ReadTCNTn( void ){unsigned char sreg;unsigned int i;/* Save global interrupt flag */sreg = SREG;/* Disable interrupts */__disable_interrupt();/* Read TCNTn into i */i = TCNTn;/* Restore global interrupt flag */SREG = sreg;return i;}Note:1.

The example code assumes that the part specific header file is included.For I/O registers located in extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and“SBI” instructions must be replaced with instructions that allow access to extendedI/O. Typically “LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”.The assembly code example returns the TCNTn value in the r17:r16 register pair.1132467M–AVR–11/04The following code examples show how to do an atomic write of the TCNTn Registercontents. Writing any of the OCRnA/B/C or ICRn Registers can be done by using thesame principle.Assembly Code Example(1)TIM16_WriteTCNTn:; Save global interrupt flagin r18,SREG; Disable interruptscli; Set TCNTn to r17:r16out TCNTnH,r17out TCNTnL,r16; Restore global interrupt flagout SREG,r18retC Code Example(1)void TIM16_WriteTCNTn( unsigned int i ){unsigned char sreg;unsigned int i;/* Save global interrupt flag */sreg = SREG;/* Disable interrupts */__disable_interrupt();/* Set TCNTn to i */TCNTn = i;/* Restore global interrupt flag */SREG = sreg;}Note:1.

The example code assumes that the part specific header file is included.For I/O registers located in extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and“SBI” instructions must be replaced with instructions that allow access to extendedI/O. Typically “LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”.The assembly code example requires that the r17:r16 register pair contains the value tobe written to TCNTn.Reusing the Temporary HighByte Register114If writing to more than one 16-bit register where the high byte is the same for all registerswritten, then the high byte only needs to be written once. However, note that the samerule of atomic operation described previously also applies in this case.ATmega1282467M–AVR–11/04ATmega128Timer/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(CSn2:0) bits located in the Timer/Counter Control Register B (TCCRnB). 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 16-bit Timer/Counter is the programmable 16-bit bi-directionalcounter unit. Figure 47 shows a block diagram of the counter and its surroundings.Figure 47.

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

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

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

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