Download mplab ide

Содержание

Помощь новичкам или быстрый старт с MPLAB IDE.

Привет новичкам и всем, кто только только столкнулся с миром микроконтроллеров. При первом же знакомстве с МК семейства PIC и ассемблером возникает много вопросов, а именно: чем и как прошить микроконтроллер?

Благодаря одному хорошему человеку, мне достался программатор-отладчик ICD2 (пиратская версия с сайта 5v.ru ) и очень очень удобная макетная плата, поэтому мое знакомство прошло интересно и завораживающе.

Итак, рассмотрим быстрый старт новичка в программировании на основе среды разработки MPLAB IDE и программатора ICD2. Лезем на оф.сайт microchip.com, и качаем последнюю версию программы MPLAB IDE. Устанавливаем ее на компьютер. Запускаем. После запуска должно появиться примерно следущее.

Теперь нужно создать папку на диске, назовем ее start. В этой папке создаем файл с расширением .asm (н-р start.asm)

Внимание: Название папок и файлов в них не должны содержать русских букв, иначе MPLAB IDE не будет с ними работать!

Приступаем к созданию проекта. Самый простой вариант через вкладку Projekt-> Project Wizard.

На приглашение нажимаем далее.

Первый шаг: выбираем нами любимый пик 18f252.

Второй: выбираем язык программирования – ассемблер (по умолчанию).

Третий: создание проекта, щелкаем на Browse, и указываем путь созданной нами папки start. Наш проект так же назовем start, нажимаем далее.

Четвертый: фаил start.asm кнопкой add добавляем к проекту, далее, готово.

Поздравляю наш проект создан.

Теперь двойным щелкаем на файл start.asm и открываем окно в которое будем добавлять наш текст программы (пишем сами или вставляем текстовый исходник).

Написали, сохраняем дискеткой, щелкаем на значек компилятора.

Компиллятор радостно сообщает нам BUILD SUCCEEDED, все можно выдохнуть, все прошло успешно и в нашей папке start создан файл прошивки для МК start.hex который мы и будем заливать в микроконтроллер. Его же можно сохранить в другом месте, или под другим названием, с помощью File->Export, в окне ОК, и сохранить как.

Эпизод второй. Заливаем прошивку в контроллер.

У нас уже есть хекс и его нужно залить в пик. Первым шагом лезем в настройки программатора. Programmer- Select programmer- выбираю свой программатор ICD2.

Откроется окно Визарда, щелкаем далее, выбираем порт COM1, скорость 19200, далее, везде далее, и на предпоследнем шаге выскочит окно с вопросом Please ensure that your system’s serial FIFO buffers are disabled . Стоп.

Идем в диспетчер устройств – порт сом1 – параметры порта – дополнительно — снимаем галку в окне буфера FIFO.

Все, закрываем все окна, в предупреждении Mплаба щелкаем ОК.

Открылась панелька программатора.

Подключаем программатор с макеткой кабелем к ком порту, коннектимся (5), через File->Import открываем нужный нам хекс, щелкаем на значек прошивки (1) и ждем. Происходит прошивка пика, она может занять некоторое время. По окончании прошивки окно программатора радостно сообщит нам, что все прошло успешно.

Если наше устройство уже собрано на макетке достаточно запустить проц кнопкой (3), и можно наслаждаться его работой.

Эпизод третий.

С помощью обратных процедур можно скачать прошивку из мк (если конечно он не залочен). Для этого коннектим программатор, запускаем проц (3), нажимаем (2) вторую кнопку Read target device, окно нам сообщает, что прошивка считана, теперь можно ее сохранить.

Можно не парится с дизассемблерами, а делать это сразу в программе. Для этого открываем импортом (File-Import) нужный нам хекс, затем откроем окно

здесь мы видим наш дизассемблированный текст, правой кнопкой убираем галки с ненужных нам столбцов, и нажимаем Output to file…

выбираем папку и имя, куда будем сохранять, все «исходник» готов.

Итак, быстрый старт работы с МПлаб завершен, теперь мы умеем создавать свой проект, компилировать исходник, делать хекс и заливать его в контроллер. Надеюсь этот обзор поможет начинающим в знакомстве с МПлаб.

Источник



