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

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

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

Typically, the pin will be driving the SS pin of the SPI Slave.If SS is configured as an input, it must be held high to ensure Master SPI operation. Ifthe SS pin is driven low by peripheral circuitry when the SPI is configured as a Masterwith the SS pin defined as an input, the SPI system interprets this as another Masterselecting the SPI as a Slave and starting to send data to it.

To avoid bus contention, theSPI system takes the following actions:1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As aresult of the SPI becoming a Slave, the MOSI and SCK pins become inputs.2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit inSREG is set, the interrupt routine will be executed.Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists apossibility that SS is driven low, the interrupt should always check that the MSTR bit isstill set.

If the MSTR bit has been cleared by a Slave Select, it must be set by the user tore-enable SPI Master mode.SPI Control Register – SPCRBit76543210SPIESPEDORDMSTRCPOLCPHASPR1SPR0Read/WriteR/WR/WR/WR/WR/WR/WR/WR/WInitial Value00000000SPCR• Bit 7 – SPIE: SPI Interrupt EnableThis bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is setand the if the global interrupt enable bit in SREG is set.• Bit 6 – SPE: SPI EnableWhen the SPE bit is written to one, the SPI is enabled. This bit must be set to enableany SPI operations.• Bit 5 – DORD: Data OrderWhen the DORD bit is written to one, the LSB of the data word is transmitted first.When the DORD bit is written to zero, the MSB of the data word is transmitted first.• Bit 4 – MSTR: Master/Slave SelectThis bit selects Master SPI mode when written to one, and Slave SPI mode when writtenlogic zero.

If SS is configured as an input and is driven low while MSTR is set, MSTR will126ATmega8(L)2486O–AVR–10/04ATmega8(L)be cleared, and SPIF in SPSR will become set. The user will then have to set MSTR tore-enable SPI Master mode.• Bit 3 – CPOL: Clock PolarityWhen this bit is written to one, SCK is high when idle. When CPOL is written to zero,SCK is low when idle.

Refer to Figure 59 and Figure 60 for an example. The CPOL functionality is summarized below:Table 48. CPOL FunctionalityCPOLLeading EdgeTrailing Edge0RisingFalling1FallingRising• Bit 2 – CPHA: Clock PhaseThe settings of the clock phase bit (CPHA) determine if data is sampled on the leading(first) or trailing (last) edge of SCK. Refer to Figure 59 and Figure 60 for an example.The CPHA functionality is summarized below:Table 49. CPHA FunctionalityCPHALeading EdgeTrailing Edge0SampleSetup1SetupSample• Bits 1, 0 – SPR1, SPR0: SPI Clock Rate Select 1 and 0These two bits control the SCK rate of the device configured as a Master.

SPR1 andSPR0 have no effect on the Slave. The relationship between SCK and the OscillatorClock frequency fosc is shown in the following table:Table 50. Relationship Between SCK and the Oscillator FrequencySPI2XSPR1SPR0000001010011100101110111SCK Frequencyfosc/4fosc/16fosc/64fosc/128fosc/2fosc/8fosc/32fosc/641272486O–AVR–10/04SPI Status Register – SPSRBit76543210SPIFWCOL–––––SPI2XRead/WriteRRRRRRRR/WInitial Value00000000SPSR• Bit 7 – SPIF: SPI Interrupt FlagWhen a serial transfer is complete, the SPIF Flag is set. An interrupt is generated ifSPIE in SPCR is set and global interrupts are enabled. If SS is an input and is driven lowwhen the SPI is in Master mode, this will also set the SPIF Flag.

SPIF is cleared byhardware when executing the corresponding interrupt Handling Vector. Alternatively, theSPIF bit is cleared by first reading the SPI Status Register with SPIF set, then accessingthe SPI Data Register (SPDR).• Bit 6 – WCOL: Write COLlision FlagThe WCOL bit is set if the SPI Data Register (SPDR) is written during a data transfer.The WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status Registerwith WCOL set, and then accessing the SPI Data Register.• Bit 5..1 – Res: Reserved BitsThese bits are reserved bits in the ATmega8 and will always read as zero.• Bit 0 – SPI2X: Double SPI Speed BitWhen this bit is written logic one the SPI speed (SCK Frequency) will be doubled whenthe SPI is in Master mode (see Table 50).

This means that the minimum SCK period willbe 2 CPU clock periods. When the SPI is configured as Slave, the SPI is only guaranteed to work at fosc/4 or lower.The SPI interface on the ATmega8 is also used for Program memory and EEPROMdownloading or uploading. See page 234 for Serial Programming and verification.SPI Data Register – SPDRBit7654321MSB0LSBRead/WriteR/WR/WR/WR/WR/WR/WR/WR/WInitial ValueXXXXXXXXSPDRUndefinedThe SPI Data Register is a Read/Write Register used for data transfer between the Register File and the SPI Shift Register. Writing to the register initiates data transmission.Reading the register causes the Shift Register Receive buffer to be read.128ATmega8(L)2486O–AVR–10/04ATmega8(L)Data ModesThere are four combinations of SCK phase and polarity with respect to serial data,which are determined by control bits CPHA and CPOL.

