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

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

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

In multimaster systems, TWAR mustbe set in masters which can be addressed as Slaves by other Masters.The LSB of TWAR is used to enable recognition of the general call address (0x00).There is an associated address comparator that looks for the slave address (or generalcall address if enabled) in the received serial address. If a match is found, an interruptrequest is generated.• Bits 7..1 – TWA: TWI (Slave) Address RegisterThese seven bits constitute the slave address of the TWI unit.• Bit 0 – TWGCE: TWI General Call Recognition Enable BitIf set, this bit enables the recognition of a General Call given over the Two-wire SerialBus.Using the TWIThe AVR TWI is byte-oriented and interrupt based. Interrupts are issued after all busevents, like reception of a byte or transmission of a START condition.

Because the TWIis interrupt-based, the application software is free to carry on other operations during aTWI byte transfer. Note that the TWI Interrupt Enable (TWIE) bit in TWCR together withthe Global Interrupt Enable bit in SREG allow the application to decide whether or notassertion of the TWINT Flag should generate an interrupt request.

If the TWIE bit iscleared, the application must poll the TWINT Flag in order to detect actions on the TWIbus.When the TWINT Flag is asserted, the TWI has finished an operation and awaits application response. In this case, the TWI Status Register (TWSR) contains a valueindicating the current state of the TWI bus. The application software can then decidehow the TWI should behave in the next TWI bus cycle by manipulating the TWCR andTWDR Registers.Figure 77 is a simple example of how the application can interface to the TWI hardware.In this example, a Master wishes to transmit a single data byte to a Slave.

This description is quite abstract, a more detailed explanation follows later in this section. A simplecode example implementing the desired behavior is also presented.1712486O–AVR–10/04ApplicationActionFigure 77. Interfacing the Application to the TWI in a Typical Transmission1. Applicationwrites to TWCR toinitiatetransmission ofSTARTTWIHardwareActionTWI bus3.

Check TWSR to see if START wassent. Application loads SLA+W intoTWDR, and loads appropriate controlsignals into TWCR, makin sure thatTWINT is written to one,and TWSTA is written to zero.START2. TWINT set.Status code indicatesSTART condition sentSLA+W5. Check TWSR to see if SLA+W wassent and ACK received.Application loads data into TWDR, andloads appropriate control signals intoTWCR, making sure that TWINT iswritten to oneA4. TWINT set.Status code indicatesSLA+W sent, ACKreceivedData7.

Check TWSR to see if data was sentand ACK received.Application loads appropriate controlsignals to send STOP into TWCR,making sure that TWINT is written to oneA6. TWINT set.Status code indicatesdata sent, ACK receivedSTOPIndicatesTWINT set1. The first step in a TWI transmission is to transmit a START condition. This isdone by writing a specific value into TWCR, instructing the TWI hardware totransmit a START condition. Which value to write is described later on.

However,it is important that the TWINT bit is set in the value written. Writing a one toTWINT clears the flag. The TWI will not start any operation as long as theTWINT bit in TWCR is set. Immediately after the application has cleared TWINT,the TWI will initiate transmission of the START condition.2. When the START condition has been transmitted, the TWINT Flag in TWCR isset, and TWSR is updated with a status code indicating that the START conditionhas successfully been sent.3. The application software should now examine the value of TWSR, to make surethat the START condition was successfully transmitted. 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 is172ATmega8(L)2486O–AVR–10/04ATmega8(L)described 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,and TWSR is updated with a status code indicating that the data packet has successfully been sent. The status code will also reflect whether a Slaveacknowledged the 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.Even 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.1732486O–AVR–10/04Assembly Code Example1ldir16, (1<<TWINT)|(1<<TWSTA)|(1<<TWEN)2out TWCR, r16wait1:r16,TWCRinC ExampleTWCR = (1<<TWINT)|(1<<TWSTA)|rjmp wait1inr16,TWSRandi r16, 0xF8cpiwhile (!(TWCR & (1<<TWINT)));4outTWDR, r16ldir16, (1<<TWINT) | (1<<TWEN)out TWCR, r16wait2:r16,TWCRinif ((TWSR & 0xF8) != START)ERROR();r16, STARTbrne ERRORldi r16, SLA_WTWDR = SLA_W;TWCR = (1<<TWINT) | (1<<TWEN);while (!(TWCR & (1<<TWINT)));sbrs r16,TWINT5rjmp wait2inr16,TWSRandi r16, 0xF8cpir16, MT_SLA_ACKbrne ERRORldi r16, DATA6outTWDR, r16ldir16, (1<<TWINT) | (1<<TWEN)out TWCR, r16wait3:r16,TWCRinif ((TWSR & 0xF8) !=MT_SLA_ACK)ERROR();TWDR = DATA;TWCR = (1<<TWINT) | (1<<TWEN);while (!(TWCR & (1<<TWINT)));sbrs r16,TWINT7rjmp wait3inr16,TWSRandi r16, 0xF8cpir16, MT_DATA_ACKbrne ERRORldi r16, (1<<TWINT)|(1<<TWEN)|(1<<TWSTO)out174Send START condition(1<<TWEN)sbrs r16,TWINT3Commentsif ((TWSR & 0xF8) !=MT_DATA_ACK)ERROR();TWCR = (1<<TWINT)|(1<<TWEN)|Wait for TWINT Flag set.

Thisindicates that the START conditionhas been transmittedCheck value of TWI StatusRegister. Mask prescaler bits. Ifstatus different from START go toERRORLoad SLA_W into TWDR Register.Clear TWINT bit in TWCR to starttransmission of addressWait for TWINT Flag set. Thisindicates that the SLA+W has beentransmitted, and ACK/NACK hasbeen received.Check value of TWI StatusRegister.

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

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

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

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