Андрей Смирнов
Время чтения: ~19 мин.
Просмотров: 29

Ардуино язык программирования: основные понятия

Содержание статьи

Libraries

The Arduino environment can be extended through the use of libraries, just like most programming platforms. Libraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating data. To use a library in a sketch, select it from Sketch > Import Library. A number of libraries come installed with the IDE, but you can also download or create your own. See these instructions for details on installing libraries. There’s also a tutorial on writing your own libraries. See the API Style Guide for information on making a good Arduino-style API for your library.

Standard Libraries

  • EEPROM — reading and writing to «permanent» storage
  • Ethernet — for connecting to the internet using the Arduino Ethernet Shield, Arduino Ethernet Shield 2 and Arduino Leonardo ETH
  • Firmata — for communicating with applications on the computer using a standard serial protocol.
  • GSM — for connecting to a GSM/GRPS network with the GSM shield.
  • LiquidCrystal — for controlling liquid crystal displays (LCDs)
  • SD — for reading and writing SD cards
  • Servo — for controlling servo motors
  • SPI — for communicating with devices using the Serial Peripheral Interface (SPI) Bus
  • Stepper — for controlling stepper motors
  • TFT — for drawing text , images, and shapes on the Arduino TFT screen
  • WiFi — for connecting to the internet using the Arduino WiFi shield
  • Wire — Two Wire Interface (TWI/I2C) for sending and receiving data over a net of devices or sensors.

The Matrix and Sprite libraries are no longer part of the core distribution.

101 Only Libraries

  • CurieBLE — Interact with smartphones and tablets with Bluetooth Low Energy (BLE).
  • CurieIMU — Manage the on-board accelerometer and gyro.
  • CurieTimerOne — Allows to use Timer functions.
  • CurieTime — Allows to control and use the internal RTC (Real Time Clock)

Due, Zero and MKR1000 Libraries

  • USBHost — Communicate with USB peripherals like mice and keyboards.
  • Scheduler — Manage multiple non-blocking tasks.

Zero and all the SAMD21 based MKR boards libraries

  • AudioFrequencyMeter — Sample an audio signal and get its frequency back
  • AudioZero — Play audio files from a SD card
  • RTC — Real Time Clock to schedule events
  • ArduinoSound — A simple way to play and analyze audio data
  • I2S — To use the I2S protocol on SAMD21

Arduino Nano 33 IoT and UNO WiFi Rev. 2

ArduinoLSM6DS3 — library to use the LSM6DS3 6 axis IMU available on the Arduino Nano 33 IoT and the Arduino UNO WiFi Rev. 2.

Arduino Nano 33 BLE and BLE Sense

ArduinoLSM9DS1 — library to use the LSM9DS1 9 axis IMU available on the Arduino Nano 33 BLE and the Arduino Nano 33 BLE Sense.

Arduino Nano 33 BLE Sense

  • PDM — library to use the digital microphone MP34DT05, our library PDM can be used also with our ArduinoSound library.
  • ArduinoAPDS9960 — library to use the gesture sensor APDS9960; it senses gesture, color, ambience illumination and proximity.
  • ArduinoLPS22HB — library to use the barometer and temperature sensor LPS22; it is an ultra-compact sensor which functions as a digital output barometer.
  • ArduinoHTS221 — library to use the relative humidity sensor HTS221; it is an ultra-compact sensor that uses a polymer dielectric planar capacitor structure capable of detecting relative humidity variations, returned as digital output on a serial interface.

MKR RGB Shield Libraries

  • ArduinoMKRRGB — library to be used with the Arduino MKR RGB Shield
  • ArduinoGraphics — library with graphic primitives, works also with the MKR RGB Shield

Yún devices Library

  • Bridge Library — Enables communication between the Linux processor and the microcontroller on the Yún.
  • Ciao Library — Aims to simplify interaction between microcontroller and Linino OS allowing a variety of connections with most common protocols

Contributed Libraries

If you’re using one of these libraries, you need to install it first. See these instructions for details on installation. There’s also a tutorial on writing your own libraries.