The SPI data transfer formatsare shown in Figure 59 and Figure 60. Data bits are shifted out and latched in on opposite edges of the SCK signal, ensuring sufficient time for data signals to stabilize. This isclearly seen by summarizing Table 48 and Table 49, as done below:Table 51. CPOL and CPHA FunctionalityLeading EdgeTrailing EdgeSPI ModeCPOL = 0, CPHA = 0Sample (Rising)Setup (Falling)0CPOL = 0, CPHA = 1Setup (Rising)Sample (Falling)1CPOL = 1, CPHA = 0Sample (Falling)Setup (Rising)2CPOL = 1, CPHA = 1Setup (Falling)Sample (Rising)3Figure 59.

SPI Transfer Format with CPHA = 0SCK (CPOL = 0)mode 0SCK (CPOL = 1)mode 2SAMPLE IMOSI/MISOCHANGE 0MOSI PINCHANGE 0MISO PINSSMSB first (DORD = 0)LSB first (DORD = 1)MSBLSBBit 6Bit 1Bit 5Bit 2Bit 4Bit 3Bit 3Bit 4Bit 2Bit 5Bit 1Bit 6LSBMSBFigure 60. SPI Transfer Format with CPHA = 1SCK (CPOL = 0)mode 1SCK (CPOL = 1)mode 3SAMPLE IMOSI/MISOCHANGE 0MOSI PINCHANGE 0MISO PINSSMSB first (DORD = 0)LSB first (DORD = 1)MSBLSBBit 6Bit 1Bit 5Bit 2Bit 4Bit 3Bit 3Bit 4Bit 2Bit 5Bit 1Bit 6LSBMSB1292486O–AVR–10/04USARTThe Universal Synchronous and Asynchronous serial Receiver and Transmitter(USART) is a highly-flexible serial communication device.

The main features are:• Full Duplex Operation (Independent Serial Receive and Transmit Registers)• Asynchronous or Synchronous Operation• Master or Slave Clocked Synchronous Operation• High Resolution Baud Rate Generator• Supports Serial Frames with 5, 6, 7, 8, or 9 Databits and 1 or 2 Stop Bits• Odd or Even Parity Generation and Parity Check Supported by Hardware• Data OverRun Detection• Framing Error Detection• Noise Filtering Includes False Start Bit Detection and Digital Low Pass Filter• Three Separate Interrupts on TX Complete, TX Data Register Empty and RX Complete• Multi-processor Communication Mode• Double Speed Asynchronous Communication ModeOverviewA simplified block diagram of the USART Transmitter is shown in Figure 61.

CPU accessible I/O Registers and I/O pins are shown in bold.Figure 61. USART Block Diagram(1)Clock GeneratorUBRR[H:L]OSCBAUD RATE GENERATORSYNC LOGICPINCONTROLXCKTransmitterTXCONTROLDATABUSUDR (Transmit)PARITYGENERATOR130TxDReceiverUCSRANote:PINCONTROLTRANSMIT SHIFT REGISTERCLOCKRECOVERYRXCONTROLRECEIVE SHIFT REGISTERDATARECOVERYPINCONTROLUDR (Receive)PARITYCHECKERUCSRBRxDUCSRC1.

Refer to “Pin Configurations” on page 2, Table 30 on page 62, and Table 29 on page62 for USART pin placement.ATmega8(L)2486O–AVR–10/04ATmega8(L)The dashed boxes in the block diagram separate the three main parts of the USART(listed from the top): Clock generator, Transmitter and Receiver. Control Registers areshared by all units. The clock generation logic consists of synchronization logic for external clock input used by synchronous slave operation, and the baud rate generator. TheXCK (transfer clock) pin is only used by synchronous transfer mode. The Transmitterconsists of a single write buffer, a serial Shift Register, Parity Generator and controllogic for handling different serial frame formats.

The write buffer allows a continuoustransfer of data without any delay between frames. The Receiver is the most complexpart of the USART module due to its clock and data recovery units. The recovery unitsare used for asynchronous data reception. In addition to the recovery units, the Receiverincludes a parity checker, control logic, a Shift Register and a two level receive buffer(UDR).

The Receiver supports the same frame formats as the Transmitter, and candetect Frame Error, Data OverRun and Parity Errors.AVR USART vs. AVR UART –CompatibilityThe USART is fully compatible with the AVR UART regarding:•Bit locations inside all USART Registers.•Baud Rate Generation.•Transmitter Operation.•Transmit Buffer Functionality.•Receiver Operation.However, the receive buffering has two improvements that will affect the compatibility insome special cases:•A second Buffer Register has been added.

The two Buffer Registers operate as acircular FIFO buffer. Therefore the UDR must only be read once for each incomingdata! More important is the fact that the Error Flags (FE and DOR) and the ninthdata bit (RXB8) are buffered with the data in the receive buffer. Therefore the statusbits must always be read before the UDR Register is read. Otherwise the errorstatus will be lost since the buffer state is lost.•The Receiver Shift Register can now act as a third buffer level.

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

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

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

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