ATmega8 (961730), страница 39

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

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

Formats and States in the Slave Transmitter ModeReception of the ownslave address and one ormore data bytesSSLARADATA$A8Arbitration lost as masterand addressed as slaveADATA$B8AP or S$C0A$B0Last data byte transmitted.Switched to not addressedslave (TWEA = '0')AAll 1'sP or S$C8DATAFrom master to slaveFrom slave to masterMiscellaneous StatesAAny 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 zeronThere are two status codes that do not correspond to a defined TWI state, see Table 70.Status 0xF8 indicates that no relevant information is available because the TWINT Flagis not set.

This occurs between other states, and when the TWI is not involved in a serialtransfer.Status 0x00 indicates that a bus error has occurred during a Two-wire Serial Bus transfer. A bus error occurs when a START or STOP condition occurs at an illegal position inthe format frame.

Examples of such illegal positions are during the serial transfer of anaddress byte, a data byte, or an acknowledge bit. When a bus error occurs, TWINT isset. To recover from a bus error, the TWSTO Flag must set and TWINT must be clearedby writing a logic one to it. This causes the TWI to enter the not addressed Slave modeand to clear the TWSTO Flag (no other bits in TWCR are affected).

The SDA and SCLlines are released, and no STOP condition is transmitted.Table 70. Miscellaneous StatesStatus Code(TWSR)Prescaler Bitsare 0Application Software ResponseStatus of the Two-wire SerialBus and Two-wire Serial Interface HardwareTo TWCRTo/from TWDR0xF8No relevant state informationavailable; TWINT = “0”No TWDR action0x00Bus error due to an illegalSTART or STOP conditionNo TWDR actionSTASTOTWINTTWEANo TWCR action011Next Action Taken by TWI HardwareWait or proceed current transferXOnly the internal hardware is affected, no STOP condition is sent on the bus. In all cases, the bus is releasedand TWSTO is cleared.1872486O–AVR–10/04Combining Several TWIModesIn some cases, several TWI modes must be combined in order to complete the desiredaction. Consider for example reading data from a serial EEPROM.

Typically, such atransfer involves the following steps:1. The transfer must be initiated.2. The EEPROM must be instructed what location should be read.3. The reading must be performed.4. The transfer must be finished.Note that data is transmitted both from Master to Slave and vice versa. The Master mustinstruct the Slave what location it wants to read, requiring the use of the MT mode.

Subsequently, data must be read from the Slave, implying the use of the MR mode. Thus,the transfer direction must be changed. The Master must keep control of the bus duringall these steps, and the steps should be carried out as an atomical operation. If this principle is violated in a multimaster system, another Master can alter the data pointer in theEEPROM between steps 2 and 3, and the Master will read the wrong data location.Such a change in transfer direction is accomplished by transmitting a REPEATEDSTART between the transmission of the address byte and reception of the data. After aREPEATED START, the Master keeps ownership of the bus.

The following figure showsthe flow in this transfer.Figure 86. Combining Several TWI Modes to Access a Serial EEPROMMaster TransmitterSSLA+WAADDRESSS = STARTARsSLA+RADATARs = REPEATED STARTTransmitted from master to slaveMulti-master Systemsand ArbitrationMaster ReceiverAPP = STOPTransmitted from slave to masterIf multiple masters are connected to the same bus, transmissions may be initiated simultaneously by one or more of them.

The TWI standard ensures that such situations arehandled in such a way that one of the masters will be allowed to proceed with the transfer, and that no data will be lost in the process. An example of an arbitration situation isdepicted below, where two masters are trying to transmit data to a Slave Receiver.Figure 87. An Arbitration ExampleVCCDevice 1Device 2Device 3MASTERTRANSMITTERMASTERTRANSMITTERSLAVERECEIVER........Device nR1R2SDASCLSeveral different scenarios may arise during arbitration, as described below:188ATmega8(L)2486O–AVR–10/04ATmega8(L)•Two or more masters are performing identical communication with the same Slave.In this case, neither the Slave nor any of the masters will know about the buscontention.•Two or more masters are accessing the same Slave with different data or directionbit.

In this case, arbitration will occur, either in the READ/WRITE bit or in the databits. The masters trying to output a one on SDA while another Master outputs a zerowill lose the arbitration. Losing masters will switch to not addressed Slave mode orwait until the bus is free and transmit a new START condition, depending onapplication software action.•Two or more masters are accessing different slaves. In this case, arbitration willoccur in the SLA bits. Masters trying to output a one on SDA while another Masteroutputs a zero will lose the arbitration. Masters losing arbitration in SLA will switch toSlave mode to check if they are being addressed by the winning Master.

