Как скачать прошивку из pic24f
Перейти к содержимому

Как скачать прошивку из pic24f

  • автор:

Bootloader для PIC24F16KA102 по RS-485

Проверка подключения RS-485 через преобразователь USB/RS-485
Добрый вечер, форумчане! Я относительно навичек софт-программист, и уж тем более навичек в.

Драйвер для RS-485
сделали кастомную плату rs485, нужно написать драйвер для Windows с поддержкой авто DTR. второй.

Прерывания для RS-485
Доброго времени суток! Помогите решить задачу. Есть интерфейсная 2-х портовая плата RS-485. На ней.

bootloader для atmega8
Пытаюсь разобраться с бутлоадером, но что то плохо получается записывать флэш. #include <avr/io.h>.

BootLoader для AVR32.
Написал BootToodir под ATUC3B0512, вернее смог принять по UART последовательно страницы по 512.

Сообщение от freddi89
Сообщение от raxp

. разумеется. При подаче питания, по-умолчанию, бутлоадер и так готов к приему, следовательно пин, управляющий направлением приема-передачи должен быть сконфигурирован изначально на прием. В рабочем режиме, бутлоадер может активироваться специальной командой.

Как простое костыльное решение: в прошивке, работающей по RS-485 по какому-либо протоколу предусмотреть прием некой оговоренной команды, сбрасывающей МК по RESET-пину через один из свободных пинов. Пришла команда по сети, МК подал на ножку импульс сброса (или через вотчдог, если есть в схеме), МК перевелся в режим загрузки, теперь шлем по сети прошивку, бутлоадер ее кушает и сбрасывает МК по завершении. Если по истечении определенного времени ничего не пришло, бутлоадер грузит старую прошивку. Фактически бутлоадер переписывать не придется.

pic24f serial bootloader

Easy way to implement bootloader for PIC24F families.

INTRODUCTIONOne of the advantages of Microchips PIC micro-controllers with self-programmable enhanced Flashmemory is the ability to implement a bootloader. Thisallows designers to implement applications that can beupdated many times over, potentially extending theapplications useful lifetime.

This application note describes a serial bootloader for16-bit PIC24F devices using the UART module as acommunication channel. The bootloader applicationuses the communication protocols originally outlined inMicrochip Application Note AN851, A Flash Bootloaderfor PIC16 and PIC18 Devices. Some modifications tothe original protocol have been made to maintaincompatibility with the PIC24 architecture. It has alsobeen redesigned to accommodate the current genera-tion of PIC24FJ Flash microcontrollers, as well as thenext generation of PIC24F devices.

Basic OperationFigure 1 summarizes the essential firmware design ofthe bootloader. Data is received through the UARTmodule and passed through the transmit/receiveengine. The engine filters and parses the data, storingthe information into a data buffer in RAM. The com-mand interpreter evaluates the command informationwithin the buffer to determine what should be done(e.g., Is the data written into memory? Is data read frommemory? Does the firmware version need to be read?).Once the operation is performed, reply data is passedback to the transmit/receive engine to be transmittedback to the source, closing the software flow controlloop.

FIGURE 1: BOOTLOADER FUNCTIONAL BLOCK DIAGRAM

COMMUNICATIONSThe microcontrollers UART module is used to receiveand transmit data; it is configured to be compatible withRS-232 communications. The device can be set up inan application to bootload from a computer through itsstandard serial interface. The following defaultcommunication settings are used:

8 Data Bits No Parity 1 Stop Bit Automatic Baud Rate Detection

The baud rate is detected using the UART moduleshardware auto-baud functionality. For more informationon this feature, refer to the UART chapter of thePIC24F Family Reference Manual (Section 21.UART (DS39708)).

Author: Brant IveyMicrochip Technology Inc.

* If present on target device. See text for details.

A Serial Bootloader for PIC24F Devices 2008 Microchip Technology Inc. DS01157A-page 1

THE RECEIVE/TRANSMIT BUFFERAll data is moved through a buffer (referred to as thereceive/transmit buffer). The buffer is a maximum of261 bytes deep. This is the maximum packet lengthsupported by the protocol. Figure 2 shows an exampleof the mapping of the buffer withinPIC24FJXXXGAXXX devices.

