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

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

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

However, the functionality and location of these bits are compatible with previousversions of the timer.• Bit 5:4 – COM21:0: Compare Match Output ModeThese bits control the Output Compare Pin (OC2) behavior. If one or both of theCOM21:0 bits are set, the OC2 output overrides the normal port functionality of the I/Opin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding to the OC2 pin must be set in order to enable the output driver.When OC2 is connected to the pin, the function of the COM21:0 bits depends on theWGM21:0 bit setting.

Table 65 shows the COM21:0 bit functionality when the WGM21:0bits are set to a normal or CTC mode (non-PWM).156ATmega1282467M–AVR–11/04ATmega128Table 65. Compare Output Mode, Non-PWM ModeCOM21COM20Description00Normal port operation, OC2 disconnected.01Toggle OC2 on compare match10Clear OC2 on compare match11Set OC2 on compare matchTable 66 shows the COM21:0 bit functionality when the WGM21:0 bits are set to fastPWM mode.Table 66. Compare Output Mode, Fast PWM Mode(1)COM21COM2000Normal port operation, OC2 disconnected.01Reserved10Clear OC2 on compare match, set OC2 at TOP11Set OC2 on compare match, clear OC2 at TOPNote:Description1.

A special case occurs when OCR2 equals TOP and COM21 is set. In this case, thecompare match is ignored, but the set or clear is done at TOP. See “Fast PWM Mode”on page 150 for more details.Table 67 shows the COM21:0 bit functionality when the WGM21:0 bits are set to phasecorrect PWM mode.Table 67. Compare Output Mode, Phase Correct PWM Mode(1)COM21COM2000Normal port operation, OC2 disconnected.01Reserved10Clear OC2 on compare match when up-counting.

Set OC2 on comparematch when downcounting.11Set OC2 on compare match when up-counting. Clear OC2 on comparematch when downcounting.Note:Description1. A special case occurs when OCR2 equals TOP and COM21 is set. In this case, thecompare match is ignored, but the set or clear is done at TOP. See “Phase CorrectPWM Mode” on page 152 for more details.• Bit 2:0 – CS22:0: Clock SelectThe three clock select bits select the clock source to be used by the Timer/Counter.Table 68.

Clock Select Bit DescriptionCS22CS21CS20Description000No clock source (Timer/Counter stopped)001clkI/O/(No prescaling)010clkI/O/8 (From prescaler)011clkI/O/64 (From prescaler)100clkI/O/256 (From prescaler)1572467M–AVR–11/04Table 68. Clock Select Bit DescriptionCS22CS21CS20Description101clkI/O/1024 (From prescaler)110External clock source on T2 pin. Clock on falling edge111External clock source on T2 pin. Clock on rising edgeIf external pin modes are used for the Timer/Counter2, transitions on the T2 pin willclock the counter even if the pin is configured as an output.

This feature allows softwarecontrol of the counting.Timer/Counter Register –TCNT2Bit76543210TCNT2[7:0]TCNT2Read/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. Writing to the TCNT2 Register blocks (removes)the compare match on the following timer clock. Modifying the counter (TCNT2) whilethe counter is running, introduces a risk of missing a compare match between TCNT2and the OCR2 Register.Output Compare Register –OCR2Bit76543210OCR2[7:0]OCR2Read/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 (TCNT2).

A match can be used to generate an output compareinterrupt, or to generate a waveform output on the OC2 pin.Timer/Counter Interrupt MaskRegister – TIMSKBit76543210OCIE2TOIE2TICIE1OCIE1AOCIE1BTOIE1OCIE0TOIE0Read/WriteR/WR/WR/WR/WR/WR/WR/WR/WInitial Value00000000TIMSK• Bit 7 – OCIE2: Timer/Counter2 Output Compare Match Interrupt EnableWhen the OCIE2 bit is written to one, and the I-bit in the Status Register is set (one), theTimer/Counter2 Compare Match interrupt is enabled. The corresponding interrupt isexecuted if a compare match in Timer/Counter2 occurs, i.e., when the OCF2 bit is set inthe Timer/Counter Interrupt Flag Register – TIFR.• Bit 6 – TOIE2: Timer/Counter2 Overflow Interrupt EnableWhen the TOIE2 bit is written to one, and the I-bit in the Status Register is set (one), theTimer/Counter2 Overflow interrupt is enabled. The corresponding interrupt is executed ifan overflow in Timer/Counter2 occurs, i.e., when the TOV2 bit is set in theTimer/Counter Interrupt Flag Register – TIFR.Timer/Counter Interrupt FlagRegister – TIFR158Bit76543210OCF2TOV2ICF1OCF1AOCF1BTOV1OCF0TOV0TIFRATmega1282467M–AVR–11/04ATmega128Read/WriteR/WR/WR/WR/WR/WR/WR/WR/WInitial Value00000000• Bit 7 – OCF2: Output Compare Flag 2The OCF2 bit is set (one) when a compare match occurs between the Timer/Counter2and the data in OCR2 – Output Compare Register2.

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

