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

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

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

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.1392486O–AVR–10/04Data 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.The 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.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.140ATmega8(L)2486O–AVR–10/04ATmega8(L)Receiving 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 andPE 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 PE bits, which all are stored in the FIFO, will change.1412486O–AVR–10/04The following code example shows a simple USART receive function that handles both9-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 ninth bit, then data from bufferinr18, UCSRAinr17, UCSRBinr16, UDR; If error, return -1andi r18,(1<<FE)|(1<<DOR)|(1<<PE)breq USART_ReceiveNoErrorldir17, HIGH(-1)ldir16, LOW(-1)USART_ReceiveNoError:; Filter the ninth 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 ninth bit, then data *//* from buffer */status = UCSRA;resh = UCSRB;resl = UDR;/* If error, return -1 */if ( status & (1<<FE)|(1<<DOR)|(1<<PE) )return -1;/* Filter the ninth bit, then return */resh = (resh >> 1) & 0x01;return ((resh << 8) | resl);}Note:1.

The example code assumes that the part specific header file is included.The receive function example reads all the I/O Registers into the Register File beforeany computation is done. This gives an optimal receive buffer utilization since the bufferlocation read will be free to accept new data as early as possible.142ATmega8(L)2486O–AVR–10/04ATmega8(L)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 (PE).

All can be accessed by reading UCSRA. Common for the error flags isthat they are located in the receive buffer together with the frame for which they indicatethe error status. Due to the buffering of the error flags, the UCSRA must be read beforethe receive buffer (UDR), since reading the UDR I/O location changes the buffer readlocation. Another equality for the error flags is that they can not be altered by softwaredoing 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. None ofthe error flags can generate interrupts.The Frame Error (FE) Flag indicates the state of the first stop bit of the next readableframe stored in the receive buffer. The FE Flag is zero when the stop bit was correctlyread (as one), and the FE Flag will be one when the stop bit was incorrect (zero).

Thisflag can be used for detecting out-of-sync conditions, detecting break conditions andprotocol handling. The FE Flag is not affected by the setting of the USBS bit in UCSRCsince the Receiver ignores all, except for the first, stop bits. For compatibility with futuredevices, always set this bit to zero when writing to UCSRA.The Data OverRun (DOR) Flag indicates data loss due to a Receiver buffer full condition.

A Data OverRun occurs when the receive buffer is full (two characters), it is a newcharacter waiting in the Receive Shift Register, and a new start bit is detected. If theDOR Flag is set there was one or more serial frame lost between the frame last readfrom UDR, and the next frame read from UDR. For compatibility with future devices,always write this bit to zero when writing to UCSRA. The DOR Flag is cleared when theframe received was successfully moved from the Shift Register to the receive buffer.The Parity Error (PE) Flag indicates that the next frame in the receive buffer had a parityerror when received.

If parity check is not enabled the PE bit will always be read zero.For compatibility with future devices, always set this bit to zero when writing to UCSRA.For more details see “Parity Bit Calculation” on page 135 and “Parity Checker” on page144.1432486O–AVR–10/04Parity CheckerThe Parity Checker is active when the high USART Parity mode (UPM1) bit is set.

Typeof parity check to be performed (odd or even) is selected by the UPM0 bit. Whenenabled, the Parity Checker calculates the parity of the data bits in incoming frames andcompares the result with the parity bit from the serial frame. The result of the check isstored in the receive buffer together with the received data and stop bits. The ParityError (PE) Flag can then be read by software to check if the frame had a parity error.The PE bit is set if the next character that can be read from the receive buffer had a parity error when received and the parity checking was enabled at that point (UPM1 = 1).This bit is valid until the receive buffer (UDR) is read.Disabling the ReceiverIn contrast to the Transmitter, disabling of the Receiver will be immediate. Data fromongoing receptions will therefore be lost.

When disabled (i.e., the RXEN is set to zero)the Receiver will no longer override the normal function of the RxD port pin. TheReceiver buffer FIFO will be flushed when the Receiver is disabled. Remaining data inthe buffer will be lostFlushing the Receive BufferThe Receiver buffer FIFO will be flushed when the Receiver is disabled (i.e., the bufferwill be emptied of its contents). Unread data will be lost. If the buffer has to be flushedduring normal operation, due to for instance an error condition, read the UDR I/O location until the RXC Flag is cleared.

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

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

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

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