Ifaddressed, they will switch to SR or ST mode, depending on the value of theREAD/WRITE bit. If they are not being addressed, they will switch to not addressedSlave mode or wait until the bus is free and transmit a new START condition,depending on application software action.This is summarized in Figure 88. Possible status values are given in circles.Figure 88. Possible Status Codes Caused by ArbitrationSTARTSLADataArbitration lost in SLAOwnAddress / General CallreceivedNoSTOPArbitration lost in Data38TWI bus will be released and not addressed slave mode will be enteredA START condition will be transmitted when the bus becomes freeYesDirectionWrite68/78ReadB0Data byte will be received and NOT ACK will be returnedData byte will be received and ACK will be returnedLast data byte will be transmitted and NOT ACK should be receivedData byte will be transmitted and ACK should be received1892486O–AVR–10/04Analog ComparatorThe Analog Comparator compares the input values on the positive pin AIN0 and negative pin AIN1.

When the voltage on the positive pin AIN0 is higher than the voltage onthe negative pin AIN1, the Analog Comparator Output, ACO, is set. The comparator’soutput can be set to trigger the Timer/Counter1 Input Capture function. In addition, thecomparator can trigger a separate interrupt, exclusive to the Analog Comparator. Theuser can select Interrupt triggering on comparator output rise, fall or toggle.

A block diagram of the comparator and its surrounding logic is shown in Figure 89.Figure 89. Analog Comparator Block Diagram(2)BANDGAPREFERENCEACBGACMEADENADC MULTIPLEXEROUTPUT (1)Notes:Special Function IO Register –SFIOR1. See Table 72 on page 192.2. Refer to “Pin Configurations” on page 2 and Table 28 on page 61 for Analog Comparator pin placement.Bit76543210––––ACMEPUDPSR2PSR10Read/WriteRRRRR/WR/WR/WR/WInitial Value00000000SFIOR• Bit 3 – ACME: Analog Comparator Multiplexer EnableWhen this bit is written logic one and the ADC is switched off (ADEN in ADCSRA iszero), the ADC multiplexer selects the negative input to the Analog Comparator. Whenthis bit is written logic zero, AIN1 is applied to the negative input of the Analog Comparator. For a detailed description of this bit, see “Analog Comparator Multiplexed Input” onpage 192.190ATmega8(L)2486O–AVR–10/04ATmega8(L)Analog Comparator Controland Status Register – ACSRBit76543210ACDACBGACOACIACIEACICACIS1ACIS0Read/WriteR/WR/WRR/WR/WR/WR/WR/WInitial Value00N/A00000ACSR• Bit 7 – ACD: Analog Comparator DisableWhen this bit is written logic one, the power to the Analog Comparator is switched off.This bit can be set at any time to turn off the Analog Comparator.

This will reduce powerconsumption in Active and Idle mode. When changing the ACD bit, the Analog Comparator Interrupt must be disabled by clearing the ACIE bit in ACSR. Otherwise an interruptcan occur when the bit is changed.• Bit 6 – ACBG: Analog Comparator Bandgap SelectWhen this bit is set, a fixed bandgap reference voltage replaces the positive input to theAnalog Comparator. When this bit is cleared, AIN0 is applied to the positive input of theAnalog Comparator. See “Internal Voltage Reference” on page 40.• Bit 5 – ACO: Analog Comparator OutputThe output of the Analog Comparator is synchronized and then directly connected toACO. The synchronization introduces a delay of 1 - 2 clock cycles.• Bit 4 – ACI: Analog Comparator Interrupt FlagThis bit is set by hardware when a comparator output event triggers the interrupt modedefined by ACIS1 and ACIS0.

The Analog Comparator Interrupt routine is executed ifthe ACIE bit is set and the I-bit in SREG is set. ACI is cleared by hardware when executing the corresponding interrupt Handling Vector. Alternatively, ACI is cleared by writinga logic one to the flag.• Bit 3 – ACIE: Analog Comparator Interrupt EnableWhen the ACIE bit is written logic one and the I-bit in the Status Register is set, the Analog Comparator interrupt is activated.

When written logic zero, the interrupt is disabled.• Bit 2 – ACIC: Analog Comparator Input Capture EnableWhen written logic one, this bit enables the Input Capture function in Timer/Counter1 tobe triggered by the Analog Comparator. The comparator output is in this case directlyconnected to the Input Capture front-end logic, making the comparator utilize the noisecanceler and edge select features of the Timer/Counter1 Input Capture interrupt. Whenwritten logic zero, no connection between the Analog Comparator and the Input Capturefunction exists.

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

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

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

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