A useful feature of the receive/transmit buffer is that itmaintains the data from the last received packet. Thisallows commands to be easily repeated by sending anempty packet (a packet with no command code ordata). If an empty packet is received, the data in thebuffer will be reused as if it were just received.

FIGURE 2: DATA MEMORY USAGE ON PIC24FJXXXGAXXX DEVICES

COMMAND INTERPRETERThe command interpreter decodes and executesvarious protocol commands. A complete list of the com-mands is provided in Appendix A: PIC24F SerialBootloader Command Summary. The commandsallow for read, write and erase operations on all types ofnonvolatile memory: program Flash, data EEPROM andConfiguration bits. Additionally, there are commands forspecial operations, such as repeating the last command,replicating the data and resetting the device.

PROGRAM MEMORY USAGEThe bootloader requires between 2 Kbytes and3.5 Kbytes of program memory, depending on the con-figured feature set and compiler optimization. In defaultconfiguration, the bootloader is designed so that it canbe placed anywhere in memory; by default it is locatedstarting at address 000400h (shown in Figure 3).

The bootloader should not be placed in the same512-byte page of memory as the interrupt vectors orConfiguration Words. This is to allow the bootloader tomodify these locations without erasing itself. If possible,the bootloader should be placed in a hardware protectedboot block area on devices which support this feature.The boot block can be protected from device self writesand erases so that the bootloader will not be at risk ofcorrupting itself. Software block protection is provided inthe bootloader to provide this functionality for devicesthat do not have built-in boot block protection.

FIGURE 3: PROGRAM MEMORY MAP FOR THE BOOTLOADER IN PIC24FJ128GA0XX DEVICES

Note: The command set is designed to supportfuture devices and not all devicesimplement all types of memory. Com-pile-time options are provided to disableunsupported commands to save codespace. Be sure to check which types ofmemory are implemented on the devicebeing used and set the configurationaccordingly.

User Code Reset

Note: Memory areas not shown to scale.

Bootloader Time-out Value

Available forApplication Code

Flash Configuration Words

for Application Code

157FChDS01157A-page 2 2008 Microchip Technology Inc.

RESET VECTORSTo ensure that the bootloader is always accessible, it isnecessary to run the bootloader first after a deviceReset. Therefore, the devices hardware Reset vector(addresses 000000h and 000002h) is used to store thebootloaders Reset vector. If the bootloaders Resetvector is ever overwritten, the device would no longerbe able to enter Boot mode. For the bootloader to call the user application, it muststore the user applications Reset vector in memory.The constant, USER_PROG_RESET, defined inconfig.h, tells the bootloader where the Reset vectoris remapped. When a user application is being pro-grammed, the bootloader will automatically relocatethe user Reset vector from 000000h to the locationdefined in this constant. The bootloader will read thislocation on device start-up and branch to the addressstored here. When using boot block protection, it is necessary tolocate the user application Reset vector outside of thehardware boot block, so that it can be erased and writ-ten by the bootloader. Optionally, the application linkerscript can be modified to remove the Reset vector. Ifthis is done, the user application will need to manuallyplace its own Reset vector in the remapped location.

INTERRUPT VECTORSBecause the Interrupt Vector Tables (IVTs) are locatedin the same page of memory as the devices Reset vec-tor, it is good practice to remap the vector tables to anew location, so that the Reset vector does not need to

be erased to update interrupt locations. Remapping theIVTs is required when hardware boot block protection isenabled. This is done by modifying bootloader andapplication linker scripts. The bootloader linker scriptentry for the interrupt tables indicates what addresseswill be placed in the IVT. The entries for the interrupts being used should bemodified to indicate the locations in the user applicationof the interrupt functions, so that the service routine canbe called directly (Option A in Figure 4). If the locationsof the interrupts are not known at the time the boot-loader is compiled, change the addresses in the linkerscript to locations where branch instructions can beplaced as part of user code. The user applicationshould then place branch instructions in these locationsto vector to the interrupt routines (Option B in Figure 4).Note that this method increases the interrupt latency bytwo instruction cycles to allow for the extra branchinstruction to execute.The application linker script must be modified toremove the interrupt vectors, to prevent the bootloaderfrom erasing the remapped interrupt vectors. Alterna-tively, you can enable the Bootloader mode whichprevents the vector table from being erased, so that theuser application linker script does not need to bemodified.Example linker scripts where these modifications havebeen done have been provided in the folder, gld. Mod-ified linker examples are shown in Appendix C:Example Linker Scripts for Use with the PIC24FBootloader.

