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

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

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

All devices connected to the bus have individualaddresses, and mechanisms for resolving bus contention are inherent in the TWIprotocol.Simple yet Powerful and Flexible Communication Interface, only Two Bus Lines NeededBoth Master and Slave Operation SupportedDevice can Operate as Transmitter or Receiver7-bit Address Space allows up to 128 Different Slave AddressesMulti-master Arbitration SupportUp to 400 kHz Data Transfer SpeedSlew-rate Limited Output DriversNoise Suppression Circuitry Rejects Spikes on Bus LinesFully Programmable Slave Address with General Call SupportAddress Recognition Causes Wake-up when AVR is in Sleep ModeFigure 86.

TWI Bus InterconnectionVCCDevice 1Device 2Device 3........Device nR1R2SDASCLTWI TerminologyThe following definitions are frequently encountered in this section.Table 86. TWI TerminologyElectrical Interconnection198TermDescriptionMasterThe device that initiates and terminates a transmission. The master alsogenerates the SCL clockSlaveThe device addressed by a masterTransmitterThe device placing data on the busReceiverThe device reading data from the busAs depicted in Figure 86, both bus lines are connected to the positive supply voltagethrough pull-up resistors.

The bus drivers of all TWI-compliant devices are open-drain oropen-collector. This implements a wired-AND function which is essential to the operation of the interface. A low level on a TWI bus line is generated when one or more TWIATmega1282467M–AVR–11/04ATmega128devices output a zero. A high level is output when all TWI devices tri-state their outputs,allowing the pull-up resistors to pull the line high. Note that all AVR devices connected tothe TWI bus must be powered in order to allow any bus operation.The number of devices that can be connected to the bus is only limited by the buscapacitance limit of 400 pF and the 7-bit slave address space. A detailed specification ofthe electrical characteristics of the TWI is given in “Two-wire Serial Interface Characteristics” on page 324.

Two different sets of specifications are presented there, onerelevant for bus speeds below 100 kHz, and one valid for bus speeds up to 400 kHz.Data Transfer and FrameFormatTransferring BitsEach data bit transferred on the TWI bus is accompanied by a pulse on the clock line.The level of the data line must be stable when the clock line is high. The only exceptionto this rule is for generating start and stop conditions.Figure 87. Data ValiditySDASCLData StableData StableData ChangeSTART and STOP ConditionsThe master initiates and terminates a data transmission. The transmission is initiatedwhen the master issues a START condition on the bus, and it is terminated when themaster issues a STOP condition. Between a START and a STOP condition, the bus isconsidered busy, and no other master should try to seize control of the bus.

A specialcase occurs when a new START condition is issued between a START and STOP condition. This is referred to as a REPEATED START condition, and is used when themaster wishes to initiate a new transfer without relinquishing control of the bus. After aREPEATED START, the bus is considered busy until the next STOP. This is identical tothe START behavior, and therefore START is used to describe both START andREPEATED START for the remainder of this datasheet, unless otherwise noted. Asdepicted below, START and STOP conditions are signalled by changing the level of theSDA line when the SCL line is high.Figure 88.

START, REPEATED START and STOP ConditionsSDASCLSTARTSTOP STARTREPEATED STARTSTOP1992467M–AVR–11/04Address Packet FormatAll address packets transmitted on the TWI bus are 9 bits long, consisting of 7 addressbits, one READ/WRITE control bit and an acknowledge bit. If the READ/WRITE bit isset, a read operation is to be performed, otherwise a write operation should be performed. When a slave recognizes that it is being addressed, it should acknowledge bypulling SDA low in the ninth SCL (ACK) cycle. If the addressed slave is busy, or forsome other reason can not service the master’s request, the SDA line should be lefthigh in the ACK clock cycle. The master can then transmit a STOP condition, or aREPEATED START condition to initiate a new transmission. An address packet consisting of a slave address and a READ or a WRITE bit is called SLA+R or SLA+W,respectively.The MSB of the address byte is transmitted first.

Slave addresses can freely be allocated by the designer, but the address 0000 000 is reserved for a general call.When a general call is issued, all slaves should respond by pulling the SDA line low inthe ACK cycle. A general call is used when a master wishes to transmit the same message to several slaves in the system. When the general call address followed by a Writebit is transmitted on the bus, all slaves set up to acknowledge the general call will pullthe SDA line low in the ack cycle. The following data packets will then be received by allthe slaves that acknowledged the general call.

Note that transmitting the general calladdress followed by a Read bit is meaningless, as this would cause contention if severalslaves started transmitting different data.All addresses of the format 1111 xxx should be reserved for future purposes.Figure 89. Address Packet FormatAddr MSBAddr LSBR/WACK789SDASCL12STARTData Packet Format200All data packets transmitted on the TWI bus are 9 bits long, consisting of one data byteand an acknowledge bit. During a data transfer, the master generates the clock and theSTART and STOP conditions, while the receiver is responsible for acknowledging thereception.

An Acknowledge (ACK) is signalled by the receiver pulling the SDA line lowduring the ninth SCL cycle. If the receiver leaves the SDA line high, a NACK is signalled.When the receiver has received the last byte, or for some reason cannot receive anymore bytes, it should inform the transmitter by sending a NACK after the final byte. TheMSB of the data byte is transmitted first.ATmega1282467M–AVR–11/04ATmega128Figure 90. Data Packet FormatData MSBData LSBACK89AggregateSDASDA fromTransmitterSDA fromReceiverSCL fromMaster127SLA+R/WCombining Address and DataPackets Into a TransmissionSTOP, REPEATEDSTART or NextData ByteData ByteA transmission basically consists of a START condition, a SLA+R/W, one or more datapackets and a STOP condition. An empty message, consisting of a START followed bya STOP condition, is illegal. Note that the Wired-ANDing of the SCL line can be used toimplement handshaking between the master and the slave.

The slave can extend theSCL low period by pulling the SCL line low. This is useful if the clock speed set up by themaster is too fast for the slave, or the slave needs extra time for processing between thedata transmissions. The slave extending the SCL low period will not affect the SCL highperiod, which is determined by the master. As a consequence, the slave can reduce theTWI data transfer speed by prolonging the SCL duty cycle.Figure 91 shows a typical data transmission. Note that several data bytes can be transmitted between the SLA+R/W and the STOP condition, depending on the softwareprotocol implemented by the application software.Figure 91. Typical Data TransmissionAddr MSBAddr LSBR/WACKData MSB7891Data LSBACK89SDASCL1START2SLA+R/W27Data ByteSTOPMulti-master BusThe TWI protocol allows bus systems with several masters.

Special concerns haveSystems, Arbitration and been taken in order to ensure that transmissions will proceed as normal, even if two ormore masters initiate a transmission at the same time. Two problems arise in multi-masSynchronizationter systems:•An algorithm must be implemented allowing only one of the masters to complete thetransmission. All other masters should cease transmission when they discover thatthey have lost the selection process. This selection process is called arbitration.When a contending master discovers that it has lost the arbitration process, itshould immediately switch to slave mode to check whether it is being addressed bythe winning master. The fact that multiple masters have started transmission at thesame time should not be detectable to the slaves, i.e., the data being transferred onthe bus must not be corrupted.2012467M–AVR–11/04•Different masters may use different SCL frequencies.

A scheme must be devised tosynchronize the serial clocks from all masters, in order to let the transmissionproceed in a lockstep fashion. This will facilitate the arbitration process.The wired-ANDing of the bus lines is used to solve both these problems. The serialclocks from all masters will be wired-ANDed, yielding a combined clock with a highperiod equal to the one from the master with the shortest high period.

The low period ofthe combined clock is equal to the low period of the master with the longest low period.Note that all masters listen to the SCL line, effectively starting to count their SCL highand low time-out periods when the combined SCL line goes high or low, respectively.Figure 92. SCL Synchronization between Multiple MastersTA lowTA highSCL frommaster ASCL frommaster BSCL BusLineTBlowMasters StartCounting Low PeriodTBhighMasters StartCounting High PeriodArbitration is carried out by all masters continuously monitoring the SDA line after outputting data.

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

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

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

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