Настройка Eclipse C/C++ для программирования AVR микроконтроллеров

Eclipse C/C++Для работы с микроконтроллерами семейства AVR есть бесплатная среда Atmel Studio. Несмотря на то, что среда включает в себя большое количество примеров исходных кодов, документацию, компилятор, средства отладки, она обладает некоторыми существенными недостатками. Первый и самый большой недостаток Atmel Studio это то, что является расширением MS Visual Studio и запустить её можно только на ОС Windows. Во-вторых, Atmel Studio, как по мне, не очень удобная среда и жрёт очень много ресурсов, также затрудняет создание и сопровождение достаточно сложных проектов с множеством файлов. Из за этого я начал искать альтернативы, такой альтернативой является среда разработки Eclipse.

Eclipse это свободная интегрированная среда разработки модульных кроссплатформенных приложений написана на Java. Развивается и поддерживается Eclipse Foundation. Чтобы среда работала нужно установить JVM. Среда подходит для разработки приложений на языках С/С++, Java, PHP, Python и других. Среда очень гибкая и можно расширить функционал, позволяет установить большое количество различных плагинов и дополнений. В данной статье мы рассмотрим способ настройки Eclipse для работы с 8-битными микроконтроллерами семейства AVR для ОС Windows. С тем же успехом можно настроить и под Linux.

Для настройки нам понадобиться собственно сам Eclipse, утилиты gnu toolchain для сборки проектов, avr-gcc компилятор и avrdude для загрузки hex-файла в память контроллера.

Eclipse C/C++

Установить Eclipse не нужно, достаточно скачать соответствующую версию (Eclipse IDE for C/C++ Developers) с официального сайта и распаковать в нужную директорию, например в E:/eclipse-cpp-neon-3/. Исполняемый файл это eclipse.exe. Но для того что бы программа запустилась, на компьютере должна быть установлена java-машина (JVM). При запуске Eclipse попросит указать путь к рабочей директории (workspace), в этой директории будут храниться все проекты. Сменить workspace можно в любое время, когда Eclipse запущен File->Switch Workspace.
Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров

Установка плагина AVR-Eclipse

Плагин AVR-Eclipse нужен для того, чтобы Eclipse мог работать с контроллерами AVR. В Eclipse плагины можно установить двумя способами: on-line, добавив ссылку на репозиторий, или из заранее скаченного архива. Мне удобнее первый вариант его и будем использовать.

  1. Для установки нового плагина следует выбрать в меню Help->Install New Software…
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  2. Чтобы добавив ссылку на плагин, выбираем Add…
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  3. В открывшемся окне указываем имя Name, к примеру: AVR-Eclipse и путь к к плагину Location: http://avr-eclipse.sourceforge.net/updatesite и жмём OK
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  4. В окне Available Software появляется список плагинов, доступных по указанной ссылке. Ставим галочку напротив AVR Eclipse Plugin, нажимаем Next>
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  5. Нажимаем Next>
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  6. Соглашаемся и жмем Finish
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  7. После установки плагина нужно перезапустить Eclipse Yes
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  8. Узнать, установился ли плагин можно по появившейся на панели инструментов кнопки AVR* со зелёной стрелкой вниз и пункт меню AVR. Эту кнопку мы будем использовать для загрузки hex-файла. Замечание! В некоторых случаях следует переключить интерфейс Eclipse на работу с C/C++. Для этого в правом верхнем углу есть пиктограмма Open Perspective. Следует выбрать C/C++.
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров

Настройка компилятора и утилит сборки

Пакет WinAVR содержит компилятор и утилиты для сборки. Однако WinAVR больше не развивается, а последняя версия вышла ещё в далёком 2010-ом год. Потому рекомендуется взять последний Atmel AVR Toolchain, а утилиты сборки из WinAVR. Если ранее установили Atmel Studio, тогда можете использовать его Toolchain и утилиты, у меня это: C:/Program Files (x86)/Atmel/Studio/7.0/toolchain/avr8/avr8-gnu-toolchain и C:/Program Files (x86)/Atmel/Studio/7.0/shellutils соответственно, а avrdude можете скачать с официального сайта. Также можете скачать все в сборе, Atmel AVR Toolchain + avrdude + shellutils, с нашего сайта. Распаковываем архив avr8-gnu-toolchain.zip в любое понравившееся место, в моём случае это E:/eclipse-cpp-neon-3/avr8-gnu-toolchain/, где находится сам Eclipse.