FIGURE 4: TECHNIQUES FOR REMAPPING INTERRUPT VECTORS

Note: Memory areas not shown to scale.

Reset Vectors 00004h

ISR for Interrupt X 01004h

Interrupt X Vector:1004h Fixed

Reset Vectors 00004h

GOTO 0x1100 01004h

Interrupt X Vector:1004h Fixed

ISR for Interrupt X 01100h

Option A: Direct Mapping to ISR Option B: Mapping an ISR through a Branch Instruction

(Fixed Location) (Fixed Instruction Location)

(Variable ISR Location) 2008 Microchip Technology Inc. DS01157A-page 3

Communication ProtocolThe bootloader employs a basic communication proto-col that is robust, simple to use and easy to implement.This protocol was originally specified in AN851. It hasbeen slightly modified to improve compatibility with the16-bit PIC24F architecture by increasing the maximumpacket size.

PACKET FORMATAll data that is transmitted to or from the device followsthe basic packet format:

[. ]where each represents a byte and [. ] representsthe data field. The start of a packet is indicated by twoStart of TeXt control characters (), and is termi-nated by a single End of TeXt control character(). The last byte before the is always achecksum, which is the twos complement of the LeastSignificant Byte of the sum of all data bytes. The datafield is limited to 261 data bytes. This length is used inorder to allow a full row of data to be received at a time.If more bytes are received, then the packet is ignoreduntil the next pair is received.

COMMUNICATION CONTROL CHARACTERSThree control characters have special meaning. Two ofthem, and , are introduced above. Thelast character not shown is the Data Link Escape,. Table 1 provides a summary of the threecontrol characters.

TABLE 1: CONTROL CHARACTERS

The is used to identify a value that could beinterpreted in the data field as a control character.Within the data field, the bootloader will always acceptthe byte following a as data, and will alwayssend a before any of the three control charac-ters. For example, if a byte of value, 55h, is transmittedas part of the data field, rather than as the control character, the character is insertedbefore the . This is called byte stuffing.

COMMANDSThe data field for each packet contains one commandand its associated data. The commands are detailed inAppendix A: PIC24F Serial Bootloader CommandSummary.

COMMAND RESPONSE LATENCYFlow control is built into the protocol. Thus, for everyreceived command (except RESET), there is aresponse. If there is no response, then one (or more) ofthe following has happened:

the data was corrupted (bad checksum) the packet was never received the data field was too long a RESET was executedSo, how long do you wait before deciding a problemhas occurred? The response latency (Figure 5) isdependent on the amount of data sent, the commandbeing executed and the clock frequency. For read com-mands, the latency is highly dependent on the clockfrequency and the size of the packet. For a smallpacket at high frequency, the response is almost imme-diate, typically about a few microseconds. For largepackets, the latency could be hundreds of micro-seconds. In general, read commands require very littletime compared to write commands. Write commandsare mostly dependent on internally timed write cycles.

FIGURE 5: RECEIVE TO TRANSMIT LATENCY

Note: Although the protocol supports 261 bytesof data, the specific device that containsthe bootloader firmware may not have asufficiently large data memory to supportthe largest packet size. Refer to the datasheet for the particular device for moreinformation.

Control Value Description

55h Start of TeXt 04h End of TeXt 05h Data Link Escape

Note: Control characters are not considereddata and are not included in thechecksum.

DelayDS01157A-page 4 2008 Microchip Technology Inc.

AN1157BOOTING A DEVICE

