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

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

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

The descriptionin this section refers to Figure 80 for details.External clock input from the XCK pin is sampled by a synchronization register to minimize the chance of meta-stability. The output from the synchronization register mustthen pass through an edge detector before it can be used by the transmitter andreceiver. This process introduces a two CPU clock period delay and therefore the maximum external XCK clock frequency is limited by the following equation:f OSCf XCK < ----------4Note that fosc depends on the stability of the system clock source. It is therefore recommended to add some margin to avoid possible loss of data due to frequency variations.Synchronous Clock Operation When Synchronous mode is used (UMSEL = 1), the XCK pin will be used as either clockinput (slave) or clock output (master).

The dependency between the clock edges anddata sampling or data change is the same. The basic principle is that data input (onRxD) is sampled at the opposite XCK clock edge of the edge the data output (TxD) ischanged.Figure 81. Synchronous Mode XCK Timing.UCPOL = 1XCKRxD / TxDSampleUCPOL = 0XCKRxD / TxDSampleThe UCPOL bit UCRSC selects which XCK clock edge is used for data sampling andwhich is used for data change. As Figure 81 shows, when UCPOL is zero the data willbe changed at rising XCK edge and sampled at falling XCK edge. If UCPOL is set, thedata will be changed at falling XCK edge and sampled at rising XCK edge.174ATmega1282467M–AVR–11/04ATmega128Frame FormatsA serial frame is defined to be one character of data bits with synchronization bits (startand stop bits), and optionally a parity bit for error checking.

The USART accepts all 30combinations of the following as valid frame formats:•1 start bit•5, 6, 7, 8, or 9 data bits•no, even or odd parity bit•1 or 2 stop bitsA frame starts with the start bit followed by the least significant data bit. Then the nextdata bits, up to a total of nine, are succeeding, ending with the most significant bit.

Ifenabled, the parity bit is inserted after the data bits, before the stop bits. When a complete frame is transmitted, it can be directly followed by a new frame, or thecommunication line can be set to an idle (high) state. Figure 82 illustrates the possiblecombinations of the frame formats.

Bits inside brackets are optional.Figure 82. Frame FormatsFRAME(IDLE)St01234[5][6][7][8][P]Sp1 [Sp2](St / IDLE)StStart bit, always low.(n)Data bits (0 to 8).PParity bit. Can be odd or even.SpStop bit, always high.IDLENo transfers on the communication line (RxD or TxD). An IDLE line must behigh.The frame format used by the USART is set by the UCSZ2:0, UPM1:0 and USBS bits inUCSRB and UCSRC. The receiver and transmitter use the same setting. Note thatchanging the setting of any of these bits will corrupt all ongoing communication for boththe receiver and transmitter.The USART Character SiZe (UCSZ2:0) bits select the number of data bits in the frame.The USART Parity mode (UPM1:0) bits enable and set the type of parity bit. The selection between one or two stop bits is done by the USART Stop Bit Select (USBS) bit.

Thereceiver ignores the second stop bit. An FE (Frame Error) will therefore only be detectedin the cases where the first stop bit is zero.Parity Bit CalculationThe parity bit is calculated by doing an exclusive-or of all the data bits. If odd parity isused, the result of the exclusive or is inverted. The relation between the parity bit anddata bits is as follows:P even = d n – 1 ⊕ … ⊕ d 3 ⊕ d 2 ⊕ d 1 ⊕ d 0 ⊕ 0P odd = d n – 1 ⊕ … ⊕ d 3 ⊕ d 2 ⊕ d 1 ⊕ d 0 ⊕ 1PevenParity bit using even parityPoddParity bit using odd paritydnData bit n of the character1752467M–AVR–11/04If used, the parity bit is located between the last data bit and first stop bit of a serialframe.USART InitializationThe USART has to be initialized before any communication can take place.

The initialization process normally consists of setting the baud rate, setting frame format andenabling the Transmitter or the Receiver depending on the usage. For interrupt drivenUSART operation, the global interrupt flag should be cleared (and interrupts globally disabled) when doing the initialization.Before doing a re-initialization with changed baud rate or frame format, be sure thatthere are no ongoing transmissions during the period the registers are changed. TheTXC flag can be used to check that the Transmitter has completed all transfers, and theRXC flag can be used to check that there are no unread data in the receive buffer.

Notethat the TXC flag must be cleared before each transmission (before UDR is written) if itis used for this purpose.The following simple USART initialization code examples show one assembly and oneC function that are equal in functionality. 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.Assembly 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<<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<<USBS)|(3<<UCSZ0);}Note:1761. 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”.ATmega1282467M–AVR–11/04ATmega128More 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 code canbe placed directly in the main routine, or be combined with initialization code for otherI/O modules.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 BitA 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 dependingon 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 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”.1772467M–AVR–11/04The function simply waits for the transmit buffer to be empty by checking the UDRE flag,before loading it with new data to be transmitted. If the data register empty interrupt isutilized, the interrupt routine writes the data into the buffer.178ATmega1282467M–AVR–11/04ATmega128Sending Frames with 9 DataBitIf 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.

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

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

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

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