General

  1. It is possible that the error was a one-time event. Try the operation again.
  2. There may be a problem programming in general. As a test, switch to ‘Run’ mode in MPLAB X IDE using the icon and program the target with the simplest application possible (e.g., a program to blink an LED). If the program will not run, then you know that something is wrong with the target setup.
  3. It is possible that the target device has been damaged in some way (e.g., over current). Development environments are notoriously hostile to components. Consider trying another target board.
  4. Microchip offers demonstration boards to support most of its microcontrollers. Consider using one of these applications, which are known to work, to verify correct MPLAB Snap In-Circuit Debugger functionality.
  5. Review debugger setup to ensure proper application setup. For more information, see the “Operation” section of the MPLAB PICkit 4 help or PDF.
  6. Your program speed may be set too high for your circuit. In MPLAB X IDE, go to File > Project Properties. Select ‘Snap’ in «Categories», then ‘Program Options’ in «Option categories». Select a slower speed from the «Program Speed» drop-down menu. The default is ‘Normal’. In MPLAB IPE, the «Program Speed» option can be found in the Advanced Mode, ‘Settings’ tab.
  7. There may be certain situations where the debugger is not operating properly and needs to be reprogrammed. See the following section.

MPLAB IDE features:

  • MPLAB C Compilers (free student editions available for download) 
  • MPLAB REAL ICE in-circuit emulator
  • MPLAB ICD 2 and MPLAB ICD 3 in-circuit debuggers and engineering programmers for selected Flash devices
  • PICkit 2 and PICkit 3 Debug Express economy debug/programmers
  • PICSTART Plus development programmer
  • MPLAB PM3 device programmer
  • Third Party tools, including HI-TECH, IAR, Byte Craft, B. Knudsen, CCS, Micrium, microEngineering Labs, Labcenter, MATLAB, Segger
  • A host of low cost starter boards, demonstration and evaluation kits
  • Fully integrated debugging with right mouse click menus for breakpoints, trace and editor functions
  • Tabbed editor option or separate source windows
  • Recordable macros
  • Context sensitive color highlighting for assembly, C and BASIC code readability
  • Mouse over variable to instantly evaluate the contents of variables and registers
  • Set breakpoints and tracepoints directly in editor to instantly make changes and evaluate their effects
  • Graphical project manager
  • Version control support for MS Source Safe, CVS, PVCS, Subversion
  • Programmer’s text editor
  • MPLAB SIM, high speed software simulator for PIC and dsPIC devices with peripheral simulation, complex stimulus injection and register logging
  • Full featured debugger
  • MPASM and MPLINK for PIC MCUs and dsPIC DSC devices
  • HI-TECH C PRO for PIC10/12/16 MCU Families running in lite mode 
  • CCS PCB C Compiler
  • Labcenter Electronic’s Proteus VSM spice simulator
  • Many Powerful Plug-Ins including
    • ○ AN851 Bootloader programmer
    • ○ AN901 BLDC Motor Control Interface
    • ○ AN908 ACIM Tuning Interface
    • ○ KeeLoq support

Программные средства разработки Microchip

Microchip предлагает своим клиентам широкий перечень программных решений, позволяющих значительно упростить процесс разработки и отладки программного кода при работе с компонентами, входящими в экосистему компании.

На текущий момент пользователям доступны следующие решения:

  • MPLAB X IDE – полнофункциональная интегрированная среда разработки (IDE), предназначенная для разработки кода для микроконтроллеров PIC, цифровых сигнальных контроллеров (DSC) dsPIC, а также микроконтроллеров AVR и SAM. Среда построена на основе IDE NetBeans с открытым исходным кодом от Apache Software Foundation.
     
  • MPLAB Xpress – представляет собой бесплатную онлайн-среду разработки, которая не требует установки или настройки системы. MPLAB Xpress имеет более ограниченный функционал по сравнению с MPLAB X IDE, однако поддерживает ее наиболее популярные функции, такие как конфигуратор кода MPLAB.
     
  • Конфигуратор кода MPLAB (MCC) – бесплатный графический плагин для инициализации системы, который также предоставляет драйверы для работы с компонентами. MCC может использоваться для настройки широкого спектра периферийных устройств и поддерживает работу с микроконтроллерами AVR и PIC.
     
  • MPLAB Harmony – гибкий фреймворк, включающий в себя программные модули, которые выступают в роли строительных блоков при создании приложения. Используя MPLAB Harmony, разработчик может включить в свой проект библиотеки и программные драйверы как компании Microchip, так и сторонних производителей. MPLAB Harmony поддерживает работу с 32-битными микроконтроллерами PIC и SAM.
     
  • Компиляторы MPLAB XC – комплексное решение для компиляции разрабатываемого программного кода. MPLAB XC поддерживает 8-битные PIC и AVR в версии MPLAB XC8, 16-битные PIC и dsPIC DSC в MPLAB XC16 и 32-битные PIC и SAM в MPLAB XC32. Для компиляторов MPLAB XC доступны два вида лицензии: бесплатная – включает базовые функции оптимизации и PRO – ориентирована на проекты, требующие максимальной оптимизации по скорости и размеру бинарного файла.
     
  • Microchip Studio (Atmel Studio 7) – интегрированная среда разработки (IDE) для написания кода и отладки микроконтроллеров AVR и SAM.
  • Atmel START – бесплатный онлайн-инструмент для графического конфигурирования микроконтроллеров для встраиваемых приложений на базе микроконтроллеров AVR и SAM.

