Ide codeblocks для arduino

Ide codeblocks для arduino

Arduino — «красивое» устройство, история которого началась с 2005 года, на сегодня выпускается серийно от 100 до 3000 в день на различных фабриках и стоит не малых кровных денег. Arduino имеет свою среду разработки Arduino IDE, которая, к сожалению, не лишёна недостатков.
Если Ваши проекты, на этом устройстве, заканчиваются лишь миганием лампочек, включение выключение релюшек, тогда нет смысла читать эту тему.
Лишь после личного опыта возни с этой средой разработки и траты своего времени, я решил убрать эти грабли с привязным топором и уберечь свои и чужие нервы.
Причин этому много: низкая скорость компиляции, крайне убогий интерфейс, малая функциональность, вернее, её отсутствие, библиотеки — это громко сказано и, самое раздражающее, создание новых окон для каждого скетча.
Заменить опасные грабли вариантов много, я взял CodeBlocks.
CodeBlocks

Как только я задумал идею, сразу притормозил . Это надо скачать чистую среду настраевать её под Arduino. Не тут то было и Google меня спасет не в первый раз.
CodeBlocks Arduino Edition – out-of-box Arduino IDE for more demanding developers

1. Качаем CodeBlocks Arduino Edition for Windows или CodeBlocks Arduino Addons for Linux (Setup Guide)
2. Распаковать. Например в «C:\CodeBlocks»
3. Запускаем C:\CodeBlocks\codeblocks.exe
4. Меню: File -> New -> Project.
5. Выбираем «Arduino Project» -> Go -> (галочку не ставим) Next
6. Для тестового проекта оставляем все как есть только в пустом селектор выбираем COM-порт нашей Arduino. У меня COM-2
7. Вводим название проекта, его путь к папке -> Next
8. В создном проекте На панели ищем Build Target -> выбираем тип своей Arduino (У меня Arduino Nano 328)
9. Посмотреть Код -> Worckspace -> Имя проекта -> Sources -> Scketch.cpp (Узнаем до боли знакомый глазу код миганием светодиода)
10. Меню: Build -> Build (Смотрим нет ли ошибок компиляции)
11. Меню: Tools -> USB Upload ( Flash )
12. Готово!!

Может сразу не заработает понадобятся MinGW — Minimalist GNU for Windows. При установке выберем компилятор только для С.

Теперь переносим свои проекты на это чудо и радуемся. )))

Библиотеки:
Очень хороший документ по созданию своей библиотеки в среде CodeBlocks Lib_codeblocks.pdf

Пожже расскажу как сделать рус, работать в отладке.

Источник

Какие существуют среды разработки (IDE) для Arduino

Все, кто начинает изучать Arduino, знакомы со средой разработки Arduino IDE. Оно позволяет писать скетчи, проверять корректность и загружать их в Ардуино. Но единственная ли это среда для разработки программ для Arduino? Вовсе нет! Давайте посмотрим, какие ещё есть варианты.

В данной статье мы рассмотрим 4 самые популярные среды разработки:

  • Arduino IDE;
  • Programino;
  • B4R;
  • CodeBlocks for Arduino.

1 Среда разработки Arduino IDE

Конечно же, эта среда разработки знакома каждому, кто хоть раз программировал для Arduino.

Главное окно среды разработки Arduino IDE

В ней имеется весь необходимый минимум для разработки программ: написание кода, проверка кода, компиляция, загрузка скетча в Ардуино, монитор последовательного порта. Все, кто работал в серьёзных «взрослых» средах разработки типа JetBrains IDEA, Microsoft Visual Studio или Quartus, наверняка отметят, что среда Arduino IDE довольно аскетична: ничего лишнего, и особых удобств она не предлагает.

2 Среда разработки Programino

Рассмотрим среду разработки PROGRAMINO. Это платная среда разработки, но её можно опробовать в течение 14-ти дней бесплатно. Programino, как и другие среды разработки, требует, однако, чтобы у вас была установлена Arduino IDE. При первом запуске программы следует в настройках указать путь к исполняемому файлу arduino.exe. Для этого идём в меню настройки: Options Editor Settings. Появится окно, в котором нужно будет указать пути к директории с Arduino IDE и сопутствующими библиотеками. Теперь мы готовы писать программы в Programino.

