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

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

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

The TWEA bit must be written to oneto enable the acknowledgement of the device’s own slave address or the general calladdress. TWSTA and TWSTO must be written to zero.When TWAR and TWCR have been initialized, the TWI waits until it is addressed by itsown slave address (or the general call address if enabled) followed by the data directionbit. If the direction bit is “1” (read), the TWI will operate in ST mode, otherwise SR modeis entered.

After its own slave address and the write bit have been received, the TWINTFlag is set and a valid status code can be read from TWSR. The status code is used todetermine the appropriate software action. The appropriate action to be taken for eachstatus code is detailed in Table 69. The Slave Transmitter mode may also be entered ifarbitration is lost while the TWI is in the Master mode (see state 0xB0).If the TWEA bit is written to zero during a transfer, the TWI will transmit the last byte ofthe transfer. State 0xC0 or state 0xC8 will be entered, depending on whether the MasterReceiver transmits a NACK or ACK after the final byte.

The TWI is switched to the notaddressed Slave mode, and will ignore the Master if it continues the transfer. Thus theMaster Receiver receives all “1” as serial data. State 0xC8 is entered if the Masterdemands additional data bytes (by transmitting ACK), even though the Slave has transmitted the last byte (TWEA zero and expecting NACK from the Master).While TWEA is zero, the TWI does not respond to its own slave address. However, theTwo-wire Serial Bus is still monitored and address recognition may resume at any timeby setting TWEA. This implies that the TWEA bit may be used to temporarily isolate theTWI from the Two-wire Serial Bus.1852486O–AVR–10/04In all sleep modes other than Idle mode, the clock system to the TWI is turned off.

If theTWEA bit is set, the interface can still acknowledge its own slave address or the generalcall address by using the Two-wire Serial Bus clock as a clock source. The part will thenwake up from sleep and the TWI will hold the SCL clock will low during the wake up anduntil the TWINT Flag is cleared (by writing it to one). Further data transmission will becarried out as normal, with the AVR clocks running as normal. Observe that if the AVR isset up with a long start-up time, the SCL line may be held low for a long time, blockingother data transmissions.Note that the Two-wire Serial Interface Data Register – TWDR does not reflect the lastbyte present on the bus when waking up from these sleep modes.Table 69. Status Codes for Slave Transmitter ModeStatus Code(TWSR)Prescaler Bitsare 00xA80xB00xB80xC00xC8186Application Software ResponseStatus of the Two-wire Serial Busand Two-wire Serial InterfaceHardwareTo TWCRTo/from TWDRSTASTOTWINTTWEALoad data byte orX010Load data byteX011Arbitration lost in SLA+R/W asMaster; own SLA+R has beenreceived; ACK has been returnedLoad data byte orX010Load data byteX011Data byte in TWDR has beentransmitted; ACK has beenreceivedLoad data byte orX010Load data byteX011Data byte in TWDR has beentransmitted; NOT ACK has beenreceivedNo TWDR action or0010No TWDR action or0011No TWDR action or1010No TWDR action1011No TWDR action or0010No TWDR action or0011No TWDR action or1010No TWDR action1011Own SLA+R has been received;ACK has been returnedLast data byte in TWDR has beentransmitted (TWEA = “0”); ACKhas been receivedNext Action Taken by TWI HardwareLast data byte will be transmitted and NOT ACK shouldbe receivedData byte will be transmitted and ACK should be receivedLast data byte will be transmitted and NOT ACK shouldbe receivedData byte will be transmitted and ACK should be receivedLast data byte will be transmitted and NOT ACK shouldbe receivedData byte will be transmitted and ACK should be receivedSwitched to the not addressed Slave mode;no recognition of own SLA or GCASwitched to the not addressed Slave mode;own SLA will be recognized;GCA will be recognized if TWGCE = “1”Switched to the not addressed Slave mode;no recognition of own SLA or GCA;a START condition will be transmitted when the busbecomes freeSwitched to the not addressed Slave mode;own SLA will be recognized;GCA will be recognized if TWGCE = “1”;a START condition will be transmitted when the busbecomes freeSwitched to the not addressed Slave mode;no recognition of own SLA or GCASwitched to the not addressed Slave mode;own SLA will be recognized;GCA will be recognized if TWGCE = “1”Switched to the not addressed Slave mode;no recognition of own SLA or GCA;a START condition will be transmitted when the busbecomes freeSwitched to the not addressed Slave mode;own SLA will be recognized;GCA will be recognized if TWGCE = “1”;a START condition will be transmitted when the busbecomes freeATmega8(L)2486O–AVR–10/04ATmega8(L)Figure 85.

