ATmega128 (961843), страница 13

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

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

When this bit is set (one), the interrupt vectors are moved to the beginning of the Boot Loader section of the flash. The actual address of the start of the BootFlash section is determined by the BOOTSZ fuses. Refer to the section “Boot LoaderSupport – Read-While-Write Self-Programming” on page 275 for details. To avoid unintentional changes of interrupt vector tables, a special write procedure must be followedto change the IVSEL bit:1. Write the Interrupt Vector Change Enable (IVCE) bit to one.2.

Within four cycles, write the desired value to IVSEL while writing a zero to IVCE.Interrupts will automatically be disabled while this sequence is executed. Interrupts aredisabled in the cycle IVCE is set, and they remain disabled until after the instructionfollowing the write to IVSEL. If IVSEL is not written, interrupts remain disabled for fourcycles. The I-bit in the Status Register is unaffected by the automatic disabling.Note:If interrupt vectors are placed in the Boot Loader section and Boot Lock bit BLB02 is programmed, interrupts are disabled while executing from the Application section.

If interruptvectors are placed in the Application section and Boot Lock bit BLB12 is programed,interrupts are disabled while executing from the Boot Loader section. Refer to the section“Boot Loader Support – Read-While-Write Self-Programming” on page 275 for details onBoot Lock bits.612467M–AVR–11/04• Bit 0 – IVCE: Interrupt Vector Change EnableThe IVCE bit must be written to logic one to enable change of the IVSEL bit.

IVCE iscleared by hardware four cycles after it is written or when IVSEL is written. Setting theIVCE bit will disable interrupts, as explained in the IVSEL description above. See CodeExample below.Assembly Code ExampleMove_interrupts:; Enable change of interrupt vectorsldi r16, (1<<IVCE)out MCUCR, r16; Move interrupts to boot flash sectionldi r16, (1<<IVSEL)out MCUCR, r16retC Code Examplevoid Move_interrupts(void){/* Enable change of interrupt vectors */MCUCR = (1<<IVCE);/* Move interrupts to boot flash section */MCUCR = (1<<IVSEL);}62ATmega1282467M–AVR–11/04ATmega128I/O PortsIntroductionAll AVR ports have true Read-Modify-Write functionality when used as general digitalI/O ports. This means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the SBI and CBI instructions.

Thesame applies when changing drive value (if configured as output) or enabling/disablingof pull-up resistors (if configured as input). Each output buffer has symmetrical drivecharacteristics with both high sink and source capability. The pin driver is strong enoughto drive LED displays directly. All port pins have individually selectable pull-up resistorswith a supply-voltage invariant resistance. All I/O pins have protection diodes to bothVCC and Ground as indicated in Figure 29.

Refer to “Electrical Characteristics” on page321 for a complete list of parameters.Figure 29. I/O Pin Equivalent SchematicRPULogicPxnCPINSee Figure"General Digital I/O" forDetailsAll registers and bit references in this section are written in general form. A lower case“x” represents the numbering letter for the port, and a lower case “n” represents the bitnumber.

However, when using the register or bit defines in a program, the precise formmust be used. For example, PORTB3 for bit no. 3 in Port B, here documented generallyas PORTxn. The physical I/O registers and bit locations are listed in “Register Description for I/O Ports” on page 84.Three I/O memory address locations are allocated for each port, one each for the DataRegister – PORTx, Data Direction Register – DDRx, and the Port Input Pins – PINx. ThePort Input Pins I/O location is read only, while the Data Register and the Data DirectionRegister are read/write. In addition, the Pull-up Disable – PUD bit in SFIOR disables thepull-up function for all pins in all ports when set.Using the I/O port as General Digital I/O is described in “Ports as General Digital I/O” onpage 64.

Most port pins are multiplexed with alternate functions for the peripheral features on the device. How each alternate function interferes with the port pin is describedin “Alternate Port Functions” on page 68. Refer to the individual module sections for afull description of the alternate functions.Note that enabling the alternate function of some of the port pins does not affect the useof the other pins in the port as General Digital I/O.632467M–AVR–11/04Ports as General DigitalI/OThe ports are bi-directional I/O ports with optional internal pull-ups. Figure 30 shows afunctional description of one I/O port pin, here generically called Pxn.Figure 30. General Digital I/O(1)PUDQDDDxnQ CLRWDxRESETQPxnDPORTxnQ CLRWPxDATA BUSRDxRESETRRxSLEEPSYNCHRONIZERDQLQDRPxQPINxnQclk I/OPUD:SLEEP:clkI/O:Note:Configuring the PinPULLUP DISABLESLEEP CONTROLI/O CLOCKWDx:RDx:WPx:RRx:RPx:WRITE DDRxREAD DDRxWRITE PORTxREAD PORTx REGISTERREAD PORTx PIN1.

WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O,SLEEP, and PUD are common to all ports.Each port pin consists of three Register bits: DDxn, PORTxn, and PINxn. As shown in“Register Description for I/O Ports” on page 84, the DDxn bits are accessed at the DDRxI/O address, the PORTxn bits at the PORTx I/O address, and the PINxn bits at the PINxI/O address.The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is writtenlogic one, Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input pin.If PORTxn is written logic one when the pin is configured as an input pin, the pull-upresistor is activated.

