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

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

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

The RWWSB in the SPMCSR will be set aslong as the RWW section is busy. During Self-Programming the interrupt vector tableshould be moved to the BLS as described in “Interrupts” on page 57, or the interruptsmust be disabled. Before addressing the RWW section after the programming is completed, the user software must clear the RWWSB by writing the RWWSRE. See “SimpleAssembly Code Example for a Boot Loader” on page 284 for an example.282ATmega1282467M–AVR–11/04ATmega128Setting the Boot Loader LockBits by SPMTo set the Boot Loader Lock bits, write the desired data to R0, write “X0001001” toSPMCSR and execute SPM within four clock cycles after writing SPMCSR. 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 108 and Table 109 for how the different settings of the Boot Loader Bitsaffect the 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 inSPMCSR.

The Z-pointer is don’t care during this operation, but for future compatibility itis recommended to load the Z-pointer with $0001 (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 SPMCSRNote 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 SPMCSRRegister.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 $0001 and set the BLBSET and SPMEN bits in SPMCSR. Whenan LPM instruction is executed within three CPU cycles after the BLBSET and SPMENbits are set in SPMCSR, 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 instruction isexecuted 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 $0000 and setthe BLBSET and SPMEN bits in SPMCSR. When an LPM instruction is executed withinthree cycles after the BLBSET and SPMEN bits are set in the SPMCSR, the value of theFuse Low bits (FLB) will be loaded in the destination register as shown below.

Refer toTable 119 on page 290 for a detailed description and mapping of the Fuse Low bits.Bit76543210RdFLB7FLB6FLB5FLB4FLB3FLB2FLB1FLB0Similarly, when reading the Fuse High bits, load $0003 in the Z-pointer. When an LPMinstruction is executed within three cycles after the BLBSET and SPMEN bits are set inthe SPMCSR, the value of the Fuse High bits (FHB) will be loaded in the destinationregister as shown below. Refer to Table 118 on page 290 for detailed description andmapping of the Fuse High bits.Bit76543210RdFHB7FHB6FHB5FHB4FHB3FHB2FHB1FHB0When reading the Extended Fuse bits, load $0002 in the Z-pointer. When an LPMinstruction is executed within three cycles after the BLBSET and SPMEN bits are set in2832467M–AVR–11/04the SPMCSR, the value of the Extended Fuse bits (EFB) will be loaded in the destination register as shown below.

Refer to Table 117 on page 289 for detailed descriptionand mapping of the Fuse High bits.Bit76543210Rd––––––EFB1EFB0Fuse and Lock bits that are programmed, will be read as zero. Fuse and Lock bits thatare unprogrammed, will be read as one.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. Secondly, the CPU itself can execute instructions incorrectly, if the supply voltagefor executing instructions is too low.Flash corruption can easily be avoided by following these design recommendations (oneis sufficient):1. If there is no need for a Boot Loader update in the system, program the BootLoader Lock bits to prevent any Boot Loader software updates.2.

Keep the AVR RESET active (low) during periods of insufficient power supplyvoltage. This can be done by enabling the internal Brown-out Detector (BOD) ifthe operating voltage matches the detection level. If not, an external low VCCReset Protection circuit can be used. If a Reset occurs while a write operation isin progress, the write operation will be completed provided that the power supplyvoltage is sufficient.3. Keep the AVR core in Power-down Sleep mode during periods of low VCC.

Thiswill prevent the CPU from attempting to decode and execute instructions, effectively protecting the SPMCSR Register and thus the Flash from unintentionalwrites.Programming Time for Flashwhen Using SPMThe calibrated RC Oscillator is used to time Flash accesses.

Table 111 shows the typical programming time for Flash accesses from the CPU.Table 111. SPM Programming Time.SymbolFlash write (page erase, page write,and write lock bits by SPM)Simple Assembly CodeExample for a Boot Loader284Min Programming TimeMax Programming Time3.7 ms4.5 ms;-the routine writes one page of data from RAM to Flash; the first data location in RAM is pointed to by the Y pointer; the first data location in Flash is pointed to by the Z-pointer;-error handling is not included;-the routine must be placed inside the boot space; (at least the Do_spm sub routine).

Only code inside NRWW sectioncan; be read during self-programming (page erase and page write).;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24),; loophi (r25), spmcsrval (r20); storing and restoring of registers is not included in the routine; register usage can be optimized at the expense of code size;-It is assumed that either the interrupt table is moved to theATmega1282467M–AVR–11/04ATmega128Boot; loader section or that the interrupts are disabled..equ PAGESIZEB = PAGESIZE*2;PAGESIZEB is page size in BYTES, notwords.org SMALLBOOTSTARTWrite_page:; page eraseldi spmcsrval, (1<<PGERS) | (1<<SPMEN)call Do_spm; re-enable the RWW sectionldi spmcsrval, (1<<RWWSRE) | (1<<SPMEN)call Do_spm; transfer data from RAM to Flash page bufferldi looplo, low(PAGESIZEB);init loop variableldi loophi, high(PAGESIZEB);not required for PAGESIZEB<=256Wrloop:ldr0, Y+ldr1, Y+ldi spmcsrval, (1<<SPMEN)call Do_spmadiw ZH:ZL, 2sbiw loophi:looplo, 2;use subi for PAGESIZEB<=256brne Wrloop; execute page writesubi ZL, low(PAGESIZEB);restore pointersbci ZH, high(PAGESIZEB);not required for PAGESIZEB<=256ldi spmcsrval, (1<<PGWRT) | (1<<SPMEN)call Do_spm; re-enable the RWW sectionldi spmcsrval, (1<<RWWSRE) | (1<<SPMEN)call Do_spm; read back and check, optionalldi looplo, low(PAGESIZEB);init loop variableldi loophi, high(PAGESIZEB);not required for PAGESIZEB<=256subi YL, low(PAGESIZEB);restore pointersbci YH, high(PAGESIZEB)Rdloop:lpm r0, Z+ldr1, Y+cpse r0, r1jmp Errorsbiw loophi:looplo, 1;use subi for PAGESIZEB<=256brne Rdloop; return to RWW section; verify that RWW section is safe to readReturn:lds temp1, SPMCSRsbrs temp1, RWWSB; If RWWSB is set, the RWW section is notready yetret; re-enable the RWW sectionldi spmcsrval, (1<<RWWSRE) | (1<<SPMEN)call Do_spm2852467M–AVR–11/04rjmp ReturnDo_spm:; check for previous SPM completeWait_spm:lds temp1, SPMCSRsbrc temp1, SPMENrjmp Wait_spm; input: spmcsrval determines SPM action; disable interrupts if enabled, store statusintemp2, SREGcli; check that no EEPROM write access is presentWait_ee:sbic EECR, EEWErjmp Wait_ee; SPM timed sequencests SPMCSR, spmcsrvalspm; restore SREG (to enable interrupts if originally enabled)out SREG, temp2retATmega128 Boot LoaderParametersIn Table 112 through Table 114, the parameters used in the description of the self programming are given.Table 112.

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

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

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

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