TOV2 is clearedby hardware when executing the corresponding interrupt handling vector. Alternatively,TOV2 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE2(Timer/Counter2 Overflow Interrupt Enable), and TOV2 are set (one), theTimer/Counter2 Overflow interrupt is executed. In PWM mode, this bit is set whenTimer/Counter2 changes counting direction at $00.1592467M–AVR–11/04Output CompareModulator (OCM1C2)OverviewThe Output Compare Modulator (OCM) allows generation of waveforms modulated witha carrier frequency. The modulator uses the outputs from the Output Compare Unit C ofthe 16-bit Timer/Counter1 and the Output Compare Unit of the 8-bit Timer/Counter2. Formore details about these Timer/Counters see “16-bit Timer/Counter (Timer/Counter1and Timer/Counter3)” on page 109 and “8-bit Timer/Counter2 with PWM” on page 144.Note that this feature is not available in ATmega103 compatibility mode.Figure 72.

Output Compare Modulator, Block DiagramTimer/Counter 1OC1CPinTimer/Counter 2OC1C /OC2 / PB7OC2When the modulator is enabled, the two output compare channels are modulatedtogether as shown in the block diagram (Figure 72).DescriptionThe Output Compare unit 1C and Output Compare unit 2 shares the PB7 port pin foroutput. The outputs of the Output Compare units (OC1C and OC2) overrides the normalPORTB7 Register when one of them is enabled (i.e., when COMnx1:0 is not equal tozero). When both OC1C and OC2 are enabled at the same time, the modulator is automatically enabled.The functional equivalent schematic of the modulator is shown on Figure 73. The schematic includes part of the Timer/Counter units and the port B pin 7 output driver circuit.Figure 73.

Output Compare Modulator, SchematicCOM21COM20VccCOM1C1COM1C0( From Waveform Generator )Modulator0D1Q1OC1CPin0( From Waveform Generator )DQOC1C /OC2 / PB7OC2DQDPORTB7QDDRB7DATABUS160ATmega1282467M–AVR–11/04ATmega128When the modulator is enabled the type of modulation (logical AND or OR) can beselected by the PORTB7 Register.

Note that the DDRB7 controls the direction of theport independent of the COMnx1:0 bit setting.Timing ExampleFigure 74 illustrates the modulator in action. In this example the Timer/Counter1 is set tooperate in fast PWM mode (non-inverted) and Timer/Counter2 uses CTC waveformmode with toggle Compare Output mode (COMnx1:0 = 1).Figure 74. Output Compare Modulator, Timing Diagramclk I/OOC1C(FPWM Mode)OC2(CTC Mode)PB7(PORTB7 = 0)PB7(PORTB7 = 1)(Period)123In this example, Timer/Counter2 provides the carrier, while the modulating signal is generated by the Output Compare unit C of the Timer/Counter1.The resolution of the PWM signal (OC1C) is reduced by the modulation.

The reductionfactor is equal to the number of system clock cycles of one period of the carrier (OC2).In this example the resolution is reduced by a factor of two. The reason for the reductionis illustrated in Figure 74 at the second and third period of the PB7 output whenPORTB7 equals zero. The period 2 high time is one cycle longer than the period 3 hightime, but the result on the PB7 output is equal in both periods.1612467M–AVR–11/04Serial PeripheralInterface – SPIThe Serial Peripheral Interface (SPI) allows high-speed synchronous data transferbetween the ATmega128 and peripheral devices or between several AVR devices. TheATmega128 SPI includes the following features:• Full-duplex, Three-wire Synchronous Data Transfer• Master or Slave Operation• LSB First or MSB First Data Transfer• Seven Programmable Bit Rates• End of Transmission Interrupt Flag• Write Collision Flag Protection• Wake-up from Idle Mode• Double Speed (CK/2) Master SPI ModeFigure 75.

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

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

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

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