Как несложно заметить, те или иные программные средства подходят только для определенного типа контроллеров. В Таблице 1 приведены данные по возможности работы с программным обеспечением в зависимости от выбранного микроконтроллера или микропроцессора.

Таблица 1. Данные по возможности работы программного обеспечения в зависимости от выбранного микроконтроллера
или микропроцессора
  Микро-
контроллеры
AVR
Микро-
контроллеры
PIC
Цифровые
контроллеры
сигналов
dsPIC
Микро-
контроллеры
SAM
Семейства
микро-
контроллеров
CEC/MEC
Микро-
процессоры
IDE MPLAB X IDE + + + + + +
MPLAB Xpress + + +
Microchip Studio + +
Компиляторы MPLAB XC + + + + + +
AVR GCC +
ARM GCC + +

Конфигураторы
кода

MPLAB Code
Configurator
+ + +
MPLAB
Harmony
+, только для
32-битных
версий
+ +
Atmel Start + +
Средства програм-
мирования
для производства
MPLAB IPE + + + +
MPLAB PM3 + +

Для упрощения процесса работы, компания Microchip объединила информацию по своим продуктам в раздел Microchip Developer Help [], в котором подробно описаны все тонкости работы с приведенными выше программными пакетами, а также приведены ссылки на продукты, дополнительные ресурсы, видеоуроки, курсы и документацию.

Стоит также учитывать возможность работы программного обеспечения на той или иной операционной системе. Например, инструменты разработки MPLAB совместимы с операционными системами Windows, Linux и macOS, а Microchip Studio (Atmel Studio 7) способна работать только под Windows.

Разберем описанные выше программные решения более подробно.

Microchip Studio (Atmel Studio 7)

Все, кто хоть раз имел дело с разработкой программного кода для микроконтроллеров, наверняка слышали о среде Atmel Studio. После того как Microchip завершила сделку по покупке компании Atmel в 2016 году, все права на среду разработки (как и на сами микроконтроллеры) перешли к новому правообладателю, а сама IDP стала носить гордое название Microchip Studio.

Microchip Studio представляет собой интегрированную платформу разработки (IDP) для создания и отладки приложений на базе микроконтроллеров AVR и SAM. Atmel Studio влилась в широкое портфолио средств разработки от Microchip и предлагает пользователям простой в использовании функционал для написания, сборки и отладки приложений, написанных на языках C/C++ или ассемблере (Рисунок 8).

Рисунок 8. Пример работы с проектом в среде Microchip Studio.

Несмотря на то, что среда получила новое название и слегка измененный внешний вид, пользователи по-прежнему могут свободно использовать документацию, курсы и видеоуроки, созданные для Atmel Studio. То же касается и аппаратной части, в частности программаторов AVR и SAM.

Microchip Studio устанавливается вместе с компиляторами avr-gcc, avr32-gcc и arm-none-eabi-gcc, в дополнение к которым был также добавлен MPLAB XC8. Его расширенная версия MPLAB XC8 PRO включает в себя улучшенную степень оптимизации, уменьшенный размер кода и успешно конкурирует с более дорогими представленными на рынке решениями.

