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

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

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

The examples assume asynchronous operation using polling (no interrupts enabled) and a fixed frame format. The baud rate isgiven as a function parameter. For the assembly code, the baud rate parameter isassumed to be stored in the r17:r16 Registers. When the function writes to the UCSRCRegister, the URSEL bit (MSB) must be set due to the sharing of I/O location by UBRRHand UCSRC.1352486O–AVR–10/04Assembly Code Example(1)USART_Init:; Set baud rateoutUBRRH, r17outUBRRL, r16; Enable Receiver and Transmitterldir16, (1<<RXEN)|(1<<TXEN)outUCSRB,r16; Set frame format: 8data, 2stop bitldir16, (1<<URSEL)|(1<<USBS)|(3<<UCSZ0)outUCSRC,r16retC Code Example(1)void USART_Init( unsigned int baud ){/* Set baud rate */UBRRH = (unsigned char)(baud>>8);UBRRL = (unsigned char)baud;/* Enable Receiver and Transmitter */UCSRB = (1<<RXEN)|(1<<TXEN);/* Set frame format: 8data, 2stop bit */UCSRC = (1<<URSEL)|(1<<USBS)|(3<<UCSZ0);}Note:1.

The example codes assume that the part specific header file is included.More advanced initialization routines can be made that include frame format as parameters, disable interrupts and so on. However, many applications use a fixed setting of theBaud and Control Registers, and for these types of applications the initialization codecan be placed directly in the main routine, or be combined with initialization code forother I/O modules.136ATmega8(L)2486O–AVR–10/04ATmega8(L)Data Transmission – TheUSART TransmitterThe USART Transmitter is enabled by setting the Transmit Enable (TXEN) bit in theUCSRB Register. When the Transmitter is enabled, the normal port operation of theTxD pin is overridden by the USART and given the function as the Transmitter’s serialoutput. The baud rate, mode of operation and frame format must be set up once beforedoing any transmissions.

If synchronous operation is used, the clock on the XCK pin willbe overridden and used as transmission clock.Sending Frames with 5 to 8Data BitsA data transmission is initiated by loading the transmit buffer with the data to be transmitted. The CPU can load the transmit buffer by writing to the UDR I/O location. Thebuffered data in the transmit buffer will be moved to the Shift Register when the ShiftRegister is ready to send a new frame. The Shift Register is loaded with new data if it isin idle state (no ongoing transmission) or immediately after the last stop bit of the previous frame is transmitted.

When the Shift Register is loaded with new data, it will transferone complete frame at the rate given by the Baud Register, U2X bit or by XCK depending on mode of operation.The following code examples show a simple USART transmit function based on pollingof the Data Register Empty (UDRE) Flag.

When using frames with less than eight bits,the most significant bits written to the UDR are ignored. The USART has to be initializedbefore the function can be used. For the assembly code, the data to be sent is assumedto be stored in Register R16Assembly Code Example(1)USART_Transmit:; Wait for empty transmit buffersbis UCSRA,UDRErjmp USART_Transmit; Put data (r16) into buffer, sends the dataoutUDR,r16retC Code Example(1)void USART_Transmit( unsigned char data ){/* Wait for empty transmit buffer */while ( !( UCSRA & (1<<UDRE)) );/* Put data into buffer, sends the data */UDR = data;}Note:1.

The example codes assumes that the part specific header file is included.The function simply waits for the transmit buffer to be empty by checking the UDREFlag, before loading it with new data to be transmitted. If the Data Register Empty Interrupt is utilized, the interrupt routine writes the data into the buffer.1372486O–AVR–10/04Sending Frames with 9 DataBitsIf 9-bit characters are used (UCSZ = 7), the ninth bit must be written to the TXB8 bit inUCSRB before the Low byte of the character is written to UDR.

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 ninth bit from r17 to TXB8cbiUCSRB,TXB8sbrc r17,0sbiUCSRB,TXB8; Put LSB data (r16) into buffer, sends the dataoutUDR,r16retC Code Example(1)void USART_Transmit( unsigned int data ){/* Wait for empty transmit buffer */while ( !( UCSRA & (1<<UDRE)) );/* Copy ninth 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.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.When 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. When138ATmega8(L)2486O–AVR–10/04ATmega8(L)interrupt-driven data transmission is used, the Data Register empty Interrupt routinemust either write new data to UDR in order to clear UDRE or disable the Data Registerempty Interrupt, otherwise a new interrupt will occur once the interrupt routineterminates.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 completeinterrupt is executed, or it can be cleared by writing a one to its bit location. The TXCFlag is useful in half-duplex communication interfaces (like the RS485 standard), wherea transmitting 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 (provided that global interrupts are enabled).

When the transmit complete interrupt is used,the interrupt handling routine does not have to clear the TXC Flag, this is done automatically when 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.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.

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

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

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

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