Первоначальная настройка среды Programino

Язык, который используется в данной среде разработки – такой же, как и в оригинальной Arduino IDE – Си. То есть, по сути, если вы уже пишете скетчи в Arduino IDE, то вам не придётся изучать новый язык программирования, что является большим плюсом данной среды разработки.

Однако помимо этого, данная IDE предлагает такой удобный способ быстрой разработки как автодополнение кода. То есть, вам не придётся постоянно лазить в справочник по командам и методам Arduino. Вы начинаете набирать код, и среда разработки предложит вам выбрать из доступных вариантов тот, который вам нужен. Например, вы набираете «digi» и IDE предлагает вам варианты: «digitalRead», «digitalWrite» и другие возможные.

Функция автодополнения кода Programino IDE

Давайте напишем простой скетч, в котором будем постоянно опрашивать один из аналоговых выводов Arduino и выводить считанные показания в последовательный порт.

Постарайтесь набирать скетч вручную, а не копировать и вставлять, чтобы прочувствовать удобство автодополнения кода Programino.

Что ещё интересного предлагает Programino IDE? В данной среде разработки имеются несколько дополнительных полезных инструментов, доступных через меню Tools. Например: блокнот, дизайнер LCD символов, преобразователь между DEC-BIN-HEX, терминал последовательного порта, аналоговый плоттер и другие.

Дополнительные инструменты Programino IDE

Остановимся подробнее на инструменте Analog Plotter. Это средство позволяет визуализировать вам то, что приходит в COM-порт от Arduino.

Для работы плоттера в скетче нужно активизировать последовательный порт на скорости 19200 кб/сек. Аналоговые данные выводятся на плоттер с помощью команды Serial.println().

Запустим аналоговый плоттер. Нажмём кнопку Connect для подключения к порту, к которому у нас подключён Arduino.

Аналоговый плоттер в Programino

Этот инструмент может быть полезным, например, для отображения показаний во времени каких-нибудь аналоговых датчиков: температуры, влажности, давления, освещённости и других.

Перед записью скетча в память Arduino, следует указать тип используемой платы и порт, к которому она подключена через меню Hardware.

Выбор платы в Programino Выбор последовательного порта в Programino

Для загрузки скетча в память Arduino нажмите в верхнем меню иконку с изображением загрузки. Programino загрузит скетч и в нижнем окне журнала покажет данные о размере скетча и оставшихся свободных ресурсах платы Ардуино.

3 Среда разработки B4R (Basic for Arduino)

Ещё одна интересная альтернатива Arduino IDE – B4R, или «Basic for Arduino». Эта среда разработки уникальна тем, что использует язык Basic, а не Си. Она также поддерживает функцию автодополнения кода. Кроме того, она полностью бесплатна.

При первом запуске среда B4R также требует указать путь к директории с Arduino IDE и, при необходимости, дополнительным нестандартным библиотекам и общим модулям. Эти настройки можно задать и позже через меню Tools Configure Paths.

Настройки среды B4R

А также выбрать плату: Tools Board Selector: Выбор платы Arduino в B4R

Давайте напишем вот такой скетч и заодно немного ближе познакомимся со средой разработки.

Главное окно B4R IDE

В центральной части находится поле для редактирования кода. В правой – область вкладок и сами вкладки: доступных библиотек, модулей скетча, журнала и поиска. На приведённый фотографии открыта вкладка с журналом. Видно, что сюда выводятся сообщения, которые в программе задаются командой Log(). В данной среде разработки можно ставить точки останова, что весьма полезно в процессе отладки, а также использовать закладки для более быстрой навигации по коду.

Вы не сможете сразу начать программировать в этой среде разработки, т.к. она использует другой, более объектно-ориентированный язык, чем классическая Arduino IDE, с другим синтаксисом. Тем не менее, удобство этой среды и наличие хорошего руководства от разработчиков полностью окупает эти недостатки.

4 Среда разработки Codeblocks for Arduino