Formats and States in the Slave Transmitter ModeReception of the ownslave address and one ormore data bytesSSLARADATA$A8Arbitration lost as masterand addressed as slaveADATA$B8AP or S$C0A$B0Last data byte transmitted.Switched to not addressedslave (TWEA = '0')AAll 1'sP or S$C8DATAFrom master to slaveFrom slave to masterMiscellaneous StatesAAny number of data bytesand their associated acknowledge bitsThis number (contained in TWSR) correspondsto a defined state of the Two-Wire Serial Bus. Theprescaler bits are zero or masked to zeronThere are two status codes that do not correspond to a defined TWI state, see Table 70.Status 0xF8 indicates that no relevant information is available because the TWINT Flagis not set.

This occurs between other states, and when the TWI is not involved in a serialtransfer.Status 0x00 indicates that a bus error has occurred during a Two-wire Serial Bus transfer. A bus error occurs when a START or STOP condition occurs at an illegal position inthe format frame. Examples of such illegal positions are during the serial transfer of anaddress byte, a data byte, or an acknowledge bit. When a bus error occurs, TWINT isset. To recover from a bus error, the TWSTO Flag must set and TWINT must be clearedby writing a logic one to it. This causes the TWI to enter the not addressed Slave modeand to clear the TWSTO Flag (no other bits in TWCR are affected).

The SDA and SCLlines are released, and no STOP condition is transmitted.Table 70. Miscellaneous StatesStatus Code(TWSR)Prescaler Bitsare 0Application Software ResponseStatus of the Two-wire SerialBus and Two-wire Serial Interface HardwareTo TWCRTo/from TWDR0xF8No relevant state informationavailable; TWINT = “0”No TWDR action0x00Bus error due to an illegalSTART or STOP conditionNo TWDR actionSTASTOTWINTTWEANo TWCR action011Next Action Taken by TWI HardwareWait or proceed current transferXOnly the internal hardware is affected, no STOP condition is sent on the bus.

In all cases, the bus is releasedand TWSTO is cleared.1872486O–AVR–10/04Combining Several TWIModesIn some cases, several TWI modes must be combined in order to complete the desiredaction. Consider for example reading data from a serial EEPROM. Typically, such atransfer involves the following steps:1. The transfer must be initiated.2.

The EEPROM must be instructed what location should be read.3. The reading must be performed.4. The transfer must be finished.Note that data is transmitted both from Master to Slave and vice versa. The Master mustinstruct the Slave what location it wants to read, requiring the use of the MT mode. Subsequently, data must be read from the Slave, implying the use of the MR mode. Thus,the transfer direction must be changed. The Master must keep control of the bus duringall these steps, and the steps should be carried out as an atomical operation.

If this principle is violated in a multimaster system, another Master can alter the data pointer in theEEPROM between steps 2 and 3, and the Master will read the wrong data location.Such a change in transfer direction is accomplished by transmitting a REPEATEDSTART between the transmission of the address byte and reception of the data. After aREPEATED START, the Master keeps ownership of the bus. The following figure showsthe flow in this transfer.Figure 86. Combining Several TWI Modes to Access a Serial EEPROMMaster TransmitterSSLA+WAADDRESSS = STARTARsSLA+RADATARs = REPEATED STARTTransmitted from master to slaveMulti-master Systemsand ArbitrationMaster ReceiverAPP = STOPTransmitted from slave to masterIf multiple masters are connected to the same bus, transmissions may be initiated simultaneously by one or more of them.

The TWI standard ensures that such situations arehandled in such a way that one of the masters will be allowed to proceed with the transfer, and that no data will be lost in the process. An example of an arbitration situation isdepicted below, where two masters are trying to transmit data to a Slave Receiver.Figure 87. An Arbitration ExampleVCCDevice 1Device 2Device 3MASTERTRANSMITTERMASTERTRANSMITTERSLAVERECEIVER........Device nR1R2SDASCLSeveral different scenarios may arise during arbitration, as described below:188ATmega8(L)2486O–AVR–10/04ATmega8(L)•Two or more masters are performing identical communication with the same Slave.In this case, neither the Slave nor any of the masters will know about the buscontention.•Two or more masters are accessing the same Slave with different data or directionbit.

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

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

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

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