Ключевые особенности среды Microchip Studio:

  • Поддержка более 500 устройств AVR и SAM;
  • Встроенный компилятор MPLAB XC8;
  • Более 1600 примеров проектов с исходными кодами, доступными через Advanced Software Framework (ASF);
  • Расширение возможностей IDE через Microchip Gallery – онлайн-магазин инструментов разработки и встроенного программного обеспечения от Microchip и сторонних производителей;
  • QTouch Composer – набор инструментов для разработки и настройки емкостных сенсорных устройств, проверки производительности системы, мониторинга энергопотребления с возможностью работы в режиме реального времени;
  • Wireless Composer набор инструментов для разработки и настройки беспроводных устройств;
  • Расширенные функции отладки, включая степпинг и точки останова, поддержку трассировки (SAM3 и SAM4), статистическое профилирование кода, отслеживание/мониторинг прерываний, отслеживание значений переменных в режиме реального времени и многое другое;
  • Встроенный редактор кода, менеджер проектов, виртуальный симулятор, модуль внутрисхемной отладки и интерфейс командной строки;
  • Возможность написания кода и моделирования прерываний, работы периферийных устройств и других внешних воздействий для конкретной модели контроллера;
  • Возможность создания дизайна приложений с низким энергопотреблением;
  • Отслеживание данных о потребляемой мощности во время отладки программы при помощи Power Debugger.

Еще одной особенностью является возможность импорта в Microchip Studio проектов Arduino, что позволяет значительно упростить и ускорить процесс перехода от создания прототипа к организации полноценного производства. Microchip Studio поддерживает работу с Arduino Zero и платами расширения Arduino Shield.

MPLAB XC8 Compiler Example

In this section, we will take an example code and compile this code. After that, we will upload hex file into proteus file and see how it works.

How to generate Configuration Bits File ?

First of all, we need to generate an configuration bit file with MPLAB XC8 compiler. Configuration bits file defines main features of pic microcontroller such as oscillator setting, watchdog timer, Power-on Reset, Brownout detect settings, etc. To know more about configuration bits, read this post:

Setting Configuration Bits Of PIC16F877A Microcontroller

To generate configuration bits file, go to window>>target memory views>>Configuration Bits and click on it.

After that, you will see this configuration bit settings field. Click on “Generate Source Code to Output”. It will generate a file. Copy that file and add it to your project. One other possible way to add this file in the project is through a header file. Create a header file and add this file to your main code.

We add this configuration file inside the main code.

// PIC16F877A Configuration Bit Settings

// 'C' source line config statements

// CONFIG
#pragma config FOSC = EXTRC // Oscillator Selection bits (RC oscillator)
#pragma config WDTE = ON // Watchdog Timer Enable bit (WDT enabled)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = ON // Brown-out Reset Enable bit (BOR enabled)
#pragma config LVP = ON // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3/PGM pin has PGM function; low-voltage programming enabled)
#pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off)
#pragma config WRT = OFF // Flash Program Memory Write Enable bits (Write protection off; all program memory may be written to by EECON control)
#pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off)

// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.

#include <xc.h>
#include <xc.h>

void main(void) 
{
return;
}

We are not going to explain how this code works. Because this tutorial is getting started guide only. The purpose of this tutorial is to teach you how to create your first project and compile code with MPLAB XC8 compiler.

PIC Microcontroller LED Blinking Example

In this section, we will see an LED blinking example. For instance, we use an LED with RB0 pin of PIC16F877A microcontroller. We connect an LED with pin0 of PORTB through a current limiting resistor.

Now copy this code to your MPLAB project and generate a hex file.

// PIC16F877A Configuration Bit Settings
// 'C' source line config statements
// CONFIG
#pragma config FOSC = EXTRC // Oscillator Selection bits (RC oscillator)
#pragma config WDTE = ON // Watchdog Timer Enable bit (WDT enabled)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = ON // Brown-out Reset Enable bit (BOR enabled)
#pragma config LVP = ON // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3/PGM pin has PGM function; low-voltage programming enabled)
#pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off)
#pragma config WRT = OFF // Flash Program Memory Write Enable bits (Write protection off; all program memory may be written to by EECON control)
#pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off)

#define _XTAL_FREQ 8000000
#include <xc.h>

void main(void) 
{
TRISB=0x00;
while(1)
{
RB0 = 1 ;
__delay_ms(500);
RB0 = 0 ;
__delay_ms(500);

}
return;
}


This example code will blink an LED with a delay of half-second. LED will turn on for half second and then remain off for half-second.

Notifications

Any conflicts or recommendations that a setup would require will show up under the ‘Notifications’ tab. This may be a simple as an I/O pin is set to analog and is recommended to be set to digital for the peripheral setting selected.

Using MCC to Select I/O Pin Configuration