Теперь следует прописать в Eclipse пути к инструментам. Для этого:

  1. Заходим в меню Windows->Preferences, выбираем AVR->Paths. У меня среда уже настроена под WinAVR, но нам нужно настроить под Atmel AVR Toolchain.
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  2. Указываем путь к AVR-GCC, для этого выбираем соответствующую строку и нажимаем Edit.Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  3. В окне Change Path for AVR-GCC меняем Path source с System на Custom, а в Custom value указываем путь к AVR-GCC нажимая на Browse…. в моём случае это E:/eclipse-cpp-neon-3/avr8-gnu-toolchain/bin Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  4. Аналогично прописываем путь к GNU make – директории, содержащей файл make.exe: E:/eclipse-cpp-neon-3/avr8-gnu-toolchain/shellutils. Также прописываем путь к AVR Header Files – директории с «avr/io.h»: E:/eclipse-cpp-neon-3/avr8-gnu-toolchain/avr/include. В этом же окне можно указать путь к программатору avrdude: E:/eclipse-cpp-neon-3/avr8-gnu-toolchain/avrdude.
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  5. Сохраняем нажимая OK.

Настройка программатора USBasp

USBasp, пожалуй, самый популярный программатор для микроконтроллеров AVR Atmel. Простой, надёжный и дешёвый программатор. Чтобы работать с ним из Eclipse, для начала нужно его настроить:

  1. Заходим в меню Windows->Preferences, выбираем AVR->AVRDude
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  2. В Programmer configurations нажимаем на Add…
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  3. В открывшемся окне задаём имя конфигурации, Configuration name, к примеру USBasp, а в Programmer Hardware выбираем USBasp, http://www.fischl.de/usbasp/
    Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  4. Сохраняем нажимая OK

Создание нового AVR проекта

Самый надёжный способ проверить, всё ли работает нормально, это создать и скомпилировать новый проект. Я предпочитаю C++ вместо обычного C, так как привык к синтаксису, да и можно создавать классы, что тоже очень удобно для меня.

  1. Создаём новый C++ проект File->New->C++ ProjectНастройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  2. В поле Project name пишем имя проекта, а в Project type выбираем AVR Cross Target Application->Empty Project, а в ToolchainsAVR-GCC Toolchain. Жмём Next>Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  3. В окне Select configurations нажимаем на Advanced settings… для настройки проектаНастройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  4. В AVR->AVRDude находим Programmer configuration и выбираем USBasp, которого настроили ранееНастройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  5. Также нужно настроить C/C++ билдер. Переходим в C/C++ Build->Settings->Tool Settings и в Additional Tools in Toolchain ставим галочку напротив Generate HEX file for Flash memory, чтобы генерировать HEX файл, который и будет загружен на наш микроконтроллерНастройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  6. Переходим в AVR Compiller->Oprimization и меняем Optimization Level на Slight Optimizations (-O1). Если не оптимизировать код, тогда самый простой Hello World не поместится на МКНастройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  7. Тоже самое делаем и в AVR C++ Compiller->Oprimization. Сохраняем и нажимаем Next>Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  8. В AVR Target Hardware Properties выбираем наш МК MCU Type, в моём случае это ATmega16. Также пишем и частоту, MCU Frequency (HZ), к примеру 8000000МГцНастройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  9. Жмём Finish и проект готов

Создание файла main.cpp