Communication (networking and protocols):

  • X10 — Sending X10 signals over AC power lines

Sensing:

Displays and LEDs:

Audio and Waveforms:

Motors and PWM:

TLC5940 — 16 channel 12 bit PWM controller.

Timing:

Utilities:

Из чего состоит Arduino?

На аппаратном уровне это серия смонтированных плат, мозгом которых являются микроконтроллеры семейства AVR.

Платы имеют на борту всё необходимое для комфортной работы, но их функциональности часто бывает недостаточно. Чтобы сделать свой проект более интерактивным, можно использовать различные модули и платы расширений, совместимые с платформой Arduino. Сюда входят датчики (температуры, освещения, влаги, газа/дыма, атмосферного давления), устройства ввода (клавиатуры, джойстики, сенсорные панели) и вывода (сегментные индикаторы, LCD/TFT дисплеи, светодиодные матрицы).

На программном уровне платформа Arduino представляет собой бесплатную среду разработки Arduino IDE. Микроконтроллеры надо программировать на языке C++, с некоторыми отличиями и облегчениями, созданными для быстрой адаптации начинающих. Компиляцию программного кода и прошивку микроконтроллера среда разработки берёт на себя.

Существует также s4a.cat — сервис, базирующийся на Scratch, позволяющий более наглядно вести разработку на Arduino. Он подойдёт для обучения детей, а также если вы разово хотите создать простое устройство без изучения языка программирования Arduino и различных документаций. Для остальных же случаев лучше придерживаться традиционного процесса разработки.

2

Общее описание языков программирования

Как я и писал выше, рассматривать мы с вами будем две популярные среды разработки. По аналогии с CoDeSyS 2.3, можно разделить на графический редактор и “умный блокнот”. Это программы Arduino IDE и FLprog.

Основой среды разработки является Processing/Wiring — это обычный C++, дополненный функциями и различными библиотеками. Существует несколько версий для операционных систем windows, Mac OS и Linux.

В чём их принципиальное различие?? Arduino IDE — это среда разработки, в которой описывается код программы. А FLprog похож на CFC CoDeSyS, позволяющий рисовать диаграммы. Какая среда лучше? Обе хороши и удобны по своему, но если хотите заниматься контроллерами серьёзно, лучше всего изучить языки, похожие на СИ. Их главный плюс в гибкости и неограниченности алгоритма. Мне очень нравится Arduino IDE.

Как настроить Ардуино на компьютере?

Делается это просто. Необходимо выполнить следующие действия:

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

Важно! При подключении вашей платы к другому USB порту все настройки будет необходимо произвести заново.

Digital Read Serial

This example shows you how to monitor the state of a switch by establishing serial communication between your Arduino or Genuino and your computer over USB.

Circuit

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Connect three wires to the board. The first two, red and black, connect to the two long vertical rows on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pull-down resistor (here 10k ohm) to ground. The other leg of the button connects to the 5 volt supply.

Pushbuttons or switches connect two points in a circuit when you press them. When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected to ground (through the pull-down resistor) and reads as LOW, or 0. When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts, so that the pin reads as HIGH, or 1.

If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is because the input is «floating» — that is, it doesn’t have a solid connection to voltage or ground, and it will randomly return either HIGH or LOW. That’s why you need a pull-down resistor in the circuit.

Code

In the program below, the very first thing that you do will in the setup function is to begin serial communications, at 9600 bits of data per second, between your board and your computer with the line:

Next, initialize digital pin 2, the pin that will read the output from your button, as an input:

Now that your setup has been completed, move into the main loop of your code. When your button is pressed, 5 volts will freely flow through your circuit, and when it is not pressed, the input pin will be connected to ground through the 10k ohm resistor. This is a digital input, meaning that the switch can only be in either an on state (seen by your Arduino as a «1», or HIGH) or an off state (seen by your Arduino as a «0», or LOW), with nothing in between.