Entering and Leaving Boot ModeWith the bootloader firmware loaded, there are two dis-tinct modes of operation: Boot mode and User mode. A1-byte value should be placed at the location specifiedby DELAY_TIME_ADDR, which is defined in config.h.A value of FFh indicates that the bootloader will remainin Boot mode and not switch to User mode without acommand to do so. Thus, a new part with no valid usercode will automatically enter Boot mode until user codeis successfully programmed. Any other value indicatesa number of seconds the bootloader will wait prior toswitching to User mode. A value of 0 will immediatelyrun User mode. The delay time will not be written intoFlash by the bootloader until the VERIFY_OK com-mand is sent. This command indicates to the boot-loader that the user application has been successfullyprogrammed, and is done in order to prevent possiblebootloader lockout.To leave Boot mode, a device Reset (hardware or soft-ware) must be initiated or a RESET command must besent.

Program Memory OperationsThe bootloader supports reads, writes and erases toFlash memory. Depending on the command beingused, there is a minimum amount of data which can bereferenced. Reading Flash is done at the instructionlevel. Each instruction has three bytes of program dataand one byte of zeroes, called the phantom byte, fora total of four bytes. Write operations are performed in64 instruction blocks called rows (256 bytes). Eraseinstructions are performed in blocks of 8 rows calledpages (2048 bytes). For detailed information on thePIC24F Flash program memory, refer to the PIC24Fprogram memory section in the PIC24F FamilyReference Manual or device data sheets.When programming memory on PIC24F devices, firstthe page needs to be erased. Most locations in Flashoperate such that erase operations set bits andprogram operations can only clear bits. Therefore, it isnot recommended to write to a location multiple timeswithout erasing. Additionally, this means that it is notpossible to recover from a situation where the boot-loader is partially or completely corrupted by writes orerases to the memory space it occupies. For thisreason, it is recommended to use either software orhardware boot block protection.

Data EEPROM OperationsSome PIC24F devices have built-in data Flash memoryEEPROM. The bootloader allows data Flash to be readand erased at a word level, 2 bytes at a time. Erasesare done on a word level prior to performing a write. Not all devices have data EEPROM. The functions thatsupport this can be removed through the bootloaderconfiguration at compile time.

Device ConfigurationPIC24F devices implement device configuration in oneof two ways: Flash Configuration Words and Configu-ration bits. Note that having access to the deviceconfiguration, though useful, is potentially dangerous.If the configuration is changed to a mode not supportedin the application, such as switching from a high-speedcrystal to the LPRC oscillator, it will cause the systemto function incorrectly, and in some cases, break thebootloaders ability to fix the configuration. For thisreason, care should be taken when performingconfiguration changes.

FLASH CONFIGURATION WORDSDevices with Flash Configuration Words store theirconfiguration information in the last few instructions inuser program memory. These values are copied intovolatile registers in the configuration memory spacewhen the part resets. Since they are a part of usermemory, a page erase performed on the final page ofFlash memory also erases the device configuration. Ifthe Flash Configuration Words are changed during runtime, the device continues to run using its originalconfiguration until a Reset occurs. The PIC24F serial bootloader treats the configurationinformation on these devices as normal user memory,and programs it along with of the last row of Flashmemory. A bootloader configuration option is providedto protect the last page of memory from erases andwrites to prevent configuration corruption.

CONFIGURATION BITSDevices using Configuration bits implement deviceconfiguration in 8-bit registers in the configuration mem-ory space, starting at address F80000h. Configurationbits are read and written in single bits and do not need tobe erased prior to writing. However, some of the Config-uration bits are unidirectional bits, and cannot beself-programmed back to a 1 if they are set to 0. Anexample is any of the code protection bits, which cannotbe disabled using device self-programming. For devices with Configuration bits, configurationinformation is read and written separately from Flashprogram memory with separate commands. Thesecommands can optionally be removed from thebootloader for devices that use Flash ConfigurationWords instead of Configuration bits to save programspace.

Note: The bootloader will not wait the correctamount of time before entering User modeif the User mode instruction speed (FCY) isnot defined correctly. 2008 Microchip Technology Inc. DS01157A-page 5

AN1157WRITING APPLICATION CODEThe bootloader operates as a separate entity, whichmeans that an application can be developed with verylittle concern about what the bootloader is doing. Thisis as it should be; the bootloader should be dormantcode until an event initiates a boot operation. Underideal circumstances, bootloader code should never berunning during an applications intended normal opera-tion. When developing an application with a residentbootloader, some basic principles must be kept in mind.