MCC allows you to set up the I/O pin configurations using a graphical interface in the Pin Manager. The first step is to select the device package type to use then a representation of the device will appear. Then click on the chart below the graphical picture of the device to select the arrangement.

A blue pin is unconnected and a green pin is connected to a peripheral or designated as a digital I/O pin. The menu of peripherals to connect the pin to can be positioned on the top (horizontal) or on the left side (vertical) by clicking on the horizontal or vertical selection.

The pin(s) associated with the peripheral will show up in the row or column of the peripheral name. This way it can be easily determined which pins to select for that particular peripheral. Once the pin is selected, the color will change to green and the lock symbol will close indicating the pin is locked into that arrangement. Clicking on the green lock will reset it back to a blue, unused state.

There are several other colors that will appear as described below:

  1. Gray colored pin: indicates that the pin is not usable in the selected configuration and that there is no enabled module which has any functionality on that pin. There are also grayed out locks on a white background that indicate pins that are locked out by selected system functions.
  2. Blue colored pin: indicates pins that are available to be allocated to a module.
  3. Green colored pin (with a lock): this combination indicates that the pin has been allocated and selected for a module. The name that appears on the pin is either the name of the pin in the module’s context or a custom name entered.
  4. Green colored pin (with chain link): this combination indicates that the pin is shared between multiple functions.
  5. Yellow colored pin: indicates a possible alternate pin for an already allocated pin function.
  6. Grayed out locks on a white background: indicates pins that are locked out by selected system functions.

Generating Code

The code will be placed into the project automatically. If it is a new project then a main.c file will also be produced. If the project already has a main.c, then the MCC will only produce the peripheral driver files. The code will show up in the project area of MPLAB X.

The code produced is fully open sourced and editable. It can be used as a base and modified for the projects needs. This also makes a great way to start a new project so initially, a set of peripheral driver code with functions for each peripheral is automatically developed.

Example Projects

The self-paced online training: «Get Started with 8-Bit PIC MCUs» shows step-by-step directions on how to create simple projects using the PICDEM Lab II development board and the MCC.

Помощь новичкам или быстрый старт с MPLAB IDE.

Привет новичкам и всем, кто только только столкнулся с миром микроконтроллеров. При первом же знакомстве с МК семейства PIC и ассемблером возникает много вопросов, а именно: чем и как прошить микроконтроллер?

Благодаря одному хорошему человеку, мне достался программатор-отладчик ICD2 (пиратская версия с сайта 5v.ru ) и очень очень удобная макетная плата, поэтому мое знакомство прошло интересно и завораживающе.

Итак, рассмотрим быстрый старт новичка в программировании на основе среды разработки MPLAB IDE и программатора ICD2. Лезем на оф.сайт microchip.com, и качаем последнюю версию программы MPLAB IDE. Устанавливаем ее на компьютер. Запускаем. После запуска должно появиться примерно следущее.

Внимание: Название папок и файлов в них не должны содержать русских букв, иначе MPLAB IDE не будет с ними работать!

Приступаем к созданию проекта. Самый простой вариант через вкладку Projekt-> Project Wizard.

На приглашение нажимаем далее.

Первый шаг: выбираем нами любимый пик 18f252.

Второй: выбираем язык программирования – ассемблер (по умолчанию).

Третий: создание проекта, щелкаем на Browse, и указываем путь созданной нами папки start. Наш проект так же назовем start, нажимаем далее.

Четвертый: фаил start.asm кнопкой add добавляем к проекту, далее, готово.

Поздравляю наш проект создан.

Теперь двойным щелкаем на файл start.asm и открываем окно в которое будем добавлять наш текст программы (пишем сами или вставляем текстовый исходник).

Написали, сохраняем дискеткой, щелкаем на значек компилятора.

Компиллятор радостно сообщает нам BUILD SUCCEEDED, все можно выдохнуть, все прошло успешно и в нашей папке start создан файл прошивки для МК start.hex который мы и будем заливать в микроконтроллер. Его же можно сохранить в другом месте, или под другим названием, с помощью File->Export, в окне ОК, и сохранить как.

Эпизод второй. Заливаем прошивку в контроллер.

У нас уже есть хекс и его нужно залить в пик. Первым шагом лезем в настройки программатора. Programmer- Select programmer- выбираю свой программатор ICD2.

Идем в диспетчер устройств – порт сом1 – параметры порта – дополнительно — снимаем галку в окне буфера FIFO.

Все, закрываем все окна, в предупреждении Mплаба щелкаем ОК.