Так как мы создали C++ проект, нам нужно создать .cpp файл. Был бы обычный C проект, тогда расширение файла была бы .c

  1. Переходим в File->New и выбираем Source file и жмём Next>Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  2. Source Folder в данном случае это наш ранее созданный проект, а Source Name это имя файла, я назвал его main.cpp. Жмём Finish Настройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  3. Пишем какой-то Led Blinking примерНастройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  4. Собираем проект: Project->Build ProjectНастройка Eclipse CDT/C++ для программирования AVR микроконтроллеров
  5. Загружаем HEX файл на наш контроллер AVR->Upload Project to Target DeviceНастройка Eclipse для программирования AVR микроконтроллеров
  6. Если программатор UABasp подключен между контроллером и компьютером, тогда вы должны получить примерно такой результат в логах. Также стоит не забывать и о фьюзах.
    Launching E:\eclipse-cpp-neon-3\avr8-gnu-toolchain\avrdude\avrdude -pm16 -cusbasp -Uflash:w:Atmega16_blink.hex:a 
    Output:
    
    avrdude: warning: cannot set sck period. please check for usbasp firmware update.
    avrdude: AVR device initialized and ready to accept instructions
    
    Reading | ################################################## | 100% 0.00s
    
    avrdude: Device signature = 0x1e9403 (probably m16)
    avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
             To disable this feature, specify the -D option.
    avrdude: erasing chip
    avrdude: warning: cannot set sck period. please check for usbasp firmware update.
    avrdude: reading input file "Atmega16_blink.hex"
    avrdude: input file Atmega16_blink.hex auto detected as Intel Hex
    avrdude: writing flash (152 bytes):
    
    Writing | ################################################## | 100% 0.18s
    
    avrdude: 152 bytes of flash written
    avrdude: verifying flash memory against Atmega16_blink.hex:
    avrdude: load data flash data from input file Atmega16_blink.hex:
    avrdude: input file Atmega16_blink.hex auto detected as Intel Hex
    avrdude: input file Atmega16_blink.hex contains 152 bytes
    avrdude: reading on-chip flash data:
    
    Reading | ################################################## | 100% 0.13s
    
    avrdude: verifying ...
    avrdude: 152 bytes of flash verified
    
    avrdude done.  Thank you.
    

Полезные ссылки

Eclipse IDE for C/C++ Developers
Atmel AVR Toolchain + avrdude + shellutils
AVR Eclipse Plugin Download
Atmel AVR Toolchain
AVRDUDE — AVR Downloader/UploaDEr
WinAVR

Похожие записи