Remapped VectorsReset and interrupt vectors for the user application areremapped outside of the normal vector space. TheReset vector for a user application should be left ataddress 00h. The bootloader will automatically take thevalue being programmed to this address and relocate itto the user Reset vector location specified in theconfiguration file.The interrupt Reset vectors, which are relocated usingthe bootloader linker script, can be used in two ways:by pointing directly to the address of an interrupt rou-tine with a known address when the bootloader is beingcompiled or by pointing to a location with a GOTOinstruction that will call the proper interrupt routine (seeFigure 4). This can be done either by modifying theuser application linker script or by creating a constantat the correct locations in memory that contain thecorrect opcode for the GOTO instruction.

Bootloader Re-EntryIf it is necessary to re-enter Boot mode from the appli-cation, this can be done in two ways. Either the part canbe reset using a RESET instruction or external Reset, orthe application code can branch to the start location ofthe bootloader. If it is desirable to maintain the currentSFR values, using the branch option over a Reset maybe preferable. Note that any SFRs that are used by thebootloader will still be modified by the bootloadersoperation.When entering Boot mode by branching to the start ofthe bootloader, the Reset indicator bits in the RCONregister on the device should be cleared in user code.

The bootloader reads these bits to determine if Bootmode entry is the result of a device Reset or if it wasintentionally called by the user. If the bootloader isentered through the user code, it will ignore the valueof the bootloader entry delay and stay in Boot mode.

EXAMPLE SOFTWAREThe Microchip PIC24F Quick Programmer (P24QP) isa simple application designed to run on a WindowsPC as a device programmer. It is provided along withthe PIC24F serial bootloader to perform basic deviceprogramming operations over a serial RS-232 inter-face. This application can be used as an example onwhich to base custom programmers. An overview of itslogic design is provided in Appendix D: P24QPApplication Flow Diagrams.

Selecting a DeviceWhen P24QP first launches, the device selectiondialog box, seen in Figure 6, will appear. This boxallows the user to either manually select what devicewill be used or allow the program to automaticallydetect a device when connecting.

FIGURE 6: DEVICE SELECTION

The Main ToolbarThe main toolbar (Figure 7) provides basic commandsand information about the device.

КАК ПРОШИТЬ PIC КОНТРОЛЛЕР

В данной статье мы разберемся, как же прошить pic-контроллер, на примере металлоискателя Малыш FM. Для достижения данной цели нам потребуется:

1) Компьютер, в котором есть COM порт (ноутбуки не подходят).

3) Прошивающий софт.

Начнем разбираться по порядку.

Поиск схемы программатора провел по буржуйским сайтам. В итоге нашёл вот эту схему, развел под нее плату. Схема программатора:

Для более качественного просмотра схемы кликните на изображение. Единственный элемент управления в данной схеме – это переключатель S1, которым включается режим высоковольтного программирования. Хочу заметить то, что в данной схеме программатора общий провод схемы ни в коем случае нельзя объединять с 5 выводом (GND) COM порта. У меня получилась вот такая штуковина.

Печатная плата прошивки pic-контроллеров

При подключении программатора к COM порту через удлиняющий кабель, длина последнего не должна превышать 0,5 метра. Прошивающего софта в Интернете навалом, но решил использовать IC-Prog – бесплатная программа. Последняя версия 1.06С от 05.04.2011. На официальном сайте можно скачать и драйвера IC-Prog NT/2000 (не думаю, что кто-то ещё пользуется 98-ми форточками или миллениумом). Если уж хочется поковыряться в данной софтине, то там же можно качнуть русский help. Итак, скачали, разархивировали все в одну папку. Запускаем экзешник, и лезем в настройки программатора Настройки>>Программатор. У меня они выглядят следующим образом.

Далее выполняем настройку самой программы Настройки>>Опции, где важны следующие закладки.

прошивка pic-контроллера 2

константа pic-контроллера 1

прошивка pic-контроллера 3

Когда все будет настроено, приступаем к самому процессу прошивки.

Прошивка pic-контроллера

