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

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

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

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. The following code example shows how to flush thereceive buffer.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:1.

The example code assumes that the part specific header file is included.Asynchronous DataReceptionThe 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.Asynchronous ClockRecoveryThe clock recovery logic synchronizes internal clock to the incoming serial frames.

Figure 65 illustrates the sampling process of the start bit of an incoming frame. The samplerate is 16 times the baud rate for Normal mode, and eight 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 mode144ATmega8(L)2486O–AVR–10/04ATmega8(L)(U2X = 1) of operation. Samples denoted zero are samples done when the RxD line isidle (i.e., no communication activity).Figure 65. 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 zerosample as shown in the figure.

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

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

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

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