The first thing you need to do in the main loop of your program is to establish a variable to hold the information coming in from your switch. Since the information coming in from the switch will be either a «1» or a «0», you can use an datatype. Call this variable , and set it to equal whatever is being read on digital pin 2. You can accomplish all this with just one line of code:

Once the board has read the input, make it print this information back to the computer as a decimal value. You can do this with the command Serial.println() in our last line of code:

Now, when you open your Serial Monitor in the Arduino Software (IDE), you will see a stream of «0»s if your switch is open, or «1»s if your switch is closed.

See Also:

  • setup()

  • loop()

  • pinMode()

  • digitalRead()

  • delay()

  • AnalogReadSerial — Read a potentiometer, print its state out to the Arduino Serial Monitor.

  • BareMinimum — The bare minimum of code needed to start an Arduino sketch.

  • Blink — Turn an LED on and off.

  • Fade — Demonstrates the use of analog output to fade an LED.

  • ReadAnalogVoltage — Reads an analog input and prints the voltage to the serial monitor.

Last revision 2015/07/29 by SM

Советы от бывалых монтажников

Существует множество спорных вопросов как в способах соединений, так и в применении отдельных монтажных изделий. Но ряд правил касается абсолютно всех мастеров, которые занимаются электромонтажом.

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

Еще несколько важных правил:

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

При использовании изоленты накладывайте витки внахлест. Одного слоя недостаточно, лучше пройтись вдоль соединения 2-3 раза, обязательно сделав последний виток на изоляции

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

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

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

У нас на сайте также есть другие статьи по соединителям проводников, способам соединения проводов разного сечения и рекомендации по выбору лучшего коннектора:

  • Способы соединения электрических проводов: виды соединений + технические нюансы
  • Клеммы для соединения проводов: какие клеммники лучше и как с ними работать
  • Соединители проводов: лучшие виды коннекторов + на что смотреть при выборе соединителя

Arduino Howto

This page is obsolete. You should instead see the Windows Howto or the Mac OS X howto (both in the Arduino guide).

These are the steps you need to follow in order to be up and running:

  1. Get an Arduino board
  2. Download the Arduino environment
  3. Install the USB drivers
  4. Connect the board
  5. Upload a program

1 | Get an Arduino board

The Arduino i/o board is a simple circuit featuring the ATmega8 processor from Atmel. The board is composed of a printed circuit board (PCB) and electronic parts.

There are a few ways to get an Arduino board:

  • buy a ready made board. See how you can buy a board or just the PCB.
  • build your own board. If you want you can build your own PCB just by downloading the CAD files from the Hardware page. Extract the .brd file and send it to a PCB manufacturer. Be aware that manufacturing a single pcb will be very expensive. It’s better to get together with other people and make 20 or 30 at a time. Since you get the full CAD files you can make your own customised version of Arduino. if you make modifications or fix bugs please send us your changes!
    • purchase parts. purchase the parts from any electronics store. The Serial version in particular has been designed to use the most basic parts that can be found anywhere in the world. The USB version on the other hand requires some advanced soldering skills because of the FTDI chip that is an smd part. Here is a list of parts for the serial board.
    • assemble the board. We put together a step by step guide on how to build an arduino board.
    • program the bootloader. In order for the development environment to be able to program the chip, this has to be programmed with a piece of code called bootloader. See the bootloader page on how to program it on your chip.

2 | Download the Arduino environment

To program the Arduino board you need the Arduino environment.

Download Arduino:
From the software page.

Linux note: For help getting the Arduino IDE running on Debian, please see the FAQ («How can I run the Arduino IDE under Linux?»).

Mac OS X note: After downloading the IDE, run the . It corrects permission on a few files for use with the serial port and will prompt you for your password. You may need to reboot after running this script.

For more information, see the guide to the Arduino environment.

3 | Install the USB drivers

If you are using a USB Arduino, you will need to install the drivers for the FTDI chip on the board. These can be found in the directory of the Arduino distribution.

On Windows, you will need to unzip . Then, when you plug in the Arduino board, point the Windows Add Hardware wizard to the directory.