У контроллера PIC12F629 на заводе записана калибровочная константа внутреннего тактового генератора. Ее желательно сохранить, а то вдруг припрет использовать микросхему в другом девайсе, в котором нет кварца. Для этого в IC-Prog выбираем тип контроллера и нажимаем кнопку «Читать микросхему». Константу ищем здесь.

мк1

Теперь выбираем файл прошивки Файл>>Открыть файл. В итоге все будет выглядеть вот так.

мк-2

Небольшое отступление по поводу конфигурации (правая часть окна). Значение конфигурационных битов прописано в даташите на данный контроллер в разделе 9.1, русский перевод качать отсюда www.microchip.ru. Галочки напротив битов конфигурации в IC-Prog означают установку бита в 0. Не трогайте состояние бита MCLR если это не предусмотрено прошивкой! Все значения конфигурации прописываются при написании прошивки. Итак, продолжим. Загрузили прошивку, теперь нажимаем кнопку «Программировать микросхему» и пойдет процесс прошивки. На такой вопрос отвечать «Нет», иначе затрется калибровочная константа.

прошивка pic-контроллера 5

Осталось дождаться вот такой надписи.

прошивка pic-контроллера 6

А у кого нет COM порта, то можно прикупить такую штуковину или просто собрать ее самому.

программирование контроллера

Объяснил как сумел – думаю всем всё понятно. Если появились вопросы – пишите на форум. Рисунок печатной платы программатора и схему в формате SPL7 качаем здесь. Автор: skateman.

Как прошить микроконтроллер PIC?

Как прошить микроконтроллер PIC?

Если вы уже собрали USB программатор PIC своими руками, то пора научиться им пользоваться. Для этого нам необходимо установить программную оболочку "PICkit 2 Programmer", которая разрабатывалась специально для управления программатором PICkit2.

Для работы программы требуется «.NET Framework». Если этот пакет не установлен на компьютере, то его нужно установить. Также можно воспользоваться дистрибутивом "PICkit 2 Programmer" с интегрированным пакетом – PicKit 2 V2.61 Install with .NET Framework. Скачать его можно здесь.

Итак, если программа установлена, приступим к изучению её возможностей.

Устанавливаем микроконтроллер в панель программации, подключаем программатор к компьютеру и запускаем "PICkit 2 Programmer".

Программирование микроконтроллера PIC16F628A

При запуске программа производит опрос программатора и автоматически определяет тип программируемого микроконтроллера по идентификационным битам (так называемому device ID). Внимание! Микросхемы семейства Baseline, а также микросхемы EEPROM и KeeLOG не имеют device ID. Чтобы программа смогла работать с этими микросхемами, нужно выбрать конкретное изделие через меню "Device Family".

Программатор найден и подключен

Если вместо такой дружелюбной картинки покажется вот такая.

Программатор не подключен!

. то нужно проверить корректно ли подключен usb-кабель, и через меню "Tools" – "Check Communication" произвести переподключение устройства.

Открытие файла с прошивкой.

Чтобы записать программу МК в его память, необходимо выбрать в меню пункт "File" — "Import Hex".

Пункт "File" - "Import Hex"

Затем выбрать в открывшемся окне нужный файл прошивки.

Выбор .hex файла прошивки

После этого в окне памяти программ (Program Memory) и данных (EEPROM Data) отобразится содержимое .hex файла.

Окна памяти программ и данных

Запись программы в МК.

Теперь можно программировать МК. Для этого жмём кнопку "Write". Процесс записи занимает 3 — 5 секунд.

Запись программы в микроконтроллер

Об успешном выполнении процедуры записи уведомит надпись "Programming Successful".

Программирование завершено успешно!

Для большей уверенности можно провести процедуру проверки. При нажатии на кнопку "Verify" программа сравнивает данные hex-файла и данные, записанные в МК. Если верификация прошла успешно, то в окне сообщений появится надпись "Verification Successful".

Внимание! Если вы прошиваете микроконтроллеры PIC12F675, PIC12F629 и аналогичные с внутренним тактовым генератором, то при верификации может выскакивать ошибка. Дело в том, что PICkit2 Programmer (версии 6.21) сохраняет калибровочную константу, а затем записывает её в последнюю ячейку памяти МК. Понятно, что исходный файл прошивки и записанные данные в памяти будут отличаться. О калибровочной константе будет рассказано далее.