Открылась панелька программатора.

Подключаем программатор с макеткой кабелем к ком порту, коннектимся (5), через File->Import открываем нужный нам хекс, щелкаем на значек прошивки (1) и ждем. Происходит прошивка пика, она может занять некоторое время. По окончании прошивки окно программатора радостно сообщит нам, что все прошло успешно.

Если наше устройство уже собрано на макетке достаточно запустить проц кнопкой (3), и можно наслаждаться его работой.

Эпизод третий.

С помощью обратных процедур можно скачать прошивку из мк (если конечно он не залочен). Для этого коннектим программатор, запускаем проц (3), нажимаем (2) вторую кнопку Read target device, окно нам сообщает, что прошивка считана, теперь можно ее сохранить.

Можно не парится с дизассемблерами, а делать это сразу в программе. Для этого открываем импортом (File-Import) нужный нам хекс, затем откроем окно

здесь мы видим наш дизассемблированный текст, правой кнопкой убираем галки с ненужных нам столбцов, и нажимаем Output to file…

выбираем папку и имя, куда будем сохранять, все «исходник» готов.

Итак, быстрый старт работы с МПлаб завершен, теперь мы умеем создавать свой проект, компилировать исходник, делать хекс и заливать его в контроллер. Надеюсь этот обзор поможет начинающим в знакомстве с МПлаб.

Источник

Download and Install MPLAB IDE and XC8 Compiler

Microchip provides free of cost MPLAB integrated development environment (IDE). We can use this IDE to program Pic and AVR microcontrollers. Additionally, we can use it along with XC8, XC16 and XC32 compilers to program PIC10F, PIC12F, PIC16, PIC18, PIC24, PIC32 and Dspic series of microcontrollers. In this post, we will see how to use MPLAB with XC8 compiler, but you can follow the same instructions to use this IDE with compilers.

Download MPLAB X IDE

First of all, we will download the MPLAB X IDE from the following link:

Open this link and go to the bottom of the page. You will find many options according to version and operating systems. This IDE is available for three popular operating systems such as Windows, MAC and Linux operating systems. Download the latest version according to your system. After that click on the installation file and follow the instruction to install IDE. We are not going to explain the installation process. Because it is pretty straightforward.

Download XC8 Compiler

In the last section, we only downloaded and installed IDE. MPLAB IDE by default does not include any compiler. We can use it to write assembly language programs without the need for any compiler. But if we want to write code in embedded c language, we need to install a compiler separately. Go to this link and download XC8 compiler:

Go to this link and scroll to the end of the page. Click on compilers download menu and click on the XC8 compiler to download. Again make sure to download compiler according to the operating system that you are using. After that install XC8 compiler by clicking on the installation file. Once you have completed the installation process, you don’t need to do anything. XC8 got linked with MPLAB IDE automatically.

Create New Project with MPLAB XC8 Compiler

To create a new project follow these steps:

Create a New Project

First, open MPLAB X IDE by clicking on its icon and after that from the menu, select File>>New Project. Also,  you can open existing projects, close projects and import from this menu.

After that, this window will pop up. From categories option, pick “MicroChip Embedded” and from Projects window, select “Standalone Project”. After that click on the Next button.

Select Microcontroller

Now we will select a target microcontroller that we want to use. You must select a microcontroller that you want to use. Type the name of the pic microcontroller in the device window. For example, we will be using PIC16F877A microcontroller, we have typed PIC16F877A.

Programmer Hardware Tool

Now form select tool option, we can select the hardware tools such as programmers, debugger or other tools. For example, if you are using PICKit3 programmer to upload code to pic microcontroller then select PICKit3. Otherwise, you can select from other available options. Moreover, if you are not using any hardware and just want to use a simulator, you can select a simulator option.

MPLAB Compiler Selection

As we mentioned earlier, the MPLAB IDE supports many compilers. From compiler toolchains, select the compiler you want to use. Right now, it is showing only XC8 compiler and mpasm. Because we have only installed XC8 compiler and MPASM is available by default in MPLAB. But if you have installed multiple compilers all will show here. Now select the XC8 compiler and click on the next button.

Save Project Location MPLAB XC8 Compiler

In this last step, we will select the location where we want to store a PIC16F877A project in our system. Type a name for the project in the Project Name field. Click Browse to set the location of the project files. To differentiate the current project in the IDE (when multiple projects exist) as the main project, click “Set as the main project”.

