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

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

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

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.

Even though most of the digital inputs are disabled in the deep sleep modes asdescribed above, floating inputs should be avoided to reduce current consumption in allother modes where the digital inputs are enabled (Reset, Active mode and Idle mode).The simplest method to ensure a defined level of an unused pin, is to enable the internalpull-up. In this case, the pull-up will be disabled during reset. If low power consumptionduring reset is important, it is recommended to use an external pull-up or pull-down.Connecting unused pins directly to VCC or GND is not recommended, since this maycause excessive currents if the pin is accidentally configured as an output.Alternate Port FunctionsMost port pins have alternate functions in addition to being general digital I/Os.

Figure33 shows how the port pin control signals from the simplified Figure 30 can be overridden by alternate functions. The overriding signals may not be present in all port pins, butthe figure serves as a generic description applicable to all port pins in the AVR microcontroller family.Figure 33. Alternate Port Functions(1)PUOExnPUOVxn1PUD0DDOExnDDOVxn1Q DDDxn0Q CLRWDxPVOExnRESET1PxnQ0DPORTxnQ CLRDIEOExnWPxDIEOVxnDATA BUSRDxPVOVxnRESET10RRxSLEEPSYNCHRONIZERDSETQRPxQDPINxnLCLRQCLRQclk I/ODIxnAIOxnPUOExn:PUOVxn:DDOExn:DDOVxn:PVOExn:PVOVxn:DIEOExn:DIEOVxn:SLEEP:Note:68Pxn PULL-UP OVERRIDE ENABLEPxn PULL-UP OVERRIDE VALUEPxn DATA DIRECTION OVERRIDE ENABLEPxn DATA DIRECTION OVERRIDE VALUEPxn PORT VALUE OVERRIDE ENABLEPxn PORT VALUE OVERRIDE VALUEPxn DIGITAL INPUT-ENABLE OVERRIDE ENABLEPxn DIGITAL INPUT-ENABLE OVERRIDE VALUESLEEP CONTROLPUD:WDx:RDx:RRx:WPx:RPx:clkI/O:DIxn:AIOxn:PULLUP DISABLEWRITE DDRxREAD DDRxREAD PORTx REGISTERWRITE PORTxREAD PORTx PINI/O CLOCKDIGITAL INPUT PIN n ON PORTxANALOG INPUT/OUTPUT PIN n ON PORTx1.

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

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

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

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