To switch the pull-up resistor off, PORTxn has to be written logiczero or the pin has to be configured as an output pin. The port pins are tri-stated when aReset condition becomes active, even if no clocks are running.If PORTxn is written logic one when the pin is configured as an output pin, the port pin isdriven high (one). If PORTxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero).64ATmega1282467M–AVR–11/04ATmega128When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn,PORTxn} = 0b11), an intermediate state with either pull-up enabled ({DDxn, PORTxn} =0b01) or output low ({DDxn, PORTxn} = 0b10) must occur. Normally, the pull-upenabled state is fully acceptable, as a high-impedant environment will not notice the difference between a strong high driver and a pull-up.

If this is not the case, the PUD bit inthe SFIOR Register can be written to one to disable all pull-ups in all ports.Switching between input with pull-up and output low generates the same problem. Theuser must use either the tri-state ({DDxn, PORTxn} = 0b00) or the output high state({DDxn, PORTxn} = 0b11) as an intermediate step.Table 25 summarizes the control signals for the pin value.Table 25. Port Pin ConfigurationsReading the Pin ValueDDxnPORTxnPUD(in SFIOR)I/OPull-up00XInputNoTri-state (Hi-Z)010InputYesPxn will source current if ext.

pulledlow.011InputNoTri-state (Hi-Z)10XOutputNoOutput Low (Sink)11XOutputNoOutput High (Source)CommentIndependent of the setting of Data Direction bit DDxn, the port pin can be read throughthe PINxn Register bit. As shown in Figure 30, the PINxn Register bit and the precedinglatch constitute a synchronizer. This is needed to avoid metastability if the physical pinchanges value near the edge of the internal clock, but it also introduces a delay. Figure31 shows a timing diagram of the synchronization when reading an externally appliedpin value.

The maximum and minimum propagation delays are denoted tpd,max and tpd,minrespectively.Figure 31. Synchronization when Reading an Externally Applied Pin ValueSYSTEM CLKINSTRUCTIONSXXXXXXin r17, PINxSYNC LATCHPINxnr170x000xFFtpd, maxtpd, min652467M–AVR–11/04Consider the clock period starting shortly after the first falling edge of the system clock.The latch is closed when the clock is low, and goes transparent when the clock is high,as indicated by the shaded region of the “SYNC LATCH” signal. The signal value islatched when the system clock goes low.

It is clocked into the PINxn Register at the succeeding positive clock edge. As indicated by the two arrows tpd,max and tpd,min, a singlesignal transition on the pin will be delayed between ½ and 1½ system clock perioddepending upon the time of assertion.When reading back a software assigned pin value, a nop instruction must be inserted asindicated in Figure 32. The out instruction sets the “SYNC LATCH” signal at the positiveedge of the clock. In this case, the delay tpd through the synchronizer is one systemclock period.Figure 32. Synchronization when Reading a Software Assigned Pin ValueSYSTEM CLKr16INSTRUCTIONS0xFFout PORTx, r16nopin r17, PINxSYNC LATCHPINxnr170x000xFFtpd66ATmega1282467M–AVR–11/04ATmega128The following code example shows how to set port B pins 0 and 1 high, 2 and 3 low, anddefine the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7.

Theresulting pin values are read back again, but as previously discussed, a nop instructionis included to be able to read back the value recently assigned to some of the pins.Assembly Code Example(1)...; Define pull-ups and set outputs high; Define directions for port pinsldir16,(1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0)ldir17,(1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0)outPORTB,r16outDDRB,r17; Insert nop for synchronizationnop; Read port pinsinr16,PINB...C Code Example(1)unsigned char i;.../* Define pull-ups and set outputs high *//* Define directions for port pins */PORTB = (1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0);DDRB = (1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0);/* Insert nop for synchronization*/__no_operation();/* Read port pins */i = PINB;...Note:Digital Input Enable and SleepModes1. For the assembly program, two temporary registers are used to minimize the timefrom pull-ups are set on pins 0, 1, 6, and 7, until the direction bits are correctly set,defining bit 2 and 3 as low and redefining bits 0 and 1 as strong high drivers.As shown in Figure 30, the digital input signal can be clamped to ground at the input ofthe schmitt-trigger.

The signal denoted SLEEP in the figure, is set by the MCU SleepController in Power-down mode, Power-save mode, Standby mode, and ExtendedStandby mode to avoid high power consumption if some input signals are left floating, orhave an analog signal level close to VCC/2.SLEEP is overridden for port pins enabled as External Interrupt pins.

If the ExternalInterrupt Request is not enabled, SLEEP is active also for these pins. SLEEP is alsooverridden by various other alternate functions as described in “Alternate Port Functions” on page 68.If a logic high level (“one”) is present on an Asynchronous External Interrupt pin configured as “Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin” while theexternal interrupt is not enabled, the corresponding External Interrupt Flag will be setwhen resuming from the above mentioned sleep modes, as the clamping in these sleepmodes produces the requested logic change.672467M–AVR–11/04Unconnected pinsIf some pins are unused, it is recommended to ensure that these pins have a definedlevel.

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

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

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

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