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

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

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

Mask prescaler bits. Ifstatus different from MT_SLA_ACKgo to ERRORLoad DATA into TWDR Register.Clear TWINT bit in TWCR to starttransmission of dataWait for TWINT Flag set. Thisindicates that the DATA has beentransmitted, and ACK/NACK hasbeen received.Check value of TWI StatusRegister. Mask prescaler bits. Ifstatus different fromMT_DATA_ACK go to ERRORTransmit STOP condition(1<<TWSTO);TWCR, r16ATmega8(L)2486O–AVR–10/04ATmega8(L)Transmission ModesThe TWI can operate in one of four major modes. These are named Master Transmitter(MT), Master Receiver (MR), Slave Transmitter (ST) and Slave Receiver (SR). Severalof these modes can be used in the same application.

As an example, the TWI can useMT mode to write data into a TWI EEPROM, MR mode to read the data back from theEEPROM. If other masters are present in the system, some of these might transmit datato the TWI, and then SR mode would be used. It is the application software that decideswhich modes are legal.The following sections describe each of these modes.

Possible status codes aredescribed along with figures detailing data transmission in each of the modes. These figures contain the following abbreviations:S: START conditionRs: REPEATED START conditionR: Read bit (high level at SDA)W: Write bit (low level at SDA)A: Acknowledge bit (low level at SDA)A: Not acknowledge bit (high level at SDA)Data: 8-bit data byteP: STOP conditionSLA: Slave AddressIn Figure 79 to Figure 85, circles are used to indicate that the TWINT Flag is set. Thenumbers in the circles show the status code held in TWSR, with the prescaler bitsmasked to zero.

At these points, actions must be taken by the application to continue orcomplete the TWI transfer. The TWI transfer is suspended until the TWINT Flag iscleared by software.When the TWINT Flag is set, the status code in TWSR is used to determine the appropriate software action. For each status code, the required software action and details ofthe following serial transfer are given in Table 66 to Table 69.

Note that the prescalerbits are masked to zero in these tables.1752486O–AVR–10/04Master Transmitter ModeIn the Master Transmitter mode, a number of data bytes are transmitted to a SlaveReceiver (see Figure 78). 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 78. Data Transfer in Master Transmitter ModeVCCDevice 1Device 2MASTERTRANSMITTERSLAVERECEIVERDevice 3........R1Device nR2SDASCLA START condition is sent by writing the following value to TWCR:TWCRvalueTWINTTWEATWSTATWSTOTWWCTWEN–TWIE1X10X10XTWEN must be set to enable the Two-wire Serial Interface, TWSTA must be written toone to transmit a START condition and TWINT must be written to one to clear theTWINT Flag.

The TWI will then test the Two-wire Serial Bus and generate a STARTcondition as soon as the bus becomes free. After a START condition has been transmitted, the TWINT Flag is set by hardware, and the status code in TWSR will be 0x08 (seeTable 66). In order to enter MT mode, SLA+W must be transmitted. This is done by writing SLA+W to TWDR.

Thereafter the TWINT bit should be cleared (by writing it to one)to continue the transfer. This is accomplished by writing the following value to TWCR:TWCRvalueTWINTTWEATWSTATWSTOTWWCTWEN–TWIE1X00X10XWhen SLA+W have been transmitted and an acknowledgement 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 0x18, 0x20, or 0x38. The appropriate action to be takenfor each of these status codes is detailed in Table 66.When SLA+W has been successfully transmitted, a data packet should be transmitted.This is done by writing the data byte to TWDR. TWDR must only be written whenTWINT is high. If not, the access will be discarded, and the Write Collision bit (TWWC)will be set in the TWCR Register.

After updating TWDR, the TWINT bit should becleared (by writing it to one) to continue the transfer. This is accomplished by writing thefollowing value to TWCR:TWCRvalue176TWINTTWEATWSTATWSTOTWWCTWEN–TWIE1X00X10XATmega8(L)2486O–AVR–10/04ATmega8(L)This scheme is repeated until the last byte has been sent and the transfer is ended bygenerating a STOP condition or a repeated START condition.

