Содержание
- 1 Содержание статьи
- 2 Libraries
- 3 Из чего состоит Arduino?
- 4 Общее описание языков программирования
- 5 Как настроить Ардуино на компьютере?
- 6 Digital Read Serial
- 7 Советы от бывалых монтажников
- 8 Arduino Howto
- 9 Существуют ли еще программы, работающие с Ардуино?
- 10 Что можно и чего нельзя
- 11 Какие ещё языки используют для Arduino
Содержание статьи
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:
- Get an Arduino board
- Download the Arduino environment
- Install the USB drivers
- Connect the board
- 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.
Главное — алгоритмы
Любой робот — это один большой алгоритм. Чтобы научиться думать как программист и писать свои алгоритмы с нуля, приходите в Практикум.
Попробовать