On the Mac, mount the (on PPC machines) or the (on Intel machines) disk image and run the included .

4 | Connect the board

If you’re using a serial board, power the board with an external power supply (6 to 25 volts DC, with the core of the connector positive). Connect the board to a serial port on your computer.

On the USB boards, the power source is selected by the jumper between the USB and power plugs. To power the board from the USB port (good for controlling low power devices like LEDs), place the jumper on the two pins closest to the USB plug. To power the board from an external power supply (needed for motors and other high current devices), place the jumper on the two pins closest to the power plug. Either way, connect the board to a USB port on your computer. On Windows, the Add New Hardware wizard will open; tell it you want to specify the location to search for drivers and point to the folder containing the USB drivers you unzipped in the previous step.

The power LED should go on.

5 | Upload a program

Open the LED blink example sketch: File > Sketchbook > Examples > led_blink.

Here’s what the code for the LED blink example looks like.

Select the serial device of the Arduino board from the Tools | Serial Port menu. On Windows, this should be or for a serial Arduino board, or , , or for a USB board. On the Mac, this should be something like for a USB board, or something like if using a Keyspan adapter with a serial board (other USB-to-serial adapters use different names).

Push the reset button on the board then click the Upload button in the IDE. Wait a few seconds. If successful, the message «Done uploading.» will appear in the status bar.

If the Arduino board doesn’t show up in the Tools | Serial Port menu, or you get an error while uploading, please see the FAQ for troubleshooting suggestions.

A few seconds after the upload finishes, you should see the amber (yellow) LED on the board start to blink.

Learn More

  • Read about the Arduino Environment
  • Learn about the parts of the Arduino board
  • See the tutorials for some example programs. (There are also some examples available in the directory inside the arduino directory.)
  • Look up specific Arduino functions and syntax in the reference
  • If you’re having problems, check the FAQ.

Существуют ли еще программы, работающие с Ардуино?

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

Аналогичный набор функций нам может предоставить программа, которая называется Processing. Она очень схожа с Arduino IDE, так как обе сделаны на одном движке. Processing имеет обширный набор функций, который мало уступает оригинальной программе. С помощью загружаемой библиотеки Serial пользователь может создать связь между передачей данных, которые передают друг другу плата и Processing.При этом мы можем заставить плату выполнять программы прямо с нашего ПК.

Существует еще одна интересная версия исходной программы. Называется она B4R, и главным ее отличием является использование в качестве основы не языка си, а другой язык программирования – Basic. Данный программный продукт является бесплатным. Для работы с ним существуют хорошие самоучители, в том числе и написанные создателями данного продукта.

Есть и платные варианты Arduino IDE. Одним из таких является программа PROGROMINO. Главным ее достоинством считается возможность автодополнения кода. При составлении программы вам больше не нужно будет искать информацию в справочниках. Программа сама предложит вам возможные варианты использования той или иной процедуры. В ее набор входит еще множество интересных функций, отсутствующих в оригинальной программе и способных облегчить вам работу с платами.

Что можно и чего нельзя

Арду­и­но рабо­та­ет на одно­ядер­ном и не шиб­ко шуст­ром про­цес­со­ре. Его так­то­вая часто­та — 16 мега­герц, то есть 16 мил­ли­о­нов про­цес­сор­ных опе­ра­ций в секун­ду. Это не очень быст­ро, плюс ядро толь­ко одно, и оно испол­ня­ет одну коман­ду за дру­гой.

Вот какие огра­ни­че­ния это на нас накла­ды­ва­ет.

Нет насто­я­щей мно­го­за­дач­но­сти. Мож­но симу­ли­ро­вать мно­го­за­дач­ность с помо­щью при­ё­ма Protothreading, но это ско­рее костыль. Нель­зя, напри­мер, ска­зать: «Когда нажмёт­ся такая-то кноп­ка — сде­лай так». Вме­сто это­го при­дёт­ся в основ­ном цик­ле писать про­вер­ку: «А эта кноп­ка нажа­та? Если да, то…»

