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

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

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

The following codeexamples show a transmit function that handles 9 bit characters. For the assemblycode, the data to be sent is assumed to be stored in Registers R17:R16.Assembly Code Example(1)USART_Transmit:; Wait for empty transmit buffersbis UCSRA,UDRErjmp USART_Transmit; Copy 9th bit from r17 to TXB8cbiUCSRB,TXB8sbrc r17,0sbiUCSRB,TXB8; Put LSB data (r16) into buffer, sends the dataoutUDR,r16retC Code Examplevoid USART_Transmit( unsigned int data ){/* Wait for empty transmit buffer */while ( !( UCSRA & (1<<UDRE)) );/* Copy 9th bit to TXB8 */UCSRB &= ~(1<<TXB8);if ( data & 0x0100 )UCSRB |= (1<<TXB8);/* Put data into buffer, sends the data */UDR = data;}Note:1. These transmit functions are written to be general functions. They can be optimized ifthe contents of the UCSRB is static. I.e., only the TXB8 bit of the UCSRB Register isused after initialization.For I/O registers located in extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and“SBI” instructions must be replaced with instructions that allow access to extendedI/O.

Typically “LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”.The ninth bit can be used for indicating an address frame when using multi processorcommunication mode or for other protocol handling as for example synchronization.Transmitter Flags andInterruptsThe USART Transmitter has two flags that indicate its state: USART Data RegisterEmpty (UDRE) and Transmit Complete (TXC).

Both flags can be used for generatinginterrupts.The Data Register Empty (UDRE) flag indicates whether the transmit buffer is ready toreceive new data. This bit is set when the transmit buffer is empty, and cleared when thetransmit buffer contains data to be transmitted that has not yet been moved into the ShiftRegister.

For compatibility with future devices, always write this bit to zero when writingthe UCSRA Register.1792467M–AVR–11/04When the Data Register empty Interrupt Enable (UDRIE) bit in UCSRB is written to one,the USART Data Register Empty Interrupt will be executed as long as UDRE is set (provided that global interrupts are enabled). UDRE is cleared by writing UDR. Wheninterrupt-driven data transmission is used, the data register empty Interrupt routine musteither write new data to UDR in order to clear UDRE or disable the data register emptyinterrupt, otherwise a new interrupt will occur once the interrupt routine terminates.The Transmit Complete (TXC) flag bit is set one when the entire frame in the TransmitShift Register has been shifted out and there are no new data currently present in thetransmit buffer.

The TXC flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. The TXC flag isuseful in half-duplex communication interfaces (like the RS485 standard), where atransmitting application must enter receive mode and free the communication busimmediately after completing the transmission.When the Transmit Compete Interrupt Enable (TXCIE) bit in UCSRB is set, the USARTTransmit Complete Interrupt will be executed when the TXC flag becomes set (providedthat global interrupts are enabled).

When the transmit complete interrupt is used, theinterrupt handling routine does not have to clear the TXC flag, this is done automaticallywhen the interrupt is executed.Parity GeneratorThe parity generator calculates the parity bit for the serial frame data. When parity bit isenabled (UPM1 = 1), the transmitter control logic inserts the parity bit between the lastdata bit and the first stop bit of the frame that is sent.Disabling the TransmitterThe disabling of the Transmitter (setting the TXEN to zero) will not become effectiveuntil ongoing and pending transmissions are completed, i.e., when the Transmit ShiftRegister and Transmit Buffer register do not contain data to be transmitted. When disabled, the Transmitter will no longer override the TxD pin.Data Reception – TheUSART ReceiverThe USART Receiver is enabled by writing the Receive Enable (RXEN) bit in theUCSRB Register to one.

When the receiver is enabled, the normal pin operation of theRxD pin is overridden by the USART and given the function as the receiver’s serialinput. The baud rate, mode of operation and frame format must be set up once beforeany serial reception can be done. If synchronous operation is used, the clock on theXCK pin will be used as transfer clock.Receiving Frames with 5 to 8Data BitsThe Receiver starts data reception when it detects a valid start bit. Each bit that followsthe start bit will be sampled at the baud rate or XCK clock, and shifted into the ReceiveShift Register until the first stop bit of a frame is received.

