Ардуино программа для программирования
Рассмотрим пример минимально возможной программы на C++ для Arduino, которая ничего не делает:
Разберёмся что здесь написано и почему это обязательно: почему нельзя обойтись просто пустым файлом.
Из чего состоит программа
Для начала стоит понять, что программу нельзя читать и писать как книгу: от корки до корки, сверху вниз, строку за строкой. Любая программа состоит из отдельных блоков. Начало блока кода в C/C++ обозначается левой фигурной скобкой < , его конец — правой фигурной скобкой >.
Блоки бывают разных видов и какой из них когда будет исполняться зависит от внешних условий. В примере минимальной программы вы можете видеть 2 блока. В этом примере блоки называются определением функции. Функция — это просто блок кода с заданным именем, которым кто-то затем может пользоваться из-вне.
В данном случае у нас 2 функции с именами setup и loop . Их присутствие обязательно в любой программе на C++ для Arduino. Они могут ничего и не делать, как в нашем случае, но должны быть написаны. Иначе на стадии компиляции вы получите ошибку.
Классика жанра: мигающий светодиод
Давайте теперь дополним нашу программу так, чтобы происходило хоть что-то. На Arduino, к 13-му пину подключён светодиод. Им можно управлять, чем мы и займёмся.
Скомпилируйте, загрузите программу. Вы увидите, что каждую секунду светодиод на плате помигивает. Разберёмся почему этот код приводит к ежесекундному миганию.
В наши ранее пустые функции мы добавили несколько выражений. Они были размещены между фигурными скобками функций setup и loop . В setup появилось одно выражение, а в loop сразу 4.
Каждое выражение — это приказ процессору сделать нечто. Выражения в рамках одного блока исполняются одно за другим, строго по порядку без всяких пауз и переключений. То есть, если мы говорим об одном конкретном блоке кода, его можно читать сверху вниз, чтобы понять что делается.
Теперь давайте поймём в каком порядке исполняются сами блоки, т.е. функции setup и loop . Не задумывайтесь пока что значат конкретные выражения, просто понаблюдайте за порядком.
Как только Arduino включается, перепрошивается или нажимается кнопка RESET , «нечто» вызывает функцию setup . То есть заставляет исполняться выражения в ней.
Как только работа loop завершается, сразу же «нечто» вызывает функцию loop ещё раз и так до бесконечности.
Если пронумеровать выражения по порядку, как они исполняются, получится:
Ещё раз напомним, что не стоит пытаться воспринимать всю программу, читая сверху вниз. Сверху вниз читается только содержимое блоков. Мы вообще можем поменять порядок объявлений setup и loop .
Результат от этого не изменится ни на йоту: после компиляции вы получите абсолютно эквивалентный бинарный файл.
Что делают выражения
Теперь давайте попробуем понять почему написанная программа приводит в итоге к миганию светодиода.
Как известно, пины Arduino могут работать и как выходы и как входы. Когда мы хотим чем-то управлять, то есть выдавать сигнал, нам нужно перевести управляющий пин в состояние работы на выход. В нашем примере мы управляем светодиодом на 13-м пине, поэтому 13-й пин перед использованием нужно сделать выходом.
Это делается выражением в функции setup :
Выражения бывают разными: арифметическими, декларациями, определениями, условными и т.д. В данном случае мы в выражении осуществляем вызов функции. Помните? У нас есть свои функции setup и loop , которые вызываются чем-то, что мы назвали «нечто». Так вот теперь мы вызываем функции, которые уже написаны где-то.
Конкретно в нашем setup мы вызываем функцию с именем pinMode . Она устанавливает заданный по номеру пин в заданный режим: вход или выход. О каком пине и о каком режиме идёт речь указывается нами в круглых скобках, через запятую, сразу после имени функции. В нашем случае мы хотим, чтобы 13-й пин работал как выход. OUTPUT означает выход, INPUT — вход.
Уточняющие значения, такие как 13 и OUTPUT называются аргументами функции. Совершенно не обязательно, что у всех функций должно быть по 2 аргумента. Сколько у функции аргументов зависит от сути функции, от того как её написал автор. Могут быть функции с одним аргументом, тремя, двадцатью; функции могут быть без аргументов вовсе. Тогда для их вызова круглые скобка открывается и тут же закрывается:
На самом деле, вы могли заметить, наши функции setup и loop также не принимают никакие аргументы. И загадочное «нечто» точно так же вызывает их с пустыми скобками в нужный момент.
Вернёмся к нашему коду. Итак, поскольку мы планируем вечно мигать светодиодом, управляющий пин должен один раз быть сделан выходом и затем мы не хотим вспоминать об этом. Для этого идеологически и предназначена функция setup : настроить плату как нужно, чтобы затем с ней работать.
Перейдём к функции loop :
Она, как говорилось, вызывается сразу после setup . И вызывается снова и снова как только сама заканчивается. Функция loop называется основным циклом программы и идеологически предназначена для выполнения полезной работы. В нашем случае полезная работа — мигание светодиодом.
Пройдёмся по выражениям по порядку. Итак, первое выражение — это вызов встроенной функции digitalWrite . Она предназначена для подачи на заданный пин логического нуля ( LOW , 0 вольт) или логической единицы ( HIGH , 5 вольт) В функцию digitalWrite передаётся 2 аргумента: номер пина и логическое значение. В итоге, первым делом мы зажигаем светодиод на 13-м пине, подавая на него 5 вольт.
Как только это сделано процессор моментально приступает к следующему выражению. У нас это вызов функции delay . Функция delay — это, опять же, встроенная функция, которая заставляет процессор уснуть на определённое время. Она принимает всего один аргумент: время в миллисекундах, которое следует спать. В нашем случае это 100 мс.
Пока мы спим всё остаётся как есть, т.е. светодиод продолжает гореть. Как только 100 мс истекают, процессор просыпается и тут же переходит к следующему выражению. В нашем примере это снова вызов знакомой нам встроенной функции digitalWrite . Правда на этот раз вторым аргументом мы передаём значение LOW . То есть устанавливаем на 13-м пине логический ноль, то есть подаём 0 вольт, то есть гасим светодиод.
После того, как светодиод погашен мы приступаем к следующему выражению. И снова это вызов функции delay . На этот раз мы засыпаем на 900 мс.
Как только сон окончен, функция loop завершается. По факту завершения «нечто» тут же вызывает её ещё раз и всё происходит снова: светодиод поджигается, горит, гаснет, ждёт и т.д.
The open-source Arduino Software (IDE) makes it easy to write code and upload it to the board. This software can be used with any Arduino board.
Refer to the Getting Started page for Installation instructions.
SOURCE CODE
Active development of the Arduino software is hosted by GitHub. See the instructions for building the code. Latest release source code archives are available here. The archives are PGP-signed so they can be verified using this gpg key.
DOWNLOAD OPTIONS
Hourly Builds
Download a preview of the incoming release with the most updated features and bugfixes.
DOWNLOAD OPTIONS
Previous Releases
Download the previous version of the current release, the classic 1.0.x, or old beta releases.
DOWNLOAD OPTIONS
Arduino with Chromebook
To program Arduino from a Chromebook, you can use the Arduino Web Editor on Arduino Cloud. The desktop version of the IDE is not available on Chrome OS.
Future Version of the Arduino IDE
Arduino IDE 2.0 RC (2.0.0-rc6)
The new major release of the Arduino IDE is faster and even more powerful! In addition to a more modern editor and a more responsive interface it features autocompletion, code navigation, and even a live debugger.
The Arduino IDE 2.0 is now moving to stable status with a series of Release Candidate (RC) builds. Community feedback is key to us, and you can use this survey form to send your feedback to us!
Nightly builds with the latest bugfixes are available through the section below.
SOURCE CODE
The Arduino IDE 2.0 is open source and its source code is hosted on GitHub.
DOWNLOAD OPTIONS
Nightly Builds
Download a preview of the incoming release with the most updated features and bugfixes.
Other Downloads
OpenWRT - Yún 1.5.3 Upgrade Image
Download the latest stable GNU/Linux OS for your Yún. It makes your Yún more stable and feature rich.
Easy Installation Procedure (recommended)
Advanced Installation Procedure
This procedure is only recommended to advanced users who wish to completely re-flash the Yún including its U-Boot bootloader. These instructions on reflashing the base images are for reference only. Following them will void your Yún's warranty.
Terms of Service
By downloading the software from this page, you agree to the specified terms.
The Arduino software is provided to you "as is" and we make no express or implied warranties whatsoever with respect to its functionality, operability, or use, including, without limitation, any implied warranties of merchantability, fitness for a particular purpose, or infringement. We expressly disclaim any liability whatsoever for any direct, indirect, consequential, incidental or special damages, including, without limitation, lost revenues, lost profits, losses resulting from business interruption or loss of data, regardless of the form of action or legal theory under which the liability may be asserted, even if advised of the possibility or likelihood of such damages.
The Arduino Integrated Development Environment - or Arduino Software (IDE) - contains a text editor for writing code, a message area, a text console, a toolbar with buttons for common functions and a series of menus. It connects to the Arduino hardware to upload programs and communicate with them.
)
Writing Sketches
Programs written using Arduino Software (IDE) are called sketches. These sketches are written in the text editor and are saved with the file extension .ino. The editor has features for cutting/pasting and for searching/replacing text. The message area gives feedback while saving and exporting and also displays errors. The console displays text output by the Arduino Software (IDE), including complete error messages and other information. The bottom righthand corner of the window displays the configured board and serial port. The toolbar buttons allow you to verify and upload programs, create, open, and save sketches, and open the serial monitor.
NB: Versions of the Arduino Software (IDE) prior to 1.0 saved sketches with the extension .pde. It is possible to open these files with version 1.0, you will be prompted to save the sketch with the .ino extension on save.
Verify Checks your code for errors compiling it.
Upload Compiles your code and uploads it to the configured board. See uploading below for details.
Note: If you are using an external programmer with your board, you can hold down the "shift" key on your computer when using this icon. The text will change to "Upload using Programmer"
New Creates a new sketch.
Open Presents a menu of all the sketches in your sketchbook. Clicking one will open it within the current window overwriting its content.
Note: due to a bug in Java, this menu doesn't scroll; if you need to open a sketch late in the list, use the File | Sketchbook menu instead.
Save Saves your sketch.
Additional commands are found within the five menus: File, Edit, Sketch, Tools, Help. The menus are context sensitive, which means only those items relevant to the work currently being carried out are available.
New Creates a new instance of the editor, with the bare minimum structure of a sketch already in place.
Open Allows to load a sketch file browsing through the computer drives and folders.
Open Recent Provides a short list of the most recent sketches, ready to be opened.
Sketchbook Shows the current sketches within the sketchbook folder structure; clicking on any name opens the corresponding sketch in a new editor instance.
Examples Any example provided by the Arduino Software (IDE) or library shows up in this menu item. All the examples are structured in a tree that allows easy access by topic or library.
Close Closes the instance of the Arduino Software from which it is clicked.
Save Saves the sketch with the current name. If the file hasn't been named before, a name will be provided in a "Save as.." window.
Save as. Allows to save the current sketch with a different name.
Page Setup It shows the Page Setup window for printing.
Print Sends the current sketch to the printer according to the settings defined in Page Setup.
Preferences Opens the Preferences window where some settings of the IDE may be customized, as the language of the IDE interface.
Quit Closes all IDE windows. The same sketches open when Quit was chosen will be automatically reopened the next time you start the IDE.
Undo/Redo Goes back of one or more steps you did while editing; when you go back, you may go forward with Redo.
Cut Removes the selected text from the editor and places it into the clipboard.
Copy Duplicates the selected text in the editor and places it into the clipboard.
Copy for Forum Copies the code of your sketch to the clipboard in a form suitable for posting to the forum, complete with syntax coloring.
Copy as HTML Copies the code of your sketch to the clipboard as HTML, suitable for embedding in web pages.
Paste Puts the contents of the clipboard at the cursor position, in the editor.
Select All Selects and highlights the whole content of the editor.
Comment/Uncomment Puts or removes the // comment marker at the beginning of each selected line.
Increase/Decrease Indent Adds or subtracts a space at the beginning of each selected line, moving the text one space on the right or eliminating a space at the beginning.
Find Opens the Find and Replace window where you can specify text to search inside the current sketch according to several options.
Find Next Highlights the next occurrence - if any - of the string specified as the search item in the Find window, relative to the cursor position.
Find Previous Highlights the previous occurrence - if any - of the string specified as the search item in the Find window relative to the cursor position.
Sketch
Verify/Compile Checks your sketch for errors compiling it; it will report memory usage for code and variables in the console area.
Upload Compiles and loads the binary file onto the configured board through the configured Port.
Upload Using Programmer This will overwrite the bootloader on the board; you will need to use Tools > Burn Bootloader to restore it and be able to Upload to USB serial port again. However, it allows you to use the full capacity of the Flash memory for your sketch. Please note that this command will NOT burn the fuses. To do so a Tools -> Burn Bootloader command must be executed.
Export Compiled Binary Saves a .hex file that may be kept as archive or sent to the board using other tools.
Show Sketch Folder Opens the current sketch folder.
Add File. Adds a supplemental file to the sketch (it will be copied from its current location). The file is saved to the data subfolder of the sketch, which is intended for assets such as documentation. The contents of the data folder are not compiled, so they do not become part of the sketch program.
Tools
Auto Format This formats your code nicely: i.e. indents it so that opening and closing curly braces line up, and that the statements inside curly braces are indented more.
Archive Sketch Archives a copy of the current sketch in .zip format. The archive is placed in the same directory as the sketch.
Fix Encoding & Reload Fixes possible discrepancies between the editor char map encoding and other operating systems char maps.
Serial Monitor Opens the serial monitor window and initiates the exchange of data with any connected board on the currently selected Port. This usually resets the board, if the board supports Reset over serial port opening.
Board Select the board that you're using. See below for descriptions of the various boards.
Port This menu contains all the serial devices (real or virtual) on your machine. It should automatically refresh every time you open the top-level tools menu.
Programmer For selecting a harware programmer when programming a board or chip and not using the onboard USB-serial connection. Normally you won't need this, but if you're burning a bootloader to a new microcontroller, you will use this.
Burn Bootloader The items in this menu allow you to burn a bootloader onto the microcontroller on an Arduino board. This is not required for normal use of an Arduino board but is useful if you purchase a new ATmega microcontroller (which normally come without a bootloader). Ensure that you've selected the correct board from the Boards menu before burning the bootloader on the target board. This command also set the right fuses.
Here you find easy access to a number of documents that come with the Arduino Software (IDE). You have access to Getting Started, Reference, this guide to the IDE and other documents locally, without an internet connection. The documents are a local copy of the online ones and may link back to our online website.
- Find in Reference This is the only interactive function of the Help menu: it directly selects the relevant page in the local copy of the Reference for the function or command under the cursor.
Sketchbook
The Arduino Software (IDE) uses the concept of a sketchbook: a standard place to store your programs (or sketches). The sketches in your sketchbook can be opened from the File > Sketchbook menu or from the Open button on the toolbar. The first time you run the Arduino software, it will automatically create a directory for your sketchbook. You can view or change the location of the sketchbook location from with the Preferences dialog.
Beginning with version 1.0, files are saved with a .ino file extension. Previous versions use the .pde extension. You may still open .pde named files in version 1.0 and later, the software will automatically rename the extension to .ino.
Tabs, Multiple Files, and Compilation
Allows you to manage sketches with more than one file (each of which appears in its own tab). These can be normal Arduino code files (no visible extension), C files (.c extension), C++ files (.cpp), or header files (.h).
Before compiling the sketch, all the normal Arduino code files of the sketch (.ino, .pde) are concatenated into a single file following the order the tabs are shown in. The other file types are left as is.
Uploading
When you upload a sketch, you're using the Arduino bootloader, a small program that has been loaded on to the microcontroller on your board. It allows you to upload code without using any additional hardware. The bootloader is active for a few seconds when the board resets; then it starts whichever sketch was most recently uploaded to the microcontroller. The bootloader will blink the on-board (pin 13) LED when it starts (i.e. when the board resets).
Libraries
There is a list of libraries in the reference. Some libraries are included with the Arduino software. Others can be downloaded from a variety of sources or through the Library Manager. Starting with version 1.0.5 of the IDE, you do can import a library from a zip file and use it in an open sketch. See these instructions for installing a third-party library.
To write your own library, see this tutorial.
Third-Party Hardware
Support for third-party hardware can be added to the hardware directory of your sketchbook directory. Platforms installed there may include board definitions (which appear in the board menu), core libraries, bootloaders, and programmer definitions. To install, create the hardware directory, then unzip the third-party platform into its own sub-directory. (Don't use "arduino" as the sub-directory name or you'll override the built-in Arduino platform.) To uninstall, simply delete its directory.
For details on creating packages for third-party hardware, see the Arduino Platform specification.
Serial Monitor
This displays serial sent from the Arduino board over USB or serial connector. To send data to the board, enter text and click on the "send" button or press enter. Choose the baud rate from the drop-down menu that matches the rate passed to Serial.begin in your sketch. Note that on Windows, Mac or Linux the board will reset (it will rerun your sketch) when you connect with the serial monitor. Please note that the Serial Monitor does not process control characters; if your sketch needs a complete management of the serial communication with control characters, you can use an external terminal program and connect it to the COM port assigned to your Arduino board.
You can also talk to the board from Processing, Flash, MaxMSP, etc (see the interfacing page for details).
Preferences
Some preferences can be set in the preferences dialog (found under the Arduino menu on the Mac, or File on Windows and Linux). The rest can be found in the preferences file, whose location is shown in the preference dialog.
Language Support
Since version 1.0.1 , the Arduino Software (IDE) has been translated into 30+ different languages. By default, the IDE loads in the language selected by your operating system. (Note: on Windows and possibly Linux, this is determined by the locale setting which controls currency and date formats, not by the language the operating system is displayed in.)
If you would like to change the language manually, start the Arduino Software (IDE) and open the Preferences window. Next to the Editor Language there is a dropdown menu of currently supported languages. Select your preferred language from the menu, and restart the software to use the selected language. If your operating system language is not supported, the Arduino Software (IDE) will default to English.
You can return the software to its default setting of selecting its language based on your operating system by selecting System Default from the Editor Language drop-down. This setting will take effect when you restart the Arduino Software (IDE). Similarly, after changing your operating system's settings, you must restart the Arduino Software (IDE) to update it to the new default language.
Boards
The board selection has two effects: it sets the parameters (e.g. CPU speed and baud rate) used when compiling and uploading sketches; and sets and the file and fuse settings used by the burn bootloader command. Some of the board definitions differ only in the latter, so even if you've been uploading successfully with a particular selection you'll want to check it before burning the bootloader. You can find a comparison table between the various boards here.
Arduino Software (IDE) includes the built in support for the boards in the following list, all based on the AVR Core. The Boards Manager included in the standard installation allows to add support for the growing number of new boards based on different cores like Arduino Due, Arduino Zero, Edison, Galileo and so on.
Arduino Yún An ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20 Digital I/O and 7 PWM.
Arduino Uno An ATmega328P running at 16 MHz with auto-reset, 6 Analog In, 14 Digital I/O and 6 PWM.
Arduino Diecimila or Duemilanove w/ ATmega168 An ATmega168 running at 16 MHz with auto-reset.
Arduino Nano w/ ATmega328P An ATmega328P running at 16 MHz with auto-reset. Has eight analog inputs.
Arduino Mega 2560 An ATmega2560 running at 16 MHz with auto-reset, 16 Analog In, 54 Digital I/O and 15 PWM.
Arduino Mega An ATmega1280 running at 16 MHz with auto-reset, 16 Analog In, 54 Digital I/O and 15 PWM.
Arduino Mega ADK An ATmega2560 running at 16 MHz with auto-reset, 16 Analog In, 54 Digital I/O and 15 PWM.
Arduino Leonardo An ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20 Digital I/O and 7 PWM.
Arduino Micro An ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20 Digital I/O and 7 PWM.
Arduino Esplora An ATmega32u4 running at 16 MHz with auto-reset.
Arduino Mini w/ ATmega328P An ATmega328P running at 16 MHz with auto-reset, 8 Analog In, 14 Digital I/O and 6 PWM.
Arduino Ethernet Equivalent to Arduino UNO with an Ethernet shield: An ATmega328P running at 16 MHz with auto-reset, 6 Analog In, 14 Digital I/O and 6 PWM.
Arduino Fio An ATmega328P running at 8 MHz with auto-reset. Equivalent to Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328P, 6 Analog In, 14 Digital I/O and 6 PWM.
Arduino BT w/ ATmega328P ATmega328P running at 16 MHz. The bootloader burned (4 KB) includes codes to initialize the on-board Bluetooth® module, 6 Analog In, 14 Digital I/O and 6 PWM..
LilyPad Arduino USB An ATmega32u4 running at 8 MHz with auto-reset, 4 Analog In, 9 Digital I/O and 4 PWM.
LilyPad Arduino An ATmega168 or ATmega132 running at 8 MHz with auto-reset, 6 Analog In, 14 Digital I/O and 6 PWM.
Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328P An ATmega328P running at 16 MHz with auto-reset. Equivalent to Arduino Duemilanove or Nano w/ ATmega328P; 6 Analog In, 14 Digital I/O and 6 PWM.
Arduino NG or older w/ ATmega168 An ATmega168 running at 16 MHzwithout auto-reset. Compilation and upload is equivalent to Arduino Diecimila or Duemilanove w/ ATmega168, but the bootloader burned has a slower timeout (and blinks the pin 13 LED three times on reset); 6 Analog In, 14 Digital I/O and 6 PWM.
Arduino Robot Control An ATmega328P running at 16 MHz with auto-reset.
Arduino Robot Motor An ATmega328P running at 16 MHz with auto-reset.
Arduino Gemma An ATtiny85 running at 8 MHz with auto-reset, 1 Analog In, 3 Digital I/O and 2 PWM.
For instructions on installing support for other boards, see third-party hardware above.
Мы решили сэкономить вам пару кликов и разместить у себя свежие версии среды Arduino IDE, потому что на официальном сайте порой чёрт ногу сломит, пока найдёт нужную ссылку. Где скачать Arduino IDE — ваш выбор: файлы дистрибутивов абсолютно идентичны. Сейчас представлена стабильная версия Arduino IDE 1.8.19 (релиз от 20.12.2021) и релиз-кандидат 2.0 RC5 (2.0.0-rc5 от 10.03.2022).
-
— Windows XP, Windows 7, Windows 8, Windows 10 и выше. — установка без прав админа, портативная версия для флешки.
Для установки из архива в общем случае нужно выполнить следующие команды.
В отдельных дистрибутивах Linux проще воспользоваться командой установки из пакетов.
Как переключить язык
Arduino IDE при установке выбирает язык системы по умолчанию. Если вам понадобится переключить интерфейс на другой язык, это можно сделать в общих настройках программы.
- Заходим в главном меню в пункт «Файл → Настройки».
- Выбираем нужный язык в выпадающем списке «Язык редактора».
- Перезапускаем среду.
Arduino IDE 2.0
-
— Windows 10 (x86-64) и новее. — установка из архива. — версия для Linux-систем с архитектурой x86-64. — macOS X 10.14 Mojave (64 бита) или новее.
Поддерживаемые платы
Arduino IDE из коробки работает со всеми оригинальными платами AVR-архитектуры и их прямыми аналогами.
Также поддерживаются сторонние платы и контроллеры на других архитектурах: SAM, SAMD, Cortex-M. Они добавляются в среду отдельными пакетами. Ниже перечислены примеры установки некоторых таких плат.
Рассмотрим начало работы с Arduino IDE в операционной системе Windows на примере Uno. Для других плат разница минимальна — эти особенности перечислены на страницах описания конкретных плат.
1. Установка Arduino IDE под Windows
Установите на компьютер интегрированную среду разработки Arduino IDE.
Последняя стабильная версия всегда доступна на нашем сайте.
Шаг 1
Выберите версию среды в зависимости от операционной системы.
Шаг 2
Нажмите на кнопку «JUST DOWNLOAD» для бесплатной загрузки программы.
2. Запуск Arduino IDE
Запустите среду программирования.
Arduino IDE не запускается?
Вероятнее всего, на компьютере некорректно установлена JRE — Java Runtime Environment. Для решения проблемы переустановите программу.
3. Подключение платы Arduino к компьютеру
Соедините Arduino с компьютером по USB-кабелю. На плате загорится светодиод «ON» и начнёт мигать светодиод «L». Это значит, что на плату подано питание и микроконтроллер начал выполнять прошитую на заводе программу «Blink».
Для настройки Arduino IDE под конкретную модель узнайте, какой номер COM-порта присвоил компьютер вашей плате. Зайдите в «Диспетчер устройств» Windows и раскройте вкладку «Порты (COM и LPT)».
Операционная система распознала плату Arduino как COM-порт и назначила номер 2 . Если вы подключите к компьютеру другую плату, операционная система назначит ей другой номер. Если у вас несколько платформ, очень важно не запутаться в номерах COM-портов.
Что-то пошло не так?
После подключения Arduino к компьютеру, в диспетчере устройств не появляются новые устройства? Это может быть следствием следующих причин:
4. Настройка Arduino IDE
Для работы среды Arduino IDE с конкретной платформой необходимо выбрать название модели и номер присвоенного плате COM-порта.
Для выбора модели Arduino зайдите в меню: Инструменты Плата и укажите соответствующую плату.
Для выбора номера COM-порта перейдите в меню: Инструменты Порт и укажите нужный порт.
Поздравляем, среда Arduino IDE настроена для прошивки вашей платы.
Что-то пошло не так?
Список последовательных портов пуст? Значит, платформа некорректно подключена к компьютеру или не установлен драйвер. Вернитесь к настройке соединения между платой и ПК.
Arduino IDE тормозит при навигации по меню? Отключите в диспетчере устройств все внешние устройства типа «Bluetooth Serial». Например, виртуальное устройство для соединения с мобильным телефоном по Bluetooth может вызвать такое поведение.
5. Загрузка первого скетча
Среда настроена, плата подключена. Пора прошивать платформу.
Arduino IDE содержит большой список готовых примеров, в которых можно быстро подсмотреть решение какой-либо задачи.
Откройте распространенный пример — «Blink»: Файл Примеры 01.Basics Blink .
Откроется окно с демонстрационным примером.
Полная версия кода:
Нажмите на иконку «Компиляция» для проверки кода на ошибки.
Нажмите на иконку «Загрузка» для заливки на плату.
После прошивки платформы светодиод «L» начнёт загораться и гаснуть каждые 100 миллисекунд — в 10 раз быстрее исходной версии. Это значит, что ваш тестовый код успешно загрузился и заработал. Теперь смело переходите к экспериментам на Arduino.
Ресурсы
Если не указано иное, содержимое этой вики предоставляется на условиях следующей лицензии: CC Attribution-Noncommercial-Share Alike 4.0 International
Читайте также: