ATmega128 (961843), страница 44

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

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

If TWSR indicates otherwise, the application software might take some special action, like calling anerror routine. Assuming that the status code is as expected, the application mustload SLA+W into TWDR. Remember that TWDR is used both for address anddata. After TWDR has been loaded with the desired SLA+W, a specific valuemust be written to TWCR, instructing the TWI hardware to transmit the SLA+Wpresent in TWDR. Which value to write is described later on. However, it isimportant that the TWINT bit is set in the value written.

Writing a one to TWINTclears the flag. The TWI will not start any operation as long as the TWINT bit inTWCR is set. Immediately after the application has cleared TWINT, the TWI willinitiate transmission of the address packet.4. When the address packet has been transmitted, the TWINT flag in TWCR is set,and TWSR is updated with a status code indicating that the address packet hassuccessfully been sent. The status code will also reflect whether a slaveacknowledged the packet or not.5. The application software should now examine the value of TWSR, to make surethat the address packet was successfully transmitted, and that the value of theACK bit was as expected.

If TWSR indicates otherwise, the application softwaremight take some special action, like calling an error routine. Assuming that thestatus code is as expected, the application must load a data packet into TWDR.Subsequently, a specific value must be written to TWCR, instructing the TWIhardware to transmit the data packet present in TWDR.

Which value to write isdescribed later on. However, it is important that the TWINT bit is set in the valuewritten. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the applicationhas cleared TWINT, the TWI will initiate transmission of the data packet.6.

When the data packet has been transmitted, the TWINT flag in TWCR is set, andTWSR is updated with a status code indicating that the data packet has successfully been sent. The status code will also reflect whether a slave acknowledgedthe packet or not.7. The application software should now examine the value of TWSR, to make surethat the data packet was successfully transmitted, and that the value of the ACKbit was as expected. If TWSR indicates otherwise, the application software mighttake some special action, like calling an error routine.

Assuming that the statuscode is as expected, the application must write a specific value to TWCR,instructing the TWI hardware to transmit a STOP condition. Which value to writeis described later on. However, it is important that the TWINT bit is set in thevalue written. Writing a one to TWINT clears the flag. The TWI will not start anyoperation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the STOPcondition. Note that TWINT is NOT set after a STOP condition has been sent.210ATmega1282467M–AVR–11/04ATmega128Even though this example is simple, it shows the principles involved in all TWI transmissions. These can be summarized as follows:•When the TWI has finished an operation and expects application response, theTWINT flag is set.

The SCL line is pulled low until TWINT is cleared.•When the TWINT flag is set, the user must update all TWI Registers with the valuerelevant for the next TWI bus cycle. As an example, TWDR must be loaded with thevalue to be transmitted in the next bus cycle.•After all TWI Register updates and other pending application software tasks havebeen completed, TWCR is written. When writing TWCR, the TWINT bit should beset. Writing a one to TWINT clears the flag.

The TWI will then commence executingwhatever operation was specified by the TWCR setting.In the following an assembly and C implementation of the example is given. Note thatthe code below assumes that several definitions have been made for example by usinginclude-files.2112467M–AVR–11/04Assembly Code Example1ldi r16,(1<<TWINT)|(1<<TWSTA)|C ExampleTWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN)(1<<TWEN)2out TWCR, r16wait1:r16,TWCRin3andi r16, 0xF8cpi;outTWDR, r16ldi r16, (1<<TWINT) |(1<<TWEN)4out TWCR, r16wait2:r16,TWCRinERROR();5andi r16, 0xF8cpir16, MT_SLA_ACKbrne ERRORldi r16, DATAoutTWDR, r16ldi r16, (1<<TWINT) |(1<<TWEN)6out TWCR, r16wait3:r16,TWCRinTWCR = (1<<TWINT) |(1<<TWEN);7andi r16, 0xF8cpir16, MT_DATA_ACKbrne ERRORldi r16,(1<<TWINT)|(1<<TWEN)|(1<<TWSTO)outNote:212Load SLA_W into TWDR Register.

ClearTWINT bit in TWCR to start transmission ofaddresswhile (!(TWCR & (1<<TWINT)));if ((TWSR & 0xF8) !=MT_SLA_ACK)ERROR();Wait for TWINT flag set. This indicates that theSLA+W has been transmitted, andACK/NACK has been received.Check value of TWI Status Register.

Maskprescaler bits. If status different fromMT_SLA_ACK go to ERRORTWDR = DATA;TWCR = (1<<TWINT) |(1<<TWEN);Load DATA into TWDR Register. Clear TWINTbit in TWCR to start transmission of datawhile (!(TWCR & (1<<TWINT)));sbrs r16,TWINTrjmp wait3inr16,TWSRCheck value of TWI Status Register. Maskprescaler bits. If status different from STARTgo to ERRORTWDR = SLA_W;sbrs r16,TWINTrjmp wait2inr16,TWSRWait for TWINT flag set. This indicates that theSTART condition has been transmittedif ((TWSR & 0xF8) != START)r16, STARTbrne ERRORldi r16, SLA_WSend START conditionwhile (!(TWCR & (1<<TWINT)))sbrs r16,TWINTrjmp wait1inr16,TWSRCommentsif ((TWSR & 0xF8) !=MT_DATA_ACK)ERROR();Wait for TWINT flag set.

This indicates that theDATA has been transmitted, and ACK/NACKhas been received.Check value of TWI Status Register. Maskprescaler bits. If status different fromMT_DATA_ACK go to ERRORTWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWSTO);Transmit STOP conditionTWCR, r16For I/O registers located in extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and “SBI” instructions must be replaced withinstructions that allow access to extended I/O.

Typically “LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”.ATmega1282467M–AVR–11/04ATmega128Transmission 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 97 to Figure 103, 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 of thefollowing serial transfer are given in Table 88 to Table 91. Note that the prescaler bitsare masked to zero in these tables.Master Transmitter ModeIn the Master Transmitter mode, a number of data bytes are transmitted to a slavereceiver (see Figure 96). 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.2132467M–AVR–11/04Figure 96. Data Transfer in Master Transmitter ModeVCCDevice 1Device 2MASTERTRANSMITTERSLAVERECEIVERDevice 3........Device nR1R2SDASCLA 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 START condition 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 $08 (See Table88). In order to enter MT mode, SLA+W must be transmitted. This is done by writingSLA+W 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+W 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 $18, $20, or $38. The appropriate action to be taken foreach of these status codes is detailed in Table 88.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.

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

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

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

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