Быстрые кнопки.

Кнопка "Auto Import Hex + Write Device" понравиться тем, кто хочет "загонять прошивку" в МК нажатием одной кнопки. Один щелчок и программа предложит выбрать файл прошивки, а затем незамедлительно запишет её в МК.

Кнопка Auto Import Hex + Write Device

Кнопка "Read Device + Export Hex File" выполняет обратную функцию — производит считывание данных с МК и предлагает сохранить файл прошивки в .hex файл.

Кнопка Read Device + Export Hex File

Изменение битов конфигурации.

Биты конфигурации задают основные параметры работы МК. Это и тип генератора (кварц, RC-цепь), включение/отключение так называемого "сторожевого таймера", установка защиты от считывания памяти программ и некоторые другие. Как правило, при написании алгоритма работы МК (программы) прописываются значения, которые нужно записать в биты конфигурации. При "прошивке" программная оболочка берёт данные о конфигурации из самого файла прошивки и принудительно указывать эти данные не требуется.

Но, нам, как начинающим не будет лишним знать, как можно просмотреть или изменить конкретные биты конфигурации. Для этого щёлкаем по надписи "Configuration". Откроется окно редактирования битов конфигурации.

Окно редактирования битов конфигурации

Если нужно поменять 0 на 1, то меняем – жмём "Save". Естественно, менять надо осознанно. Повторяю, при использовании готового файла прошивки менять ничего не надо, программа сделает всё автоматически.

Выбор модели микроконтроллера.

Микроконтроллеры бывают разные. Поэтому при программировании МК бывает необходимость указать конкретную модель микроконтроллера. При выборе пункта меню "Device Family" выпадает список семейств микроконтроллеров. Есть среди этого списка и микросхемы памяти EEPROM.

Выбор типа микроконтроллера

В отличие от микроконтроллеров, микросхемы памяти EEPROM не определяются автоматически по команде "Tools" – "Check Communication". Поэтому при считывании/записи микросхем EEPROM в программе необходимо указать маркировку микросхемы.

В меню выбираем пункт "Device Family" – "EEPROMS" – "24LC".

Далее выбираем конкретную марку микросхемы в выпадающем списке "-Select Part-". Как видим, у нас микросхема 24LC08B (аналоги 24C08, 24WC08L и др.).

Выбираем тип микросхемы EEPROM

Чтобы считать данные с микросхемы EEPROM жмём "Read". Если в памяти записаны данные, то в окне "Program Memory" значения обновятся.

Считывание данных с микросхемы EEPROM

Кнопки "Write" (считать), "Erase" (стереть) выполняют соответствующие функции.

Калибровочная константа.

Как известно, для работы микроконтроллера требуется тактовый генератор. Элементом, который задаёт частоту работы этого генератора, может быть внешний кварцевый резонатор, RC — цепь. Но среди микроконтроллеров PIC есть такие, которые содержат необходимые задающие цепи внутри самой микросхемы. К таким МК относятся, например PIC12F629, PIC12F675.

На заводе в память таких микроконтроллеров записывается специальная константа, которая задаёт параметры встроенного генератора на 4 МГц. Эта калибровочная константа вида 34хх записывается в последнюю ячейку памяти программ по адресу 0x3FF.

При программировании микроконтроллера эту константу легко стереть. И хоть PICkit2 Programmer версии 2.61 автоматически сохраняет эту константу и затем записывает её при программации, не лишним будет записать значение константы OSCCAL.

Значение калибровочной константы микроконтроллера

При необходимости константу легко указать вручную. Для этого в меню выбираем пункт "Tools" – "OSCCAL" – "Set Manually".

Ручная установка константы OSCCAL

В поле "OSCCAL value" указываем ранее записанное значение константы. Жмём кнопку "Set" (установить).

Теперь, когда вы знакомы с основными возможностями PICkit2 Programmer, можно смело начать сборку какого-нибудь устройства на микроконтроллере, например, RGB-светильника на PIC12F629/675.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *