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

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

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

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 new character waiting in the Receive Shift Register, and a new start bit is detected.

If the DOR flagis set there was one or more serial frame lost between the frame last read from UDR,and the next frame read from UDR. For compatibility with future devices, always writethis bit to zero when writing to UCSRA. The DOR flag is cleared when the framereceived was successfully moved from the Shift Register to the receive buffer.The Parity Error (UPE) flag indicates that the next frame in the receive buffer had a parity error when received. If parity check is not enabled the UPE bit will always be readzero. For compatibility with future devices, always set this bit to zero when writing toUCSRA.

For more details see “Parity Bit Calculation” on page 175 and “Parity Checker”on page 184.1832467M–AVR–11/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 (UPE) flag can then be read by software to check if the frame had a Parity Error.The UPE bit is set if the next character that can be read from the receive buffer had aparIty 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. The receiverbuffer FIFO will be flushed when the receiver is disabled.

Remaining data in the bufferwill be lostFlushing the Receive BufferThe receiver buffer FIFO will be flushed when the receiver is disabled, i.e. the buffer willbe emptied of its contents. Unread data will be lost. If the buffer has to be flushed duringnormal operation, due to for instance an error condition, read the UDR I/O location untilthe RXC flag is cleared. The following code example shows how to flush the receivebuffer.Assembly Code Example(1)USART_Flush:sbis UCSRA, RXCretinr16, UDRrjmp USART_FlushC Code Example(1)void USART_Flush( void ){unsigned char dummy;while ( UCSRA & (1<<RXC) ) dummy = UDR;}Note:Asynchronous DataReception1841. 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 USART includes a clock recovery and a data recovery unit for handling asynchronous data reception. The clock recovery logic is used for synchronizing the internallygenerated baud rate clock to the incoming asynchronous serial frames at the RxD pin.The data recovery logic samples and low pass filters each incoming bit, thereby improving the noise immunity of the receiver.

The asynchronous reception operational rangedepends on the accuracy of the internal baud rate clock, the rate of the incomingframes, and the frame size in number of bits.ATmega1282467M–AVR–11/04ATmega128Asynchronous ClockRecoveryThe clock recovery logic synchronizes internal clock to the incoming serial frames. Figure 83 illustrates the sampling process of the start bit of an incoming frame.

The samplerate is 16 times the baud rate for normal mode, and 8 times the baud rate for DoubleSpeed mode. The horizontal arrows illustrate the synchronization variation due to thesampling process. Note the larger time variation when using the double speed mode(U2X = 1) of operation. Samples denoted zero are samples done when the RxD line isidle (i.e., no communication activity).Figure 83. Start Bit SamplingRxDIDLESTARTBIT 0Sample(U2X = 0)0012345678910111213141516123Sample(U2X = 1)01234567812When the clock recovery logic detects a high (idle) to low (start) transition on the RxDline, the start bit detection sequence is initiated. Let sample 1 denote the first zero-sample as shown in the figure.

The clock recovery logic then uses samples 8, 9, and 10 fornormal mode, and samples 4, 5, and 6 for Double Speed mode (indicated with samplenumbers inside boxes on the figure), to decide if a valid start bit is received. If two ormore of these three samples have logical high levels (the majority wins), the start bit isrejected as a noise spike and the receiver starts looking for the next high to low-transition. If however, a valid start bit is detected, the clock recovery logic is synchronized andthe data recovery can begin.

The synchronization process is repeated for each start bit.Asynchronous Data RecoveryWhen the receiver clock is synchronized to the start bit, the data recovery can begin.The data recovery unit uses a state machine that has 16 states for each bit in normalmode and 8 states for each bit in Double Speed mode. Figure 84 shows the sampling ofthe data bits and the parity bit. Each of the samples is given a number that is equal tothe state of the recovery unit.Figure 84.

Sampling of Data and Parity BitRxDBIT nSample(U2X = 0)123456789101112131415161Sample(U2X = 1)123456781The decision of the logic level of the received bit is taken by doing a majority voting ofthe logic value to the three samples in the center of the received bit. The center samplesare emphasized on the figure by having the sample number inside boxes.

The majorityvoting process is done as follows: If two or all three samples have high levels, thereceived bit is registered to be a logic 1. If two or all three samples have low levels, thereceived bit is registered to be a logic 0. This majority voting process acts as a low passfilter for the incoming signal on the RxD pin. The recovery process is then repeated untila complete frame is received. Including the first stop bit. Note that the receiver only uses1852467M–AVR–11/04the first stop bit of a frame. Figure 85 shows the sampling of the stop bit and the earliestpossible beginning of the start bit of the next frame.Figure 85. Stop Bit Sampling and Next Start Bit SamplingRxDSTOP 1(A)(B)(C)Sample(U2X = 0)123456789100/10/10/1Sample(U2X = 1)1234560/1The same majority voting is done to the stop bit as done for the other bits in the frame.

Ifthe stop bit is registered to have a logic 0 value, the Frame Error (FE) flag will be set.A new high to low transition indicating the start bit of a new frame can come right afterthe last of the bits used for majority voting. For Normal Speed mode, the first low levelsample can be at point marked (A) in Figure 85. For Double Speed mode the first lowlevel must be delayed to (B).

(C) marks a stop bit of full length. The early start bit detection influences the operational range of the receiver.Asynchronous OperationalRangeThe operational range of the Receiver is dependent on the mismatch between thereceived bit rate and the internally generated baud rate. If the Transmitter is sendingframes at too fast or too slow bit rates, or the internally generated baud rate of thereceiver does not have a similar (see Table 75) base frequency, the Receiver will not beable to synchronize the frames to the start bit.The following equations can be used to calculate the ratio of the incoming data rate andinternal receiver baud rate.( D + 1 )SR slow = -----------------------------------------S – 1 + D ⋅ S + SF( D + 2 )SR fast = ----------------------------------( D + 1 )S + S MDSum of character size and parity size (D = 5 to 10-bit)SSamples per bit.

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

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

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

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