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

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

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

Interrupts, subroutine callsand returns will need five, seven, or nine clock cycles more than specified in the instruction set manual for one, two, and three wait-states.172467M–AVR–11/04The five different addressing modes for the data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment.

Inthe Register file, registers R26 to R31 feature the indirect addressing pointer registers.The direct addressing reaches the entire data space.The Indirect with Displacement mode reaches 63 address locations from the baseaddress given by the Y- or Z-register.When using register indirect addressing modes with automatic pre-decrement and postincrement, the address registers X, Y, and Z are decremented or incremented.The 32 general purpose working registers, 64 I/O registers, and the 4096 bytes of internal data SRAM in the ATmega128 are all accessible through all these addressingmodes.

The Register file is described in “General Purpose Register File” on page 10.Figure 9. Data Memory MapMemory Configuration AData Memory32 Registers64 I/O Registers160 Ext I/O Reg.Memory Configuration BData Memory$0000 - $001F$0020 - $005F$0060 - $00FF$0100Internal SRAM(4096 x 8)32 Registers64 I/O RegistersInternal SRAM(4000 x 8)$0FFF$1000$10FF$1100External SRAM(0 - 64K x 8)External SRAM(0 - 64K x 8)$FFFF18$0000 - $001F$0020 - $005F$0060$FFFFATmega1282467M–AVR–11/04ATmega128Data Memory Access TimesThis section describes the general access timing concepts for internal memory access.The internal data SRAM access is performed in two clkCPU cycles as described in Figure10.Figure 10. On-chip Data SRAM Access CyclesT1T2T3clkCPUAddressAddress validCompute AddressWriteDataWRReadDataRDMemory access instructionEEPROM Data MemoryNext instructionThe ATmega128 contains 4K bytes of data EEPROM memory.

It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has anendurance of at least 100,000 write/erase cycles. The access between the EEPROMand the CPU is described in the following, specifying the EEPROM Address Registers,the EEPROM Data Register, and the EEPROM Control Register.“Memory Programming” on page 288 contains a detailed description on EEPROM programming in SPI, JTAG, or Parallel Programming modeEEPROM Read/Write AccessThe EEPROM access registers are accessible in the I/O space.The write access time for the EEPROM is given in Table 2. A self-timing function, however, lets the user software detect when the next byte can be written.

If the user codecontains instructions that write the EEPROM, some precautions must be taken. Inheavily filtered power supplies, VCC is likely to rise or fall slowly on Power-up/down. Thiscauses the device for some period of time to run at a voltage lower than specified asminimum for the clock frequency used. See “Preventing EEPROM Corruption” on page23. for details on how to avoid problems in these situations.In order to prevent unintentional EEPROM writes, a specific write procedure must be followed. Refer to the description of the EEPROM Control Register for details on this.When the EEPROM is read, the CPU is halted for four clock cycles before the nextinstruction is executed.

When the EEPROM is written, the CPU is halted for two clockcycles before the next instruction is executed.EEPROM Address Register –EEARH and EEARLBitRead/WriteInitial Value15141312111098––––EEAR11EEAR10EEAR9EEAR8EEARHEEAR7EEAR6EEAR5EEAR4EEAR3EEAR2EEAR1EEAR0EEARL76543210RRRRR/WR/WR/WR/WR/WR/WR/WR/WR/WR/WR/WR/W0000XXXXXXXXXXXX• Bits 15..12 – Res: Reserved Bits192467M–AVR–11/04These are reserved bits and will always read as zero.

When writing to this address location, write these bits to zero for compatibility with future devices.• Bits 11..0 – EEAR11..0: EEPROM AddressThe EEPROM Address Registers – EEARH and EEARL – specify the EEPROMaddress in the 4K bytes EEPROM space. The EEPROM data bytes are addressed linearly between 0 and 4096.

The initial value of EEAR is undefined. A proper value mustbe written before the EEPROM may be accessed.EEPROM Data Register –EEDRBit7654321MSB0LSBRead/WriteR/WR/WR/WR/WR/WR/WR/WR/WInitial Value00000000EEDR• Bits 7..0 – EEDR7.0: EEPROM DataFor the EEPROM write operation, the EEDR Register contains the data to be written tothe EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the EEDR contains the data read out from the EEPROM at the address given byEEAR.EEPROM Control Register –EECRBit76543210––––EERIEEEMWEEEWEEERERead/WriteRRRRR/WR/WR/WR/WInitial Value000000X0EECR• Bits 7..4 – Res: Reserved BitsThese bits are reserved bits in the ATmega128 and will always read as zero.• Bit 3 – EERIE: EEPROM Ready Interrupt EnableWriting EERIE to one enables the EEPROM Ready Interrupt if the I-bit in SREG is set.Writing EERIE to zero disables the interrupt. The EEPROM Ready interrupt generates aconstant interrupt when EEWE is cleared.• Bit 2 – EEMWE: EEPROM Master Write EnableThe EEMWE bit determines whether setting EEWE to one causes the EEPROM to bewritten.

When EEMWE is written to one, writing EEWE to one within four clock cycleswill write data to the EEPROM at the selected address. If EEMWE is zero, writing EEWEto one will have no effect. When EEMWE has been written to one by software, hardwareclears the bit to zero after four clock cycles. See the description of the EEWE bit for anEEPROM write procedure.• Bit 1 – EEWE: EEPROM Write EnableThe EEPROM Write Enable Signal EEWE is the write strobe to the EEPROM.