A second stop bit will beignored by the receiver. When the first stop bit is received, i.e., a complete serial frameis present in the Receive Shift Register, the contents of the Shift Register will be movedinto the receive buffer. The receive buffer can then be read by reading the UDR I/Olocation.180ATmega1282467M–AVR–11/04ATmega128The following code example shows a simple USART receive function based on pollingof the Receive Complete (RXC) flag.

When using frames with less than eight bits themost significant bits of the data read from the UDR will be masked to zero. The USARThas to be initialized before the function can be used.Assembly Code Example(1)USART_Receive:; Wait for data to be receivedsbis UCSRA, RXCrjmp USART_Receive; Get and return received data from bufferinr16, UDRretC Code Example(1)unsigned char USART_Receive( void ){/* Wait for data to be received */while ( !(UCSRA & (1<<RXC)) );/* Get and return received data from buffer */return UDR;}Note:1. The example code assumes that the part specific header file is included.For I/O registers located in extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and“SBI” instructions must be replaced with instructions that allow access to extendedI/O.

Typically “LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”.The function simply waits for data to be present in the receive buffer by checking theRXC flag, before reading the buffer and returning the value.1812467M–AVR–11/04Receiving Frames with 9 DataBitsIf 9-bit characters are used (UCSZ=7) the ninth bit must be read from the RXB8 bit inUCSRB before reading the low bits from the UDR. This rule applies to the FE, DOR andUPE status flags as well. Read status from UCSRA, then data from UDR. Reading theUDR I/O location will change the state of the receive buffer FIFO and consequently theTXB8, FE, DOR, and UPE bits, which all are stored in the FIFO, will change.The following code example shows a simple USART receive function that handles bothnine bit characters and the status bits.Assembly Code Example(1)USART_Receive:; Wait for data to be receivedsbis UCSRA, RXCrjmp USART_Receive; Get status and 9th bit, then data from bufferinr18, UCSRAinr17, UCSRBinr16, UDR; If error, return -1andi r18,(1<<FE)|(1<<DOR)|(1<<UPE)breq USART_ReceiveNoErrorldir17, HIGH(-1)ldir16, LOW(-1)USART_ReceiveNoError:; Filter the 9th bit, then returnlsrr17andi r17, 0x01retC Code Example(1)unsigned int USART_Receive( void ){unsigned char status, resh, resl;/* Wait for data to be received */while ( !(UCSRA & (1<<RXC)) );/* Get status and 9th bit, then data *//* from buffer */status = UCSRA;resh = UCSRB;resl = UDR;/* If error, return -1 */if ( status & (1<<FE)|(1<<DOR)|(1<<UPE) )return -1;/* Filter the 9th bit, then return */resh = (resh >> 1) & 0x01;return ((resh << 8) | resl);}182ATmega1282467M–AVR–11/04ATmega128Note:1.

The example code assumes that the part specific header file is included.For I/O registers located in extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and“SBI” instructions must be replaced with instructions that allow access to extendedI/O. Typically “LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”.The receive function example reads all the I/O registers into the register file before anycomputation is done. This gives an optimal receive buffer utilization since the bufferlocation read will be free to accept new data as early as possible.Receive Compete Flag andInterruptThe USART Receiver has one flag that indicates the receiver state.The Receive Complete (RXC) flag indicates if there are unread data present in thereceive buffer.

This flag is one when unread data exist in the receive buffer, and zerowhen the receive buffer is empty (i.e., does not contain any unread data). If the Receiveris disabled (RXEN = 0), the receive buffer will be flushed and consequently the RXC bitwill become zero.When the Receive Complete Interrupt Enable (RXCIE) in UCSRB is set, the USARTReceive Complete Interrupt will be executed as long as the RXC flag is set (providedthat global interrupts are enabled). When interrupt-driven data reception is used, thereceive complete routine must read the received data from UDR in order to clear theRXC flag, otherwise a new interrupt will occur once the interrupt routine terminates.Receiver Error FlagsThe USART receiver has three error flags: Frame Error (FE), Data OverRun (DOR) andParity Error (UPE).

All can be accessed by reading UCSRA. Common for the error flagsis that they are located in the receive buffer together with the frame for which they indicate the error status. Due to the buffering of the error flags, the UCSRA must be readbefore the receive buffer (UDR), since reading the UDR I/O location changes the bufferread location. Another equality for the error flags is that they can not be altered by software doing a write to the flag location. However, all flags must be set to zero when theUCSRA is written for upward compatibility of future USART implementations.

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

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

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

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