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

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

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

Formats and States in the Master Transmitter ModeMTSuccessfulltransmissionto a slavereceiverSSLA$08WADATA$18AP$28Next transferstarted with arepeated startconditionRSSLAW$10Not acknowledgereceived after theslave addressARP$20MRNot acknowledgereceived after a databyteAP$30Arbitration lost in slaveaddress or data byteA or AOther mastercontinues$38Arbitration lost andaddressed as slaveA$68From master to slaveFrom slave to master216A or AOther mastercontinues$38Other mastercontinues$78DATATo correspondingstates in slave mode$B0AnAny 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/04ATmega128Master Receiver ModeIn the Master Receiver Mode, a number of data bytes are received from a slave transmitter (see Figure 98).

In order to enter a Master mode, a START condition must betransmitted. The format of the following address packet determines whether MasterTransmitter or Master Receiver mode is to be entered. If SLA+W is transmitted, MTmode is entered, if SLA+R is transmitted, MR mode is entered. All the status codesmentioned in this section assume that the prescaler bits are zero or are masked to zero.Figure 98.

Data Transfer in Master Receiver ModeVCCDevice 1Device 2MASTERRECEIVERSLAVETRANSMITTERDevice 3........Device nR1R2SDASCLA START condition is sent by writing the following value to TWCR:TWCRvalueTWINTTWEATWSTATWSTOTWWCTWEN–TWIE1X10X10XTWEN must be written to one to enable the Two-wire Serial Interface, TWSTA must bewritten to one to transmit a START condition and TWINT must be set to clear the TWINTflag.

The TWI will then test the Two-wire Serial Bus and generate a START condition assoon as the bus becomes free. After a START condition has been transmitted, theTWINT flag is set by hardware, and the status code in TWSR will be $08 (See Table 88).In order to enter MR mode, SLA+R must be transmitted. This is done by writing SLA+Rto TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) to continuethe transfer. This is accomplished by writing the following value to TWCR:TWCRvalueTWINTTWEATWSTATWSTOTWWCTWEN–TWIE1X00X10XWhen SLA+R have been transmitted and an acknowledgment bit has been received,TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in Master mode are $38, $40, or $48.

The appropriate action to be taken foreach of these status codes is detailed in Table 97. Received data can be read from theTWDR Register when the TWINT flag is set high by hardware. This scheme is repeateduntil the last byte has been received. After the last byte has been received, the MRshould inform the ST by sending a NACK after the last received data byte. The transferis ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing the following value to TWCR:TWCRvalueTWINTTWEATWSTATWSTOTWWCTWEN–TWIE1X01X10XA REPEATED START condition is generated by writing the following value to TWCR:TWCRvalueTWINTTWEATWSTATWSTOTWWCTWEN–TWIE1X10X10XAfter a repeated START condition (state $10) the Two-wire Serial Interface can accessthe same slave again, or a new slave without transmitting a STOP condition.

Repeated2172467M–AVR–11/04START enables the master to switch between slaves, Master Transmitter mode andMaster Receiver mode without losing control over the bus.Figure 99. Formats and States in the Master Receiver ModeMRSuccessfullreceptionfrom a slavereceiverSSLA$08RADATA$40ADATA$50AP$58Next transferstarted with arepeated startconditionRSSLAR$10Not acknowledgereceived after theslave addressAWP$48MTArbitration lost in slaveaddress or data byteA or AOther mastercontinues$38Arbitration lost andaddressed as slaveA$68From master to slaveFrom slave to master218AOther mastercontinues$38Other mastercontinues$78DATATo correspondingstates in slave mode$B0AnAny 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/04ATmega128Table 89.