Нет поня­тия фай­лов (без допол­ни­тель­ных при­мо­чек, биб­лио­тек и желе­за). На кон­трол­лер нель­зя ниче­го сохра­нить, кро­ме управ­ля­ю­щей им про­грам­мы. К сча­стью, есть пла­ты рас­ши­ре­ния, кото­рые поз­во­ля­ют немнож­ко рабо­тать с фай­ла­ми на SD-карточках.

Ана­ло­гич­но с сетью: без допол­ни­тель­ных плат и биб­лио­тек Арду­и­но не может ни с чем общать­ся (кро­ме как включать-выключать элек­три­че­ство на сво­их выхо­дах).

Полег­че со слож­ной мате­ма­ти­кой: если вам нуж­но что-то слож­ное типа три­го­но­мет­ри­че­ских функ­ций, будь­те гото­вы к тому, что Арду­и­но будет счи­тать их доволь­но мед­лен­но. Для вас это одна строч­ка кода, а для Арду­и­но это тыся­чи опе­ра­ций под капо­том. Поща­ди­те.

Отчё­ты? Ошиб­ки? Толь­ко при ком­пи­ля­ции. У Арду­и­но нет встро­ен­ных средств сооб­щить вам, что ему нехо­ро­шо. Если он завис, он не пока­жет окно ошиб­ки: во-первых, у него нет гра­фи­че­ско­го интер­фей­са, во-вторых — экра­на. Если хоти­те систе­му оши­бок или отчёт­ность, пиши­те её

Если серьёз­но, то перед зали­вом про­грам­мы на кон­трол­лер ком­пи­ля­тор про­ве­рит код и най­дёт в нём опе­чат­ки или про­бле­мы с типа­ми дан­ных. Но на этом всё: если у вас слу­чай­но полу­чи­лась бес­ко­неч­ная пет­ля в коде или при каких-то обсто­я­тель­ствах вы пове­си­те про­цес­сор деле­ни­ем на ноль — жми­те пере­за­груз­ку и исправ­ляй­те код.

Какие ещё языки используют для Arduino

Но чу! Под Arduino мож­но писать и на дру­гих язы­ках!

С. Как и С++, Си лег­ко мож­но исполь­зо­вать для про­грам­ми­ро­ва­ния мик­ро­кон­трол­ле­ров Arduino. Толь­ко если С++ не тре­бу­ет ника­ких допол­ни­тель­ных про­грамм, то для С вам пона­до­бит­ся , что­бы пра­виль­но пере­ве­сти код в язык, понят­ный кон­трол­ле­рам AVR.

Python. Было бы стран­но, если бы тако­му уни­вер­саль­но­му язы­ку не нашлось при­ме­не­ния в робо­то­тех­ни­ке. Берё­те биб­лио­те­ки PySerial и vPython, при­кру­чи­ва­е­те их к Python и гото­во!

Java. Прин­цип такой же, как в Python: берё­те биб­лио­те­ки для рабо­ты с пор­та­ми и кон­трол­ле­ра­ми и мож­но начи­нать про­грам­ми­ро­вать.

HTML. Это, конеч­но, совсем экзо­ти­ка, но есть про­ек­ты, кото­рые застав­ля­ют HTML-код рабо­тать на Arduino.

А вооб­ще Arduino рабо­та­ет на кон­трол­ле­рах AVR, и про­шить их мож­но любым кодом, кото­рый ском­пи­ли­ро­ван под это желе­зо. Всё, что вам нуж­но — най­ти биб­лио­те­ку для ваше­го люби­мо­го язы­ка, кото­рая пре­об­ра­зу­ет нуж­ные коман­ды в машин­ный код для AVR.

Главное — алгоритмы

Любой робот — это один боль­шой алго­ритм. Что­бы научить­ся думать как про­грам­мист и писать свои алго­рит­мы с нуля, при­хо­ди­те в Прак­ти­кум.
Попро­бо­вать

Рейтинг автора
5
Материал подготовил
Максим Иванов
Наш эксперт
Написано статей
129
Ссылка на основную публикацию
Похожие публикации