ATmega8 (961730), страница 44

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

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

One section, consisting of the least significant bits, is addressing the words within a page, while the most significant bits areaddressing the pages. This is shown in Figure 103. Note that the page erase and pagewrite operations are addressed independently. Therefore it is of major importance thatthe Boot Loader software addresses the same page in both the page erase and pagewrite operation.

Once a programming operation is initiated, the address is latched andthe Z-pointer can be used for other operations.The only SPM operation that does not use the Z-pointer is Setting the Boot Loader LockBits. The content of the Z-pointer is ignored and will have no effect on the operation. TheLPM instruction does also use the Z-pointer to store the address. Since this instructionaddresses the Flash byte by byte, also the LSB (bit Z0) of the Z-pointer is used.2112486O–AVR–10/04Figure 103.

Addressing the Flash during SPM(1)BIT15ZPCMSBZPAGEMSBZ - REGISTER1 00PCMSBPROGRAMCOUNTERPAGEMSBPCPAGEPAGE ADDRESSWITHIN THE FLASHPCWORDWORD ADDRESSWITHIN A PAGEPROGRAM MEMORYPAGEPAGEINSTRUCTION WORDPCWORD[PAGEMSB:0]:000102PAGEENDNotes:Self-Programming theFlash1. The different variables used in the figure are listed in Table 84 on page 218.2.

PCPAGE and PCWORD are listed in Table 89 on page 222.The Program memory is updated in a page by page fashion. Before programming apage with the data stored in the temporary page buffer, the page must be erased. Thetemporary page buffer is filled one word at a time using SPM and the buffer can be filledeither before the page erase command or between a page erase and a page writeoperation:Alternative 1, fill the buffer before a page erase.•Fill temporary page buffer.•Perform a page erase.•Perform a page write.Alternative 2, fill the buffer after page erase.•Perform a page erase.•Fill temporary page buffer.•Perform a page write.If only a part of the page needs to be changed, the rest of the page must be stored (forexample in the temporary page buffer) before the erase, and then be rewritten. Whenusing alternative 1, the boot loader provides an effective Read-Modify-Write featurewhich allows the user software to first read the page, do the necessary changes, andthen write back the modified data.

If alternative 2 is used, it is not possible to read theold data while loading since the page is already erased. The temporary page buffer canbe accessed in a random sequence. It is essential that the page address used in boththe page erase and page write operation is addressing the same page. See “Simple212ATmega8(L)2486O–AVR–10/04ATmega8(L)Assembly Code Example for a Boot Loader” on page 216 for an assembly codeexample.Performing Page Erase bySPMFilling the Temporary Buffer(Page Loading)To execute page erase, set up the address in the Z-pointer, write “X0000011” toSPMCR and execute SPM within four clock cycles after writing SPMCR. The data in R1and R0 is ignored. The page address must be written to PCPAGE in the Z-register.Other bits in the Z-pointer will be ignored during this operation.•Page Erase to the RWW section: The NRWW section can be read during the pageerase.•Page Erase to the NRWW section: The CPU is halted during the operation.To write an instruction word, set up the address in the Z-pointer and data in R1:R0, write“00000001” to SPMCR and execute SPM within four clock cycles after writing SPMCR.The content of PCWORD in the Z-register is used to address the data in the temporarypage buffer.

The temporary buffer will auto-erase after a page write operation or by writing the RWWSRE bit in SPMCR. It is also erased after a System Reset. Note that it isnot possible to write more than one time to each address without erasing the temporarybuffer.Note:Performing a Page WriteIf the EEPROM is written in the middle of an SPM page Load operation, all data loadedwill be lost.To execute page write, set up the address in the Z-pointer, write “X0000101” to SPMCRand execute SPM within four clock cycles after writing SPMCR. The data in R1 and R0is ignored. The page address must be written to PCPAGE. Other bits in the Z-pointermust be written to zero during this operation.•Page Write to the RWW section: The NRWW section can be read during the pagewrite.•Page Write to the NRWW section: The CPU is halted during the operation.Using the SPM InterruptIf the SPM interrupt is enabled, the SPM interrupt will generate a constant interruptwhen the SPMEN bit in SPMCR is cleared.

This means that the interrupt can be usedinstead of polling the SPMCR Register in software. When using the SPM interrupt, theInterrupt Vectors should be moved to the BLS section to avoid that an interrupt isaccessing the RWW section when it is blocked for reading. How to move the interruptsis described in “Interrupts” on page 44.Consideration While UpdatingBLSSpecial care must be taken if the user allows the Boot Loader section to be updated byleaving Boot Lock bit11 unprogrammed.