Now click on the finish button, it will create a new project and you will see a project window in MPLAB as shown below:

The Hardware Tool Emergency Boot Firmware Recovery Utility

CAUTION
Debugger Failure.
Only use this utility to restore hardware tool boot firmware to its factory state.
Use only if your hardware tool no longer functions on any machine

The debugger may need to be forced into recovery boot mode (reprogrammed) in rare situations, for example, if none of the LEDs are lit when the debugger is connected to the computer.

You must use MPLAB X IDE v5.05 or greater to use the emergency recovery utility for the MPLAB Snap.

Carefully follow the instructions found in MPLAB X IDE under the main menu option Debug > Hardware Tool Emergency Boot Firmware Recovery. After the Warning screen, select ‘MPLAB Snap’.

Figure 1: Selecting Emergency Utility

Figure 2 shows where the emergency recovery jumper is located on the board.

Figure 2: Emergency Recovery Jumper

If the procedure was successful, the recovery wizard displays a success screen. MPLAB Snap is now operational and able to communicate with the MPLAB X IDE.

If the procedure fails, try it again. If it fails a second time, contact Microchip Support at http://support.microchip.com.

Atmel START

Atmel START представляет собой онлайн-инструмент для конфигурирования и настройки проектов встраиваемого программного обеспечения при помощи графического интерфейса. Atmel START основан на последнем поколении Advanced Software Framework и дает возможность разработчику выбирать и настраивать программные компоненты, драйверы и промежуточное ПО, а также подбирать примеры проектов, специально адаптированных под потребности создаваемого решения. При работе в Atmel START пользователь может просматривать зависимости между программными компонентами, предотвращая тем самым конфликты и аппаратные ограничения. В случае возникновения конфликта Atmel START автоматически предложит решения, подходящие для данной конкретной конфигурации.

Начиная работу с Atmel START, пользователь может создать новый проект или начать работу с уже существующим примером. После завершения конфигурирования программного обеспечения пользователь может загрузить сгенерированный проект и открыть его в IDE, установленной на персональном компьютере, например, Microchip Studio 7, IAR Embedded Workbench, Keil µVision (Рисунок 9).

Рисунок 9. Процесс работы с онлайн-инструментом Atmel START.

Atmel START предоставляет пользователю следующие преимущества:

  • Дает возможность найти и протестировать примеры для своего решения;
  • Позволяет сконфигурировать микроконтроллер, настроить драйверы и промежуточное ПО;
  • Позволяет настроить параметры таймеров и тактирование;
  • Дает возможность подготовить проект для работы на современной IDE;
  • И многое другое.

Отдельно следует отметить TrustZone Manager – графический интерфейс для настройки параметров безопасной (защищенной) зоны, также интегрированный в Atmel START.

Технология Arm TrustZone обеспечивает аппаратное разделение так называемых защищенных и незащищенных зон. Данное разделение позволяет обезопасить критически важные функции или конфиденциальную информацию, хранящуюся в защищенной зоне, от доступа из компонентов, расположенных вовне. Технология TrustZone, в частности, доступна при работе с микроконтроллерами SAM L11.

Write First Program with MPLAB XC8 Compiler

Before writing the first program with the MPLAB XC8 compiler, we need to add a source file or C file in the project. The easiest way to add source will is through a project window option. Right-click on Select New>>C Source File.

After you click on the main.c file, this window will open. Give this source file a useful name as we have given it a name “pic16f877aLED” and select extension ‘c’. Similarly, we can add header files also. But for header files, select extension ‘h’ from the menu.

After that click on the “Finish” button. It will create a new source file. This file “pic16f877aled” with your specified name will also appear in the project window. The file contains this minimum code. This is a starting point of your first project with MPLAB XC8 Compiler.

#include <xc.h>

void main(void) 
{
return;
}

#include <xc.h> this header file contains definition of all registers of PIC16F877A microcontroller. This header file microcontroller specific features.

How to Compile Code with MPLAB XC8 Compiler

After you finish writing your first program, you will need to compile the code to generate hex file and to see if there is an error in the code. To compile code, click on a building project button. If there is no error in the code, it will display a message of successfully built and generate a hex file.

You can upload this hex file to your microcontroller. You can read this tutorial on how to upload code to pic microcontroller using PICKit3 programmer:

How to Use PICKit3 to upload code to pic microcontroller

If you are using proteus, you can get a hex file from your project folder and upload it to the proteus.