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

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

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

SPI Block DiagramSPI2XSPI2XDIVIDER/2/4/8/16/32/64/128Note:Refer to Figure 1 on page 2 and Table 30 on page 71 for SPI pin placement.The interconnection between Master and Slave CPUs with SPI is shown in Figure 76.The system consists of two Shift Registers, and a Master clock generator. The SPI Master initiates the communication cycle when pulling low the Slave Select SS pin of thedesired Slave. Master and Slave prepare the data to be sent in their respective ShiftRegisters, and the Master generates the required clock pulses on the SCK line to interchange data.

Data is always shifted from Master to Slave on the Master Out – Slave In,MOSI, line, and from Slave to Master on the Master In – Slave Out, MISO, line. Aftereach data packet, the Master will synchronize the Slave by pulling high the Slave Select,SS, line.162ATmega1282467M–AVR–11/04ATmega128When configured as a Master, the SPI interface has no automatic control of the SS line.This must be handled by user software before communication can start. When this isdone, writing a byte to the SPI Data Register starts the SPI clock generator, and thehardware shifts the 8 bits into the Slave. After shifting one byte, the SPI clock generatorstops, setting the end of transmission flag (SPIF). If the SPI interrupt enable bit (SPIE) inthe SPCR Register is set, an interrupt is requested.

The Master may continue to shift thenext byte by writing it into SPDR, or signal the end of packet by pulling high the SlaveSelect, SS line. The last incoming byte will be kept in the buffer register for later use.When configured as a Slave, the SPI interface will remain sleeping with MISO tri-statedas long as the SS pin is driven high. In this state, software may update the contents ofthe SPI Data Register, SPDR, but the data will not be shifted out by incoming clockpulses on the SCK pin until the SS pin is driven low. As one byte has been completelyshifted, the end of transmission flag, SPIF is set.

If the SPI interrupt enable bit, SPIE, inthe SPCR Register is set, an interrupt is requested. The Slave may continue to placenew data to be sent into SPDR before reading the incoming data. The last incoming bytewill be kept in the buffer register for later use.Figure 76.

SPI Master-Slave InterconnectionSHIFTENABLEThe system is single buffered in the transmit direction and double buffered in the receivedirection. This means that bytes to be transmitted cannot be written to the SPI DataRegister before the entire shift cycle is completed. When receiving data, however, areceived character must be read from the SPI Data Register before the next characterhas been completely shifted in. Otherwise, the first byte is lost.In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. Toensure correct sampling of the clock signal, the frequency of the SPI clock should neverexceed fosc/4.When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins isoverridden according to Table 69. For more details on automatic port overrides, refer to“Alternate Port Functions” on page 68.Table 69.

SPI Pin Overrides(1)PinDirection, Master SPIDirection, Slave SPIMOSIUser DefinedInputMISOInputUser DefinedSCKUser DefinedInputSSUser DefinedInput1632467M–AVR–11/04Note:1. See “Alternate Functions of Port B” on page 71 for a detailed description of how todefine the direction of the user defined SPI pins.The following code examples show how to initialize the SPI as a Master and how to perform a simple transmission. DDR_SPI in the examples must be replaced by the actualdata direction register controlling the SPI pins.

DD_MOSI, DD_MISO and DD_SCKmust be replaced by the actual data direction bits for these pins. For example, if MOSI isplaced on pin PB5, replace DD_MOSI with DDB5 and DDR_SPI with DDRB.Assembly Code Example(1)SPI_MasterInit:; Set MOSI and SCK output, all others inputldir17,(1<<DD_MOSI)|(1<<DD_SCK)outDDR_SPI,r17; Enable SPI, Master, set clock rate fck/16ldir17,(1<<SPE)|(1<<MSTR)|(1<<SPR0)outSPCR,r17retSPI_MasterTransmit:; Start transmission of data (r16)outSPDR,r16Wait_Transmit:; Wait for transmission completesbis SPSR,SPIFrjmp Wait_TransmitretC Code Example(1)void SPI_MasterInit(void){/* Set MOSI and SCK output, all others input */DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);/* Enable SPI, Master, set clock rate fck/16 */SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);}void SPI_MasterTransmit(char cData){/* Start transmission */SPDR = cData;/* Wait for transmission complete */while(!(SPSR & (1<<SPIF)));}Note:1641.

The example code assumes that the part specific header file is included.ATmega1282467M–AVR–11/04ATmega128The following code examples show how to initialize the SPI as a slave and how to perform a simple reception.Assembly Code Example(1)SPI_SlaveInit:; Set MISO output, all others inputldir17,(1<<DD_MISO)outDDR_SPI,r17; Enable SPIldir17,(1<<SPE)outSPCR,r17retSPI_SlaveReceive:; Wait for reception completesbis SPSR,SPIFrjmp SPI_SlaveReceive; Read received data and returninr16,SPDRretC Code Example(1)void SPI_SlaveInit(void){/* Set MISO output, all others input */DDR_SPI = (1<<DD_MISO);/* Enable SPI */SPCR = (1<<SPE);}char SPI_SlaveReceive(void){/* Wait for reception complete */while(!(SPSR & (1<<SPIF)));/* Return data register */return SPDR;}Note:1.

The example code assumes that the part specific header file is included.1652467M–AVR–11/04SS Pin FunctionalitySlave ModeWhen the SPI is configured as a slave, the Slave Select (SS) pin is always input. WhenSS is held low, the SPI is activated, and MISO becomes an output if configured so bythe user. All other pins are inputs. When SS is driven high, all pins are inputs, and theSPI is passive, which means that it will not receive incoming data. Note that the SPIlogic will be reset once the SS pin is driven high.The SS pin is useful for packet/byte synchronization to keep the slave bit counter synchronous with the master clock generator. When the SS pin is driven high, the SPI slavewill immediately reset the send and receive logic, and drop any partially received data inthe Shift Register.Master ModeWhen the SPI is configured as a master (MSTR in SPCR is set), the user can determinethe direction of the SS pin.If SS is configured as an output, the pin is a general output pin which does not affect theSPI system.

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 will166ATmega1282467M–AVR–11/04ATmega128be 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 77 and Figure 78 for an example.

The CPOL functionality is summarized below:Table 70. 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 77 and Figure 78 for an example.The CPHA functionality is summarized below:Table 71. 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 72. Relationship Between SCK and the Oscillator FrequencySPI2XSPR1SPR0000001010011100101110111SCK Frequencyfosc /4fosc /16fosc /64fosc /128fosc /2fosc /8fosc /32fosc /641672467M–AVR–11/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 if SPIEin 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 by hardware 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 ATmega128 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 72).

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

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

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

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