Whenaddress and data are correctly set up, the EEWE bit must be set to write the value intothe EEPROM. The EEMWE bit must be set when the logical one is written to EEWE,otherwise no EEPROM write takes place. The following procedure should be followedwhen writing the EEPROM (the order of steps 3 and 4 is not essential):1. Wait until EEWE becomes zero.2.

Wait until SPMEN in SPMCSR becomes zero.3. Write new EEPROM address to EEAR (optional).4. Write new EEPROM data to EEDR (optional).20ATmega1282467M–AVR–11/04ATmega1285. Write a logical one to the EEMWE bit while writing a zero to EEWE in EECR.6. Within four clock cycles after setting EEMWE, write a logical one to EEWE.The EEPROM can not be programmed during a CPU write to the Flash memory. Thesoftware must check that the Flash programming is completed before initiating a newEEPROM write. Step 2 is only relevant if the software contains a boot loader allowingthe CPU to program the Flash. If the Flash is never being updated by the CPU, step 2can be omitted. See “Boot Loader Support – Read-While-Write Self-Programming” onpage 275 for details about boot programming.Caution: An interrupt between step 5 and step 6 will make the write cycle fail, since theEEPROM Master Write Enable will time-out.

If an interrupt routine accessing theEEPROM is interrupting another EEPROM access, the EEAR or EEDR Register will bemodified, causing the interrupted EEPROM access to fail. It is recommended to havethe global interrupt flag cleared during the four last steps to avoid these problems.When the write access time has elapsed, the EEWE bit is cleared by hardware. Theuser software can poll this bit and wait for a zero before writing the next byte. WhenEEWE has been set, the CPU is halted for two cycles before the next instruction isexecuted.• Bit 0 – EERE: EEPROM Read EnableThe EEPROM Read Enable Signal EERE is the read strobe to the EEPROM. When thecorrect address is set up in the EEAR Register, the EERE bit must be written to a logicone to trigger the EEPROM read. The EEPROM read access takes one instruction, andthe requested data is available immediately. When the EEPROM is read, the CPU ishalted for four cycles before the next instruction is executed.The user should poll the EEWE bit before starting the read operation.

If a write operationis in progress, it is neither possible to read the EEPROM, nor to change the EEARRegister.The calibrated Oscillator is used to time the EEPROM accesses. Table 2 lists the typicalprogramming time for EEPROM access from the CPU.Table 2. EEPROM Programming TimeSymbolNumber of Calibrated RCOscillator Cycles(1)Typ Programming TimeEEPROM Write (from CPU)84488.5 msNote:1. Uses 1 MHz clock, independent of CKSEL-fuse settings.212467M–AVR–11/04The following code examples show one assembly and one C function for writing to theEEPROM. The examples assume that interrupts are controlled (e.g., by disabling interrupts globally) so that no interrupts will occur during execution of these functions.

Theexamples also assume that no flash boot loader is present in the software. If such codeis present, the EEPROM write function must also wait for any ongoing SPM command tofinish.Assembly Code ExampleEEPROM_write:; Wait for completion of previous writesbic EECR,EEWErjmp EEPROM_write; Set up address (r18:r17) in address registerout EEARH, r18out EEARL, r17; Write data (r16) to data registerout EEDR,r16; Write logical one to EEMWEsbi EECR,EEMWE; Start eeprom write by setting EEWEsbi EECR,EEWEretC Code Examplevoid EEPROM_write(unsigned int uiAddress, unsigned char ucData){/* Wait for completion of previous write */while(EECR & (1<<EEWE));/* Set up address and data registers */EEAR = uiAddress;EEDR = ucData;/* Write logical one to EEMWE */EECR |= (1<<EEMWE);/* Start eeprom write by setting EEWE */EECR |= (1<<EEWE);}22ATmega1282467M–AVR–11/04ATmega128The next code examples show assembly and C functions for reading the EEPROM.

Theexamples assume that interrupts are controlled so that no interrupts will occur duringexecution of these functions.Assembly Code ExampleEEPROM_read:; Wait for completion of previous writesbic EECR,EEWErjmp EEPROM_read; Set up address (r18:r17) in address registerout EEARH, r18out EEARL, r17; Start eeprom read by writing EEREsbi EECR,EERE; Read data from data registerinr16,EEDRretC Code Exampleunsigned char EEPROM_read(unsigned int uiAddress){/* Wait for completion of previous write */while(EECR & (1<<EEWE));/* Set up address register */EEAR = uiAddress;/* Start eeprom read by writing EERE */EECR |= (1<<EERE);/* Return data from data register */return EEDR;}EEPROM Write During Powerdown Sleep ModeWhen entering Power-down sleep mode while an EEPROM write operation is active, theEEPROM write operation will continue, and will complete before the write access timehas passed.

However, when the write operation is completed, the Oscillator continuesrunning, and as a consequence, the device does not enter Power-down entirely. It istherefore recommended to verify that the EEPROM write operation is completed beforeentering Power-down.Preventing EEPROMCorruptionDuring periods of low VCC, the EEPROM data can be corrupted because the supply voltage is too low for the CPU and the EEPROM to operate properly. These issues are thesame as for board level systems using EEPROM, and the same design solutions shouldbe applied.An EEPROM data corruption can be caused by two situations when the voltage is toolow. First, a regular write sequence to the EEPROM requires a minimum voltage tooperate correctly.

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

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

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

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