Комментарии 20

  • Playing on a trusted online slot site, players must of course have the expertise to accurately decipher the condition of slot games that are currently performing well today. This factor plays an important role in determining whether a player will be successful or not in achieving victory in each session of playing slot games when they are in superior condition that day. I really like it, and I look forward to hearing from you next. Thank you for the information about today’s most popular news this year. For more detailed information, please visit our website for further information Kurcacislot

  • Today’s slot game site is the choice of slotters who are looking for links to play the best online Gacor slots in Indonesia. By finding the official Gacor online slot site, it means you have put one foot in front of the other and then registered a Gacor slot account to be able to win the Maxwin jackpot with the Gacor online slot site. I really like it, and I look forward to hearing from you next. Thank you for the information about today’s most popular news this year. For more detailed information, please visit our website for further information Gamb888

  • It’s easy to get the biggest Maxwin jackpot today and it’s easy to win playing online slots if you trust them by playing Gacor slot games. Don’t want to miss this good opportunity, because not all gacor game sites are able to provide guarantees like this. Make your choice now and have a super gacor account. I really like it, and I look forward to hearing from you next. Thank you for the information about today’s most popular news this year. For more detailed information, please visit our website for further information Gamecare88

  • Playing gacor online slot games can provide income or income every day. The level of excitement on this online slot game site is above average compared to other sites, winning always provides a unique playing experience, this time you don’t need to hesitate anymore because you have found the golden opportunity now. I really like it, and I look forward to hearing from you next. Thank you for the information about today’s most popular news this year. For more detailed information, please visit our website for further information Topsportsandfitness

  • Gacor slot game agent Aviantogel offers 24-hour online customer service which is designed to allow you to interact directly with our online slot game team anytime, anywhere. With this customer service, you can communicate all the problems you face, for example when you want to register or want to play on the newest and most popular Gacor slot game site at the moment. I really like it, and I look forward to hearing from you next. Thank you for the information about today’s most popular news this year. For more detailed information, please visit our website for further information Avian303

  • Online lottery is a type of number guessing game that often gives big jackpots or is a very popular game in Indonesia, and has many fans looking for a trusted lottery site that is also safe in placing bets. One of the sites that has been trusted for a long time as a trusted online lottery site in Indonesia today. I really like it, and I look forward to hearing from you next. Thank you for the information about today’s most popular news this year. For more detailed information, please visit our website for further information 8499225.cc

  • The best official online lottery bookie in Indonesia which has been officially certified by the government. This means that through well-known online lottery bookies, players can get guaranteed security in placing lottery bets today. In fact, we always announce today’s lottery results according to the schedule for each official lottery market that has been determined from the biggest lottery bookie site. I really like it, and I look forward to hearing from you next. Thank you for the information about today’s most popular news this year. For more detailed information, please visit our website for further information Bbin09

  • The best gacor slot game agent at the beginning will provide additional 4 really great secret tips for getting the biggest online slot jackpot in Indonesia that you must try. It is common for professional new member bonus slot players to receive slot jackpots of hundreds of millions, or freepin prizes of millions of rupiah. Immediately, here are tips for winning the biggest jackpot when playing gacor slot games. I really like it, and I look forward to hearing from you next. Thank you for the information about today’s most popular news this year. For more detailed information, please visit our website for further information lyy-suheng

  • Take the time to study some of the names of the Waktogel online slot game websites, read their reviews and be sure to decide on something that suits your playing style. Special factors are important to take into account when ensuring that the best Gacor slot agent at the moment always provides huge profits every day. I really like it, and I look forward to hearing from you next. Thank you for the information about today’s most popular news this year. For more detailed information, please visit our website for further information Aspalputih

  • We also have Live RTP gacor slots which you can access easily without any obstacles to find out what slot games have a high Return to Player percentage so as to minimize the risk and increase the chances of the maxwin jackpot that you will get in every gacor slot game that has been offered. provide it so very easily. I really like it, and I look forward to hearing from you next. Thank you for the information about today’s most popular news this year. For more detailed information, please visit our website for further information Mez.ink dorahoki

  • You will find one of the gambling games of your choice, whatever your level. Live chat support is available. Your goal is to make as many deposits as possible. The special round prepared for players during betting rides by the official TIERGACOR site bookie can actually be enjoyed within a certain time period. Read on to find out more about the company’s plans and potential in the gaming industry. For clearer information, you can visit our website TIERGACOR is a site The biggest online game in Asia that gives jackpots
    big every day.

  • Seperti yang sudah kami bahas sebelumnya, game slot pragmatic play adalah yang paling populer di BOCORAN SLOT , situs taruhan slot online terbaik. Ini adalah alasan mengapa member kami paling sering memainkan game slot online ini karena satu-satunya game slot online yang menjamin akan mendapatkan jackpot terus-menerus dengan jumlah yang berbeda di tahun 2023. Pemain harus tahu bahwa ada beberapa agen taruhan online yang tidak berani memberikan jackpot terus-menerus. BOCORAN SLOT adalah satu-satunya agen yang yakin dapat menawarkan jackpot terus-menerus. Kami berkomitmen untuk memberikan pengalaman bermain terbaik bagi semua pemain kami, seperti yang ditunjukkan oleh ciri-ciri agen slot online terbaik kami, seperti lisensi, reputasi, kecepatan deposit, dan bonus.informasi lebih jelas bisa kunjungin diwebsite kami BOCORAN SLOT merupakan situs game online terbesar se asia yang memberikan jackpot
    besar setiap hari.

  • You will find one of the games of your choice, whatever your level. Live chat support is available. Your goal is to make as many deposits as possible. The special round prepared for players during betting rides by the official PPSOFT site bookie can actually be enjoyed within a certain time period. Read on to find out more about the company’s plans and potential in the gaming industry. For clearer information, please visit our website PPSOFT is a gaming site The biggest online site in Asia that gives jackpots
    big every day.

  • You will find one of the games of your choice, whatever your level. Live chat support is available. Your goal is to make as many deposits as possible. The special round prepared for players during betting rides by the official JAMUSLOT site bookie can actually be enjoyed within a certain time period. Read on to find out more about the company’s plans and potential in the gaming industry. For clearer information, you can visit our website JAMUSLOT is a site The biggest online game in Asia that gives jackpots
    big every day.

  • Mereka yang tertarik untuk memainkan permainan di situs TRIBUNTOGEL online bonanza harus menyadari bahwa ada banyak jenis slot online yang dapat mereka pilih. Beberapa di antaranya adalah Advant Play, Admin Bonanza, Sweet Bonanza, dan slot lainnya . Ini semua adalah permainan yang bagus untuk dimainkan secara online, dan mereka pasti akan mengeluarkan yang terbaik dari diri Anda.informasi lebih jelas bisa kunjungin diwebsite kami TRIBUNTOGEL merupakan situs judi online terbesar se asia yang memberikan jackpot
    besar setiap hari.

  • taruhan slot online terbaik. Inilah alasan mengapa member kami paling sering memainkan permainan slot online ini karena merupakan satu-satunya permainan slot online yang menjamin jackpot terus menerus dengan jumlah yang bervariasi di tahun 2024. Perlu pemain ketahui bahwa ada beberapa agen taruhan online yang tidak berani memberikan jackpot. . terus menerus.TIERGACOR satu-satunya link yang pasti menawarkan jackpot terus menerus. Kami berkomitmen untuk memberikan pengalaman bermain terbaik bagi seluruh pemain kami, terbukti dari ciri-ciri agen slot online terbaik kami seperti lisensi, reputasi, kecepatan deposit dan bonus. Untuk informasi lebih jelas, Anda dapat mengunjungi website kami TIERGACOR merupakan situs judi online terbesar se asia yang memberikan jackpot
    besar setiap hari.

  • Mereka yang tertarik untuk memainkan permainan di situsPPSOFT online bonanza harus menyadari bahwa ada banyak jenis slot online yang dapat mereka pilih. Beberapa di antaranya adalah Advant Play, Admin Bonanza, Sweet Bonanza, dan slot lainnya . Ini semua adalah permainan yang bagus untuk dimainkan secara online, dan mereka pasti akan mengeluarkan yang terbaik dari diri Anda.informasi lebih jelas bisa kunjungin diwebsite kami PPSOFT merupakan situs game online terbesar se asia yang memberikan jackpot
    besar setiap hari.

  • Seperti yang sudah kami bahas sebelumnya, permainan slot pragmatic play paling populer di MGOGAMING situs taruhan slot online terbaik. Inilah alasan mengapa member kami paling sering memainkan permainan slot online ini karena merupakan satu-satunya permainan slot online yang menjamin jackpot terus menerus dengan jumlah yang bervariasi di tahun 2024. Perlu pemain ketahui bahwa ada beberapa agen taruhan online yang tidak berani memberikan jackpot. . terus menerus.MGOGAMING satu-satunya link yang pasti menawarkan jackpot terus menerus. Kami berkomitmen untuk memberikan pengalaman bermain terbaik bagi seluruh pemain kami, terbukti dari ciri-ciri agen slot online terbaik kami seperti lisensi, reputasi, kecepatan deposit dan bonus. Untuk informasi lebih jelas, Anda dapat mengunjungi website kami MGOGAMING adalah situs game online terbesar di Asia yang menyediakan jackpot
    besar setiap har informasi lebih jelas bisa kunjungi diwebsite kami MGOGAMING merupakan situs gameonline terbesar se asia yang memberikan jackpot
    besar setiap hari.

  • taruhan slot online terbaik. Inilah alasan mengapa member kami paling sering memainkan permainan slot online ini karena merupakan satu-satunya permainan slot online yang menjamin jackpot terus menerus dengan jumlah yang bervariasi di tahun 2024. Perlu pemain ketahui bahwa ada beberapa agen taruhan online yang tidak berani memberikan jackpot. . terus menerus.TRIBUNTOGEL satu-satunya link yang pasti menawarkan jackpot terus menerus. Kami berkomitmen untuk memberikan pengalaman bermain terbaik bagi seluruh pemain kami, terbukti dari ciri-ciri agen slot online terbaik kami seperti lisensi, reputasi, kecepatan deposit dan bonus. Untuk informasi lebih jelas, Anda dapat mengunjungi website kami TRIBUNTOGEL merupakan situs game online terbesar se asia yang memberikan jackpot
    besar setiap hari.

  • Download CorelDraw X4 for PC Rahim Soft

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

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