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

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

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

Note that when using fixed TOP values, the unused bits aremasked to zero when any of the OCR1x Registers are written. As the third period shownin Figure 39 illustrates, changing the TOP actively while the Timer/Counter is running inthe Phase Correct mode can result in an unsymmetrical output. The reason for this canbe found in the time of update of the OCR1x Register. Since the OCR1x update occursat TOP, the PWM period starts and ends at TOP. This implies that the length of the falling slope is determined by the previous TOP value, while the length of the rising slope isdetermined by the new TOP value.

When these two values differ the two slopes of the90ATmega8(L)2486O–AVR–10/04ATmega8(L)period will differ in length. The difference in length gives the unsymmetrical result on theoutput.It is recommended to use the Phase and Frequency Correct mode instead of the PhaseCorrect mode when changing the TOP value while the Timer/Counter is running. Whenusing a static TOP value there are practically no differences between the two modes ofoperation.In phase correct PWM mode, the compare units allow generation of PWM waveforms onthe OC1x pins.

Setting the COM1x1:0 bits to 2 will produce a non-inverted PWM and aninverted PWM output can be generated by setting the COM1x1:0 to 3. See Table 38 onpage 96. The actual OC1x value will only be visible on the port pin if the data directionfor the port pin is set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x Register at the Compare Match between OCR1x and TCNT1when the counter increments, and clearing (or setting) the OC1x Register at CompareMatch between OCR1x and TCNT1 when the counter decrements.

The PWM frequencyfor the output when using phase correct PWM can be calculated by the followingequation:f clk_I/Of OCnxPCPWM = --------------------------2 ⋅ N ⋅ TOPThe N variable represents the prescaler divider (1, 8, 64, 256, or 1024).The extreme values for the OCR1x Register represent special cases when generating aPWM waveform output in the phase correct PWM mode. If the OCR1x is set equal toBOTTOM the output will be continuously low and if set equal to TOP the output will becontinuously high for non-inverted PWM mode.

For inverted PWM the output will havethe opposite logic values.If OCR1A is used to define the TOP value (WMG13:0 = 11) and COM1A1:0 = 1, theOC1A output will toggle with a 50% duty cycle.Phase and Frequency CorrectPWM ModeThe phase and frequency correct Pulse Width Modulation, or phase and frequency correct PWM mode (WGM13:0 = 8 or 9) provides a high resolution phase and frequencycorrect PWM waveform generation option. The phase and frequency correct PWMmode is, like the phase correct PWM mode, based on a dual-slope operation. Thecounter counts repeatedly from BOTTOM (0x0000) to TOP and then from TOP to BOTTOM.

In non-inverting Compare Output mode, the Output Compare (OC1x) is clearedon the Compare Match between TCNT1 and OCR1x while upcounting, and set on theCompare Match while downcounting. In inverting Compare Output mode, the operationis inverted. The dual-slope operation gives a lower maximum operation frequency compared to the single-slope operation. However, due to the symmetric feature of the dualslope PWM modes, these modes are preferred for motor control applications.The main difference between the phase correct, and the phase and frequency correctPWM mode is the time the OCR1x Register is updated by the OCR1x Buffer Register,(see Figure 39 and Figure 40).The PWM resolution for the phase and frequency correct PWM mode can be defined byeither ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to0x0003), and the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX).

The PWMresolution in bits can be calculated using the following equation:log ( TOP + 1 )R PFCPWM = ----------------------------------log ( 2 )In phase and frequency correct PWM mode the counter is incremented until the countervalue matches either the value in ICR1 (WGM13:0 = 8), or the value in OCR1A912486O–AVR–10/04(WGM13:0 = 9). The counter has then reached the TOP and changes the countdirection. The TCNT1 value will be equal to TOP for one timer clock cycle. The timingdiagram for the phase correct and frequency correct PWM mode is shown on Figure 40.The figure shows phase and frequency correct PWM mode when OCR1A or ICR1 isused to define TOP.

The TCNT1 value is in the timing diagram shown as a histogram forillustrating the dual-slope operation. The diagram includes non-inverted and invertedPWM outputs. The small horizontal line marks on the TCNT1 slopes represent comparematches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set when aCompare Match occurs.Figure 40. Phase and Frequency Correct PWM Mode, Timing DiagramOCnA Interrupt Flag Set orICFn Interrupt Flag Set(Interrupt on TOP)OCRnx / TOP Update andTOVn Interrupt Flag Set(Interrupt on Bottom)TCNTnOCnx(COMnx1:0 = 2)OCnx(COMnx1:0 = 3)Period1234The Timer/Counter Overflow Flag (TOV1) is set at the same timer clock cycle as theOCR1x Registers are updated with the double buffer value (at BOTTOM).

When eitherOCR1A or ICR1 is used for defining the TOP value, the OC1A or ICF1 Flag set whenTCNT1 has reached TOP. The Interrupt Flags can then be used to generate an interrupteach time the counter reaches the TOP or BOTTOM value.When changing the TOP value the program must ensure that the new TOP value ishigher or equal to the value of all of the Compare Registers. If the TOP value is lowerthan any of the Compare Registers, a Compare Match will never occur between theTCNT1 and the OCR1x.As Figure 40 shows the output generated is, in contrast to the Phase Correct mode,symmetrical in all periods.