Status Codes for Master Receiver ModeStatus Code(TWSR)Prescaler Bitsare 0Application Software ResponseStatus of the Two-wire SerialBus and Two-wire Serial Interface HardwareTo TWCRTo/from TWDRSTASTOTWINTTWEA$08A START condition has beentransmittedLoad SLA+R001XSLA+R will be transmittedACK or NOT ACK will be received$10A repeated START conditionhas been transmittedLoad SLA+R or001XLoad SLA+W001XSLA+R will be transmittedACK or NOT ACK will be receivedSLA+W will be transmittedLogic will switch to master transmitter modeNo TWDR action or001XNo TWDR action101XNo TWDR action or0010No TWDR action0011No TWDR action orNo TWDR action or100111XXNo TWDR action111X$38$40$48Arbitration lost in SLA+R or NOTACK bitSLA+R has been transmitted;ACK has been receivedSLA+R has been transmitted;NOT ACK has been received$50Data byte has been received;ACK has been returnedRead data byte or0Read data byte0011$58Data byte has been received;NOT ACK has been returnedRead data byte orRead data byte or100111XXRead data byte111XSlave Receiver Mode01Next Action Taken by TWI HardwareTwo-wire Serial Bus will be released and not addressedslave mode will be enteredA START condition will be transmitted when the busbecomes freeData byte will be received and NOT ACK will bereturnedData byte will be received and ACK will be returnedRepeated START will be transmittedSTOP condition will be transmitted and TWSTO flag willbe resetSTOP condition followed by a START condition will betransmitted and TWSTO flag will be reset0Data byte will be received and NOT ACK will bereturnedData byte will be received and ACK will be returnedRepeated START will be transmittedSTOP condition will be transmitted and TWSTO flag willbe resetSTOP condition followed by a START condition will betransmitted and TWSTO flag will be resetIn the Slave Receiver mode, a number of data bytes are received from a master transmitter (see Figure 100).

All the status codes mentioned in this section assume that theprescaler bits are zero or are masked to zero.Figure 100. Data Transfer in Slave Receiver ModeVCCDevice 1Device 2SLAVERECEIVERMASTERTRANSMITTERDevice 3........Device nR1R2SDASCLTo initiate the Slave Receiver mode, TWAR and TWCR must be initialized as follows:TWARvalueTWA6TWA5TWA4TWA3TWA2TWA1TWA0TWGCEDevice’s Own Slave Address2192467M–AVR–11/04The 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 “0” (write), the TWI will operate in SR mode, otherwise ST 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 90. The slave receiver mode may also be entered if arbitration is lost while the TWI is in the master mode (see states $68 and $78).If the TWEA bit is reset during a transfer, the TWI will return a “Not Acknowledge” (“1”)to SDA after the next received data byte. This can be used to indicate that the slave isnot able to receive any more bytes. While TWEA is zero, the TWI does not acknowledgeits own slave address.

However, the Two-wire Serial Bus is still monitored and addressrecognition may resume at any time by setting TWEA. This implies that the TWEA bitmay be used to temporarily isolate the TWI 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 low during the wake up anduntil the TWINT flag is cleared (by writing it to one). Further data reception will be carried 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.220ATmega1282467M–AVR–11/04ATmega128Table 90.

Status Codes for Slave Receiver ModeStatus Code(TWSR)Prescaler Bitsare 0Application Software ResponseStatus of the Two-wire Serial Busand Two-wire Serial InterfaceHardwareTo TWCRTo/from TWDRSTASTOTWINTTWEANo TWDR action orX010$60Own SLA+W has been received;ACK has been returnedNo TWDR actionX011$68Arbitration lost in SLA+R/W asmaster; own SLA+W has beenreceived; ACK has been returnedNo TWDR action orX010No TWDR actionX011$70General call address has beenreceived; ACK has been returnedNo TWDR action orX010No TWDR actionX011$78Arbitration lost in SLA+R/W asmaster; General call address hasbeen received; ACK has beenreturnedNo TWDR action orX010No TWDR actionX011$80Previously addressed with ownSLA+W; data has been received;ACK has been returnedRead data byte orX010Read data byteX011$88Previously addressed with ownSLA+W; data has been received;NOT ACK has been returnedRead data byte or0010Read data byte or0011Read data byte or1010Read data byte1011X010$90Previously addressed withgeneral call; data has been received; ACK has been returnedRead data byte orRead data byteX011$98Previously addressed withgeneral call; data has beenreceived; NOT ACK has beenreturnedRead data byte or0010Read data byte or0011Read data byte or1010Read data byte1011No Action0010001110101011$A0A STOP condition or repeatedSTART condition has beenreceived while still addressed asslaveNext Action Taken by TWI HardwareData byte will be received and NOT ACK will bereturnedData byte will be received and ACK will be returnedData byte will be received and NOT ACK will bereturnedData byte will be received and ACK will be returnedData byte will be received and NOT ACK will bereturnedData byte will be received and ACK will be returnedData byte will be received and NOT ACK will bereturnedData byte will be received and ACK will be returnedData byte will be received and NOT ACK will bereturnedData byte will be received and ACK will be returnedSwitched 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 freeData byte will be received and NOT ACK will bereturnedData byte will be received and ACK will be returnedSwitched 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 free2212467M–AVR–11/04Figure 101.

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

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

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

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