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

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

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

Formats and States in the Slave Receiver ModeReception of theown slave addressand one or moredata bytes. All areacknowledgedSSLAWADATA$60ADATA$80Last data byte receivedis not acknowledgedAP or S$80$A0AP or S$88Arbitration lost as masterand addressed as slaveA$68Reception of the general calladdress and one or more databytesGeneral CallADATA$70ADATA$90Last data byte received isnot acknowledgedAP or S$90$A0AP or S$98Arbitration lost as master andaddressed as slave by general callA$78DATAFrom master to slaveFrom slave to masterSlave Transmitter ModeAnAny 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 zeroIn the Slave Transmitter mode, a number of data bytes are transmitted to a masterreceiver (see Figure 102). All the status codes mentioned in this section assume that theprescaler bits are zero or are masked to zero.Figure 102. Data Transfer in Slave Transmitter ModeVCCDevice 1Device 2SLAVETRANSMITTERMASTERRECEIVERDevice 3........Device nR1R2SDASCLTo initiate the Slave Transmitter mode, TWAR and TWCR must be initialized as follows:222ATmega1282467M–AVR–11/04ATmega128TWARTWA6TWA5valueTWA4TWA3TWA2TWA1TWA0TWGCEDevice’s Own Slave AddressThe upper seven bits are the address to which the Two-wire Serial Interface will respondwhen addressed by a master.

If the LSB is set, the TWI will respond to the general calladdress ($00), otherwise it will ignore the general call address.TWCRvalueTWINTTWEATWSTATWSTOTWWCTWEN–TWIE0100010XTWEN must be written to one to enable the TWI. The TWEA bit must be written to oneto enable the acknowledgment 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 91. The Slave Transmitter mode may also be entered ifarbitration is lost while the TWI is in the Master mode (see state $B0).If the TWEA bit is written to zero during a transfer, the TWI will transmit the last byte ofthe transfer.

State $C0 or state $C8 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 $C8 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.In 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.2232467M–AVR–11/04Table 91.

Status Codes for Slave Transmitter ModeStatus Code(TWSR)Prescaler Bitsare 0$A8$B0$B8$C0$C8Application Software ResponseStatus of the Two-wire Serial Busand Two-wire Serial InterfaceHardwareTo TWCRTo/from TWDRSTASTOTWINTTWEANext Action Taken by TWI HardwareLoad data byte orX010Load data byteX011Last data byte will be transmitted and NOT ACK shouldbe receivedData byte will be transmitted and ACK should be receivedArbitration 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 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 freeFigure 103.

Formats and States in the Slave Transmitter ModeReception of theown slave addressand 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$C8From master to slaveFrom slave to master224DATAAnAny 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 zeroATmega1282467M–AVR–11/04ATmega128Miscellaneous StatesThere are two status codes that do not correspond to a defined TWI state, see Table 92.Status $F8 indicates that no relevant information is available because the TWINT flag isnot set.

This occurs between other states, and when the TWI is not involved in a serialtransfer.Status $00 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 92. Miscellaneous StatesStatus Code(TWSR)Prescaler Bitsare 0Application Software ResponseStatus of the Two-wire SerialBus and Two-wire Serial Interface HardwareTo TWCRTo/from TWDRSTASTO$F8No relevant state informationavailable; TWINT = “0”No TWDR actionNo TWCR action$00Bus error due to an illegalSTART or STOP conditionNo TWDR action0Combining Several TWIModesTWINT1TWEANext Action Taken by TWI HardwareWait or proceed current transfer1XOnly the internal hardware is affected, no STOP condition is sent on the bus.

In all cases, the bus is releasedand TWSTO is cleared.In 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 initiated2. The EEPROM must be instructed what location should be read3. The reading must be performed4. The transfer must be finishedNote 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.

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

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

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

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