Since the OCR1x Registers are updated at BOTTOM, thelength of the rising and the falling slopes will always be equal. This gives symmetricaloutput pulses and is therefore frequency correct.Using the ICR1 Register for defining TOP works well when using fixed TOP values. Byusing ICR1, the OCR1A Register is free to be used for generating a PWM output onOC1A. However, if the base PWM frequency is actively changed by changing the TOPvalue, using the OCR1A as TOP is clearly a better choice due to its double bufferfeature.In phase and frequency correct PWM mode, the compare units allow generation ofPWM waveforms on the OC1x pins. Setting the COM1x1:0 bits to 2 will produce a noninverted PWM and an inverted PWM output can be generated by setting the COM1x1:092ATmega8(L)2486O–AVR–10/04ATmega8(L)to 3.

See Table 38 on page 96. The actual OC1x value will only be visible on the port pinif the data direction for the port pin is set as output (DDR_OC1x). The PWM waveform isgenerated by setting (or clearing) the OC1x Register at the Compare Match betweenOCR1x and TCNT1 when the counter increments, and clearing (or setting) the OC1xRegister at Compare Match between OCR1x and TCNT1 when the counter decrements.The PWM frequency for the output when using phase and frequency correct PWM canbe calculated by the following equation:f clk_I/Of OCnxPFCPWM = --------------------------2 ⋅ N ⋅ TOPThe N variable represents the prescaler divider (1, 8, 64, 256, or 1024).The extreme values for the OCR1x Register represents special cases when generatinga PWM waveform output in the phase correct PWM mode.

If the OCR1x is set equal toBOTTOM the output will be continuously low and if set equal to TOP the output will beset to high for non-inverted PWM mode. For inverted PWM the output will have theopposite logic values.If OCR1A is used to define the TOP value (WGM13:0 = 9) and COM1A1:0 = 1, theOC1A output will toggle with a 50% duty cycle.Timer/Counter TimingDiagramsThe Timer/Counter is a synchronous design and the timer clock (clkT1) is thereforeshown as a clock enable signal in the following figures. The figures include informationon when Interrupt Flags are set, and when the OCR1x Register is updated with theOCR1x buffer value (only for modes utilizing double buffering).

Figure 41 shows a timingdiagram for the setting of OCF1x.Figure 41. Timer/Counter Timing Diagram, Setting of OCF1x, no PrescalingclkI/OclkTn(clkI/O /1)TCNTnOCRnxOCRnx - 1OCRnxOCRnx + 1OCRnx + 2OCRnx ValueOCFnxFigure 42 shows the same timing data, but with the prescaler enabled.932486O–AVR–10/04Figure 42. Timer/Counter Timing Diagram, Setting of OCF1x, with Prescaler (fclk_I/O/8)clkI/OclkTn(clkI/O /8)TCNTnOCRnx - 1OCRnxOCRnxOCRnx + 1OCRnx + 2OCRnx ValueOCFnxFigure 43 shows the count sequence close to TOP in various modes. When using phaseand frequency correct PWM mode the OCR1x Register is updated at BOTTOM.

Thetiming diagrams will be the same, but TOP should be replaced by BOTTOM, TOP-1 byBOTTOM+1 and so on. The same renaming applies for modes that set the TOV1 Flagat BOTTOM.Figure 43. Timer/Counter Timing Diagram, no PrescalingclkI/OclkTn(clkI/O /1)TCNTn(CTC and FPWM)TCNTn(PC and PFC PWM)TOP - 1TOPBOTTOMBOTTOM + 1TOP - 1TOPTOP - 1TOP - 2TOVn (FPWM)and ICFn (if usedas TOP)OCRnx(Update at TOP)Old OCRnx ValueNew OCRnx ValueFigure 44 shows the same timing data, but with the prescaler enabled.94ATmega8(L)2486O–AVR–10/04ATmega8(L)Figure 44.

Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)clkI/OclkTn(clkI/O /8)TCNTn(CTC and FPWM)TCNTn(PC and PFC PWM)TOP - 1TOPBOTTOMBOTTOM + 1TOP - 1TOPTOP - 1TOP - 2TOVn (FPWM)and ICFn (if usedas TOP)OCRnxOld OCRnx Value(Update at TOP)New OCRnx Value16-bit Timer/CounterRegister DescriptionTimer/Counter 1 ControlRegister A – TCCR1ABit76543210COM1A1COM1A0COM1B1COM1B0FOC1AFOC1BWGM11WGM10Read/WriteR/WR/WR/WR/WWWR/WR/WInitial Value00000000TCCR1A• Bit 7:6 – COM1A1:0: Compare Output Mode for channel A• Bit 5:4 – COM1B1:0: Compare Output Mode for channel BThe COM1A1:0 and COM1B1:0 control the Output Compare Pins (OC1A and OC1Brespectively) behavior. If one or both of the COM1A1:0 bits are written to one, the OC1Aoutput overrides the normal port functionality of the I/O pin it is connected to.

If one orboth of the COM1B1:0 bit are written to one, the OC1B output overrides the normal portfunctionality of the I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding to the OC1A or OC1B pin must be set in order to enablethe output driver.When the OC1A or OC1B is connected to the pin, the function of the COM1x1:0 bits isdependent of the WGM13:0 bits setting.

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

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

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

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