An accidental write to the Boot Loader itself cancorrupt the entire Boot Loader, and further software updates might be impossible. If it isnot necessary to change the Boot Loader software itself, it is recommended to programthe Boot Lock bit11 to protect the Boot Loader software from any internal softwarechanges.Prevent Reading the RWWSection During SelfProgrammingDuring Self-Programming (either page erase or page write), the RWW section is alwaysblocked for reading.

The user software itself must prevent that this section is addressedduring the self programming operation. The RWWSB in the SPMCR will be set as longas the RWW section is busy. During Self-Programming the Interrupt Vector table shouldbe moved to the BLS as described in “Interrupts” on page 44, or the interrupts must bedisabled. Before addressing the RWW section after the programming is completed, theuser software must clear the RWWSB by writing the RWWSRE. See “Simple AssemblyCode Example for a Boot Loader” on page 216 for an example.2132486O–AVR–10/04Setting the Boot Loader LockBits by SPMTo set the Boot Loader Lock Bits, write the desired data to R0, write “X0001001” toSPMCR and execute SPM within four clock cycles after writing SPMCR. The onlyaccessible Lock Bits are the Boot Lock Bits that may prevent the Application and BootLoader section from any software update by the MCU.Bit76543210R011BLB12BLB11BLB02BLB0111See Table 78 and Table 79 for how the different settings of the Boot Loader Bits affectthe Flash access.If bits 5..2 in R0 are cleared (zero), the corresponding Boot Lock bit will be programmedif an SPM instruction is executed within four cycles after BLBSET and SPMEN are set inSPMCR.

The Z-pointer is don’t care during this operation, but for future compatibility it isrecommended to load the Z-pointer with 0x0001 (same as used for reading the LockBits). For future compatibility It is also recommended to set bits 7, 6, 1, and 0 in R0 to “1”when writing the Lock Bits. When programming the Lock Bits the entire Flash can beread during the operation.EEPROM Write PreventsWriting to SPMCRNote that an EEPROM write operation will block all software programming to Flash.Reading the Fuses and Lock Bits from software will also be prevented during theEEPROM write operation. It is recommended that the user checks the status bit (EEWE)in the EECR Register and verifies that the bit is cleared before writing to the SPMCRRegister.Reading the Fuse and LockBits from SoftwareIt is possible to read both the Fuse and Lock Bits from software. To read the Lock Bits,load the Z-pointer with 0x0001 and set the BLBSET and SPMEN bits in SPMCR.

Whenan LPM instruction is executed within three CPU cycles after the BLBSET and SPMENbits are set in SPMCR, the value of the Lock Bits will be loaded in the destination register. The BLBSET and SPMEN bits will auto-clear upon completion of reading the LockBits or if no LPM instruction is executed within three CPU cycles or no SPM instructionis executed within four CPU cycles. When BLBSET and SPMEN are cleared, LPM willwork as described in the Instruction set Manual.Bit76543210Rd––BLB12BLB11BLB02BLB01LB2LB1The algorithm for reading the Fuse Low bits is similar to the one described above forreading the Lock Bits. To read the Fuse Low bits, load the Z-pointer with 0x0000 and setthe BLBSET and SPMEN bits in SPMCR. When an LPM instruction is executed withinthree cycles after the BLBSET and SPMEN bits are set in the SPMCR, the value of theFuse Low bits (FLB) will be loaded in the destination register as shown below.

Refer toTable 88 on page 221 for a detailed description and mapping of the fuse low bits.Bit76543210RdFLB7FLB6FLB5FLB4FLB3FLB2FLB1FLB0Similarly, when reading the Fuse High bits, load 0x0003 in the Z-pointer. When an LPMinstruction is executed within three cycles after the BLBSET and SPMEN bits are set inthe SPMCR, the value of the Fuse High bits (FHB) will be loaded in the destination register as shown below.

Refer to Table 87 on page 220 for detailed description andmapping of the fuse high bits.Bit76543210RdFHB7FHB6FHB5FHB4FHB3FHB2FHB1FHB0Fuse and Lock Bits that are programmed, will be read as zero. Fuse and Lock Bits thatare unprogrammed, will be read as one.214ATmega8(L)2486O–AVR–10/04ATmega8(L)Preventing Flash CorruptionDuring periods of low VCC, the Flash program can be corrupted because the supply voltage is too low for the CPU and the Flash to operate properly. These issues are the sameas for board level systems using the Flash, and the same design solutions should beapplied.A Flash program corruption can be caused by two situations when the voltage is too low.First, a regular write sequence to the Flash requires a minimum voltage to operate correctly.

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

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

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

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