Существуют и другие среды разработки для Arduino кроме перечисленных. Например, CodeBlocks. Основное её отличие от описанных IDE – возможность писать код для микроконтроллеров и некоторых других платформ, не только для Arduino. Более подробно описывать её не буду, проще почитать информацию на официальном сайте и файлы справки.

Среда разработки CodeBlocks для Arduino

Теперь мы знаем, что существуют альтернативные, гораздо более удобные, среды разработки, чем классическая Arduino IDE. Их использование может существенно упростить и ускорить написание ваших собственных скетчей.

Источник

provideyourown/CodeBlocks-Arduino

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

CodeBlocks-Arduino (version: 1.0b2)

© 2012-2013 Scott Daniels (http://provideyourown.com) under GNU General Public License

Portions are: © 2012 Stanley Huang (stanleyhuangyc@gmail.com) under GNU General Public License

CodeBlocks-Arduino contains added functionality for Code::Blocks to allow Arduino software development. Code::Blocks is a more advanced IDE than the ArduinoIDE, yet is still fairly straightforward. When an Arduino project starts incorporating custom libraries, it often becomes too cumbersome for the ArduinoIDE. This package adds a custom project wizard for creating Arduino projects. The distribution also integrates the latest Arduino core files and libraries, AVR toolchains, avrdude for uploading, and a serial terminal.

  • Dedicated project wizard for Arduino development
  • Integrated Arduino core files and libraries
  • Integrated pre-configured AVR compiler toolchain
  • Integrated AVRDUDE for uploading (Flash and EEPROM) via USB or programmer
  • Integrated serial terminal
  • Various Arduino boards supported as build targets

Certain files must be placed in the Code::Blocks’ data folder. The following instructions apply to Linux computers. For other operating systems installations, contributions on how to do it are welcome — http://provideyourown.com/contact.

The data folder for CodeBlocks is located in:

In this folder place:

A symlink to your Arduino directory. It must be named arduino . For example if your Arduino install is at:

then use this command (from within /home/USER/.codeblocks ):

A symlink to your Sketches directory. It must be named sketches . For example if your Sketches directory is at:

then use this command (from within /home/USER/.codeblocks ):

Copy the helpers directory to the codeblocks folder (or ‘symlink’ it)

There should be the following folder path:

If there is not, then create it. The copy the folder /wizards/arduino to the wizard folder.

Copy the default.conf file

When you are done, your data folder should look like the following:

The /share/codeblocks/templates/wizard folder should look like:

###Instructions for Code::Blocks newer than version 10 When you try to create a new project, newer versions of Code::Blocks will not show the arduino wizard by default. The wizard must first be registered. To do so, select New/Project from the menu. Then right-click on any of the wizards. Select Edit Global Registration Script. Under the function RegisterWizards() , place this line:

and save the file. It will be placed in your user wizard folder.

##Using ###Creating an Arduino Project using the Wizard

Launch Code::Blocks. Select New/Project menu item. You should see Arduino Project in red. If you do not, then something in your installation is wrong.

Select Arduino Project. After the intro page, the next page will be where you configure your project. Most of the defaults are fine to use. If you are using a programmer instead of the Arduino bootloader to program your device, select the programmer you will be using. Also, now is the time to choose the serial port to use for uploading your code.

TIP for serial port selection:

  • For Usbasp programmers, choose ttyUSB0.
  • For Uno & Leonardo, choose ttyACM0 in most cases.
  • For all others, ttyUSB0 is a safe bet.

Note: You can change/select the board from the Build target menu after finishing the wizard. The programmer and serial port remain the same for each board. They can be changed for individual boards after completing the wizard — see the Modifying section for details.

On the next page, creating a new project is pretty self-explanatory. If you are using an existing Arduino project, do the following:

a. Select the folder to create project in — this will be your existing Arduino project folder

b. Give it the project title — usually this will be the same as the folder name

c. Edit the Resulting Filename box and remove the extra folder being created

###Tools Menu Several tools are provided in the Tools menu. They are:

  • Serial Terminal
  • Upload Code
  • Upload EEPROM
  • Arduino-Make
  • Arduino-Make (Clean)
  • Arduino-Make (Upload)

####Serial Terminal Tool This tool opens a serial comm window just like the ArduinoIDE. It does not close automatically before an upload, so if using the same serial port for uploading, you will need to close this window first.

####Upload Tools If after compiling, you need to upload your code again, use the Upload Code tool. EEPROM data is not uploaded by default, so the Upload EEPROM tool is provided for that.

####Arduino-Make These tools invoke the make function using command-line Arduino-Make tool(https://github.com/sudar/Arduino-Makefile). You must install this script and create your config file within your project folder before using. You can add your own additional make commands from the Configure tools. menu item in the Tools menu.

####GitG This tool launches the GitG application for your project.

##Modifying Sometimes you need to modify a project after creating it. For most settings, go to Project/Build Options. . You will find different sets of options for both the project and individual target devices. The two sets are merged at compile time (you can change this if desired), so you will need to check both when looking for configurations to change. Some common ones you might want to change are:

  • Compiler Settings/#defines (project setting) — arduino version & what core libraries to include
  • Custom Variables (device setting)
    • programmer protocol
    • upload port

You can select which board to compile and upload your program to by choosing from the Build target menu in the toolbar. This will change the appropriate upload settings, with the exception of the programmer used and the upload port.

###Programmer For Arduino boards with bootloaders, the correct programmer is already chosen. For other boards using a programmer, the one chosen in the wizard will be the one used. If it needs to be changed, then go to the Project/Build options. and select the correct build target and go to the Custom Variables tab. Edit the correct PROTOCOL there.

###Upload Port The correct port varies across the boards. Different ISP programmers may have their own port. The Uno and Leonardo use a different port than their predecessors. If you have other devices sharing the same port labeling system plugged in, then the port number will change.

In most cases, these values will work:

  • Uno/Leonardo: ttyACM0 (because Leonardo connects & disconnects all the time, expect it to change from time to time, usually to ttyACM1 or ttyACM2.
  • Usbasp programmers: ttyUSB0
  • All others: ttyUSB0 is a safe bet.

To change the port for a board, then go to the Project/Build options. and select the correct build target and go to the Custom Variables tab. Edit the correct UPLOAD_PORT setting there.

The method of linking used is not as efficient as the ArduinoIDE. No solution is known at present. In most projects it won’t matter, but if a project is reaching the maximum flash memory point, it may be a problem.

Leonardo uploading is still problematic (and not recommended at this time), and automatic reset does not work. Sometimes uploading will put the Leonardo in an unresponsive state. The only way to revive it is to upload a sketch from the ArduinoIDE while pressing the reset button (sometimes it has to be done more than once).

Everything has been written and tested on Linux systems. Use on Windows systems may require some tweaking — Upload port selection and Tool menu settings.

  1. Fix known issues
  2. Do more with command-line make tool?
  3. Make sketch.cpp file more compatible with the ArduinoIDE sketch.ino file (eliminate the need for both) when using either IDE.

8/18/13 — directory includes improvements:

  • Improved various directory includes:
    • The hardware directory for ATTiny support is now located in the sketches directory as per standard ArduinoIDE location. You can get support for most ATTiny chips here — https://github.com/provideyourown/attiny.git
    • The libraries directory for your sketches is now included by default. Libraries can now be included by name only without specifying a relative path — just like the ArduinoIDE.

1/17/13 — bug fixes; Tools menu changes:

  • Tools Menu:
    • Generalized upload cmds to work with any target board
    • Added support for command-line make tool(https://github.com/sudar/Arduino-Makefile)
  • Added -D option to avrdude for Arduino boards (must not be used for ATtinys)
  • Removed default port selection (can’t get it to work)
  • Added more instruction to README file

###1/16/13 — changes to Stanley Huang’s original code:

  • Added size calculation to postprocessing steps to calculate both flash memory and SRAM.
  • Fixed avrdude configuration to work with ATtiny
  • Added support for Leonardo
  • Added support for alternative configurations such as ATtiny boards
  • Added support for ISP programmers for uploads
  • Added support for Code::Blocks version 12
  • Added tooltips to Wizard options

About

Addons to Code::Blocks to support Arduinos and ATtinys

Источник

Adblock
detector