A STOP condition is generated by writing the following value to TWCR:TWCRTWINTTWEATWSTATWSTOTWWCTWEN–TWIE1X01X10XvalueA REPEATED START condition is generated by writing the following value to TWCR:TWCRTWINTTWEATWSTATWSTOTWWCTWEN–TWIE1X10X10XvalueAfter a repeated START condition (state 0x10) the Two-wire Serial Interface can accessthe same Slave again, or a new Slave without transmitting a STOP condition. RepeatedSTART enables the Master to switch between Slaves, Master Transmitter mode andMaster Receiver mode without losing control of the bus..Table 66. Status codes for Master Transmitter ModeStatus Code(TWSR)Prescaler Bitsare 0Application Software ResponseStatus of the Two-wire SerialBus and Two-wire Serial Interface HardwareTo/from TWDR0x08A START condition has beentransmitted0x10A repeated START conditionhas been transmitted0x180x200x280x300x38SLA+W has been transmitted;ACK has been receivedSLA+W has been transmitted;NOT ACK has been receivedData byte has been transmitted;ACK has been receivedData byte has been transmitted;NOT ACK has been receivedArbitration lost in SLA+W or databytesTo TWCRSTASTOTWINTTWEALoad SLA+W001XSLA+W will be transmitted;ACK or NOT ACK will be receivedLoad SLA+W or001XLoad SLA+R001XSLA+W will be transmitted;ACK or NOT ACK will be receivedSLA+R will be transmitted;Logic will switch to Master Receiver modeLoad data byte or001XNo TWDR action orNo TWDR action or100111XXNo TWDR action111XLoad data byte or001XNo TWDR action orNo TWDR action or100111XXNo TWDR action111XLoad data byte or001XNo TWDR action orNo TWDR action or100111XXNo TWDR action111XLoad data byte or001XNo TWDR action orNo TWDR action or100111XXNo TWDR action111XNo TWDR action or001XNo TWDR action101XNext Action Taken by TWI HardwareData byte will be transmitted and ACK or NOT ACK willbe receivedRepeated START will be transmittedSTOP condition will be transmitted andTWSTO Flag will be resetSTOP condition followed by a START condition will betransmitted and TWSTO Flag will be resetData byte will be transmitted and ACK or NOT ACK willbe receivedRepeated START will be transmittedSTOP condition will be transmitted andTWSTO Flag will be resetSTOP condition followed by a START condition will betransmitted and TWSTO Flag will be resetData byte will be transmitted and ACK or NOT ACK willbe receivedRepeated START will be transmittedSTOP condition will be transmitted andTWSTO Flag will be resetSTOP condition followed by a START condition will betransmitted and TWSTO Flag will be resetData byte will be transmitted and ACK or NOT ACK willbe receivedRepeated START will be transmittedSTOP condition will be transmitted andTWSTO Flag will be resetSTOP condition followed by a START condition will betransmitted and TWSTO Flag will be resetTwo-wire Serial Bus will be released and not addressedSlave mode enteredA START condition will be transmitted when the bus becomes free1772486O–AVR–10/04Figure 79.

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 master178A 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 zeroATmega8(L)2486O–AVR–10/04ATmega8(L)Master Receiver ModeIn the Master Receiver mode, a number of data bytes are received from a Slave Transmitter (see Figure 80).

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 80.

Data Transfer in Master Receiver ModeVCCDevice 1Device 2MASTERRECEIVERSLAVETRANSMITTERDevice 3........R1Device nR2SDASCLA 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 0x08 (See Table66). In order to enter MR mode, SLA+R must be transmitted. This is done by writingSLA+R to TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) tocontinue the transfer.

This is accomplished by writing the following value to TWCR:TWCRvalueTWINTTWEATWSTATWSTOTWWCTWEN–TWIE1X00X10XWhen SLA+R have been transmitted and an acknowledgement 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 0x38, 0x40, or 0x48. The appropriate action to be takenfor each of these status codes is detailed in Table 67. Received data can be read fromthe TWDR Register when the TWINT Flag is set high by hardware.

This scheme isrepeated until the last byte has been received. After the last byte has been received, theMR should inform the ST by sending a NACK after the last received data byte. Thetransfer is ended by generating a STOP condition or a repeated START condition. ASTOP 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–TWIE1X10X10X1792486O–AVR–10/04After a repeated START condition (state 0x10) the Two-wire Serial Interface can accessthe same Slave again, or a new Slave without transmitting a STOP condition. RepeatedSTART enables the Master to switch between Slaves, Master Transmitter mode andMaster Receiver mode without losing control over the bus.Table 67.

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

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

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

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