Главная chevron_right Уроки chevron_right Программирование chevron_right Справочник Arduino API

Справочник Arduino API

Компактный справочник по языку программирования Arduino: функции, переменные, операторы и структура скетча в одном месте.

Это сжатая версия Arduino Language Reference — своего рода TLDR; по Arduino API. Здесь собраны все ключевые функции, типы данных и операторы, которые нужны при написании скетчей.

Обратите внимание: по состоянию на 15.01.2024 статья ещё находится в разработке.

---

Функции

Цифровой ввод/вывод (Digital I/O)

Method & ParametersDescriptionReturns
int digitalRead(int pin)Reads the state of a digital pin.int
void digitalWrite(int pin, int state)Writes a state to a digital pin.Nothing
void pinMode(int pin, int mode)*Define the mode of a pin.Nothing

*Доступные режимы пина:

  • INPUT (0) — вход
  • OUTPUT (1) — выход
  • INPUT_PULLUP (2) — вход с подтяжкой к питанию
  • INPUT_PULLDOWN (3) — вход с подтяжкой к земле
  • OUTPUT_OPENDRAIN (4) — выход с открытым коллектором

Практическое замечание. Режим INPUT_PULLUP особенно удобен для кнопок: он избавляет от необходимости ставить внешний резистор. INPUT_PULLDOWN поддерживается не всеми платами — проверяйте документацию своей архитектуры.

Аналоговый ввод/вывод (Analog I/O)

Method & ParametersDescriptionReturns
int analogRead(int pin)Reads the value of an analog pin in a 10-bit resolution (0-1023).*int
void analogReadResolution(int resolution)Sets ADC read resolution in bits.Nothing
void analogReference(int reference)Changes the voltage reference for a board.**Nothing
void analogWrite(int pin, int value)Writes a value to a PWM supported pin in a 8-bit resolution (0-255).**Nothing
void analogWriteResolution(int resolution)Sets write resolution for a board.Nothing
  • *Диапазон значений зависит от разрядности АЦП: 0–1023 при 10-битном разрешении, 0–4095 при 12-битном и т. д.
  • **Набор доступных опорных напряжений зависит от платы и архитектуры.
  • *Диапазон значений ШИМ зависит от разрядности: по умолчанию 0–255 (8 бит).

Типичная ошибка. Если analogRead() возвращает нестабильные значения, убедитесь, что аналоговый пин не «висит в воздухе» — подключите его через резистор к известному потенциалу.

Расширенный ввод/вывод (Advanced I/O)

Method & ParametersDescriptionReturns
void tone(int pin, int frequency, long duration)Generates a square wave on specified pin, with 50% duty cycle.Nothing
void noTone(int pin)Stops generation of square wave on the specified pin.Nothing
long pulseIn(int pin, int state, long timeout)Reads a pulse (either HIGH or LOW) on a pin and returns the length of the pulse (in microseconds)long
long pulseInLong(int pin, int state, long timeout)Returns the length of the pulse (in microseconds)long
int shiftIn(int pin, int clockPin, int bitOrder)*Shifts in a byte of data one bit at a time, and returns the value of the bit read.byte
void shiftOut(int pin, int clockPin, int bitOrder, byte value)**Shifts out a byte of data one bit at a time.Nothing
  • *Параметр bitOrder задаёт порядок битов: MSBFIRST (1) — старший бит первым, или LSBFIRST (0) — младший бит первым.
  • **Пин, используемый для shiftOut(), должен быть предварительно настроен как OUTPUT с помощью pinMode().

Как это работает. shiftOut() реализует программный SPI: данные передаются побитово через два пина (данные и тактирование). Это медленнее аппаратного SPI, но не требует специальных пинов.

Время (Time)

Method & ParametersDescriptionReturns
void delay(long milliseconds)Freezes program execution for specified number of milliseconds.Nothing
void delayMicroseconds(int microseconds)Freezes program execution for specified number of microseconds.Nothing
long millis()Returns milliseconds passed since program start.long
long micros()Returns microseconds passed since program start.long

Практическое замечание. millis() и micros() переполняются примерно через 50 дней и 70 минут соответственно. Для корректного отсчёта интервалов всегда вычитайте сохранённое значение из текущего, а не сравнивайте их напрямую.

Математические функции (Math)

Method & ParametersDescriptionReturns
int abs(int value)Calculates the absolute value of a number.int
int constrain(int value, int min, int max)Constrains a number to be within a range.int
long map(long val, long min, long max, long newMin, long newMax)Re-maps a number from one range to another.long
int max(int val1, int val2)Returns the greater of two values.int
int min(int val1, int val2)Returns the smaller of two values.int
double pow(double base, double exponent)Raises a base to the power of an exponent.double
int sq(int value)Calculates the square of a number.int
double sqrt(double value)Calculates the square root of a number.double

Тригонометрия (Trigonometry)

Method & ParametersDescriptionReturns
cos(double angle)Calculates the cosine of an angle in radians.double
sin(double angle)Calculates the sine of an angle in radians.double
tan(double angle)Calculates the tangent of an angle in radians.double

Работа с символами (Characters)

Method & ParametersDescriptionReturns
boolean isAlpha(char c)Checks if the character is an alphabetic character.boolean
boolean isAlphaNumeric(char c)Checks if the character is an alphanumeric character.boolean
boolean isAscii(char c)Checks if the character is a 7-bit ASCII character.boolean
boolean isControl(char c)Checks if the character is a control character.boolean
boolean isDigit(char c)Checks if the character is a digit (0-9).boolean
boolean isGraph(char c)Checks if the character is a printable character, excluding space.boolean
boolean isHexadecimalDigit(char c)Checks if the character is a hexadecimal digit (0-9, A-F, a-f).boolean
boolean isLowerCase(char c)Checks if the character is a lowercase alphabetic character.boolean
boolean isPrintable(char c)Checks if the character is a printable character, including space.boolean
boolean isPunct(char c)Checks if the character is a punctuation character.boolean
boolean isSpace(char c)Checks if the character is a whitespace character.boolean
boolean isUpperCase(char c)Checks if the character is an uppercase alphabetic character.boolean
boolean isWhitespace(char c)Checks if the character is a whitespace character according to isSpaceChar() method.boolean

Случайные числа (Random Numbers)

Method & ParametersDescriptionReturns
int random()Generates a pseudo-random number between 0 and RAND_MAX.int
void randomSeed(unsigned long seed)Seeds the random number generator.Nothing

Практическое замечание. Без вызова randomSeed() последовательность псевдослучайных чисел будет одинаковой при каждом запуске. Для инициализации часто используют analogRead() с незаземлённого пина.

Биты и байты (Bits and Bytes)

Method & ParametersDescriptionReturns
boolean bit(int value, int bitNumber)Gets the value of a specific bit.boolean
void bitClear(int &value, int bit)Clears a specific bit.Nothing
boolean bitRead(int value, int bitNumber)Reads the value of a specific bit.boolean
void bitSet(int &value, int bit)Sets a specific bit.Nothing
void bitWrite(int &value, int bit, int bitValue)Writes a value to a specific bit.Nothing
byte highByte(int value)Returns the high byte of an int.byte
byte lowByte(int value)Returns the low byte of an int.byte

Внешние прерывания (External Interrupts)

Method & ParametersDescriptionReturns
void attachInterrupt(int pin, void (*function)(void), int mode)Attaches an interrupt to a specific pin.Nothing
void detachInterrupt(int pin)Detaches an interrupt from a specific pin.Nothing

Типичная ошибка. Внутри обработчика прерывания (ISR) нельзя использовать delay() и Serial. Переменные, изменяемые в ISR, обязательно объявляйте с ключевым словом volatile.

Прерывания (Interrupts)

Method & ParametersDescriptionReturns
void interrupts()Enables interrupts globally.Nothing
void noInterrupts()Disables interrupts globally.Nothing

Stream

Method & ParametersDescriptionReturns
int available()Returns the number of bytes available in the serial buffer.int
int read()Reads the next byte from the serial buffer.int
void flush()Waits for the transmission of outgoing serial data to complete.Nothing
int find(char *target)Searches for a target string in the serial buffer.int
int findUntil(char *target, char *terminate)Searches for a target string until a specified termination string is found.int
int peek()Returns the next byte in the serial buffer without removing it.int
int readBytes(char *buffer, int length)Reads characters from the serial buffer into a buffer.int
int readBytesUntil(char terminator, char *buffer, int length)Reads characters from the serial buffer into a buffer until a terminator is found.int
String readString()Reads characters from the serial buffer into a String until a newline character is found.String
String readStringUntil(char terminator)Reads characters from the serial buffer into a String until a specified terminator is found.String
int parseInt()Reads characters from the serial buffer and converts them to an integer.int
float parseFloat()Reads characters from the serial buffer and converts them to a float.float
void setTimeout(unsigned long timeout)Sets the maximum duration for find(), findUntil(), parseInt(), and parseFloat().Nothing

Serial

Method & ParametersDescriptionReturns
if(Serial)Checks if the Serial object is available.boolean
int available()Returns the number of bytes available for reading.int
int availableForWrite()Returns the number of bytes available for writing.int
void begin(unsigned long baudrate)Initializes the Serial communication with the specified baud rate.void
void end()Ends the Serial communication.void
int find(char *target)Searches for a target string in the serial buffer.int
int findUntil(char *target, char *terminate)Searches for a target string until a specified termination string is found.int
void flush()Waits for the transmission of outgoing serial data to complete.void
float parseFloat()Reads characters from the serial buffer and converts them to a float.float
int parseInt()Reads characters from the serial buffer and converts them to an integer.int
int peek()Returns the next byte in the serial buffer without removing it.int
size_t print()Prints data to the serial port.size_t
size_t println()Prints data to the serial port followed by a newline character.size_t
int read()Reads the next byte from the serial buffer.int
int readBytes(char *buffer, size_t length)Reads characters from the serial buffer into a buffer.int
int readBytesUntil(char terminator, char *buffer, size_t length)Reads characters from the serial buffer into a buffer until a terminator is found.int
String readString()Reads characters from the serial buffer into a String until a newline character is found.String
String readStringUntil(char terminator)Reads characters from the serial buffer into a String until a specified terminator is found.String
void setTimeout(unsigned long timeout)Sets the maximum duration for find(), findUntil(), parseInt(), and parseFloat().void
size_t write(uint8_t)Writes a byte to the serial port.size_t
void serialEvent()Called when data is available in the serial buffer.void

SPI

Method & ParametersDescriptionReturns
SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode)Creates an SPISettings object with the specified clock, bit order, and data mode.SPISettings
void begin()Initializes the SPI library.void
void beginTransaction(SPISettings settings)Begins an SPI transaction with the specified settings.void
void endTransaction()Ends the current SPI transaction.void
void end()Ends the SPI library.void
void setBitOrder(uint8_t bitOrder)Sets the bit order (MSBFIRST or LSBFIRST) for SPI communication.void
void setClockDivider(uint8_t divider)Sets the clock divider for SPI communication.void
void setDataMode(uint8_t dataMode)Sets the data mode for SPI communication.void
byte transfer(byte value)Transfers a byte over SPI.byte
void usingInterrupt(int interruptNumber)Specifies which interrupt to use for SPI transactions.void

I2C (Wire)

Method & ParametersDescriptionReturns
void begin()Initializes the Wire library.void
void end()Ends the Wire library.void
int requestFrom(int address, int quantity)Requests data from a slave device with the specified address and quantity of bytes.int
void beginTransmission(int address)Begins a transmission to the slave device with the specified address.void
int endTransmission()Ends the transmission and returns the status.int
size_t write(uint8_t data)Writes a byte to the I2C bus.size_t
int available()Returns the number of bytes available for reading.int
int read()Reads a byte from the I2C bus.int
void setClock(uint32_t frequency)Sets the I2C clock frequency.void
void onReceive(void (*function)(int))Sets a function to be called when data is received by the slave.void
void onRequest(void (*function)(void))Sets a function to be called when the master requests data from the slave.void
void setWireTimeout(uint32_t timeout)Sets the timeout for I2C operations.void
void clearWireTimeoutFlag()Clears the timeout flag.void
bool getWireTimeoutFlag()Returns the timeout flag status.bool

---

Переменные

Перечисления (Enums)

Enum TypeEnumerationDescription
PinStatusHIGH / LOWLogical HIGH and LOW values (1 and 0).
PinModeINPUT / OUTPUT / INPUT_PULLUP / INPUT_PULLDOWN / OUTPUT_OPENDRAINConstants for specifying pin modes (0, 1, 2, 3, 4).
LED_BUILTINConstant representing the built-in LED pin.*
true / falseBoolean constants for true and false (1 and 0).

Преобразование типов (Conversion)

Method & ParameterDescription
(unsigned int)Type casting to unsigned int.
(unsigned long)Type casting to unsigned long.
byte()Type casting to byte.
char()Type casting to char.
float()Type casting to float.
int()Type casting to int.
long()Type casting to long.
word()Type casting to word.

Типы данных (Data Types)

Method & ParameterDescription
arrayCollection of variables of the same type.
boolBoolean data type.
booleanBoolean data type (synonym for bool).
byte8-bit unsigned data type.
char8-bit character data type.
doubleDouble-precision floating-point data type.
floatSingle-precision floating-point data type.
intInteger data type.
longLong integer data type.
shortShort integer data type.
size_tUnsigned integer data type.
stringSequence of characters (not a primitive type).
String()String class in Arduino.
unsigned charUnsigned 8-bit character data type.
unsigned intUnsigned integer data type.
unsigned longUnsigned long integer data type.
voidRepresents the absence of a type.
word16-bit unsigned data type.

Практическое замечание. На платах с 8-битными микроконтроллерами (Uno, Nano) тип int занимает 2 байта и имеет диапазон −32 768…32 767. На 32-битных платах (Due, ESP32) int — уже 4 байта. Учитывайте это при переносе скетчей между платформами.

Область видимости и квалификаторы (Variable Scope & Qualifiers)

Method & ParameterDescription
constQualifier to define constants.
scopeNot a specific keyword; refers to variable scope.
staticQualifier to declare static variables.
volatileQualifier to declare volatile variables.

Утилиты (Utilities)

Method & ParameterDescription
PROGMEMQualifier to store data in program memory.
sizeof()Operator to determine the size of a data type or variable.

---

Структура скетча (Structure)

Скетч (Sketch)

Method & ParameterDescription
void loop()Main function for continuous code execution.
void setup()Initialization function, called once at startup.

Управляющие конструкции (Control Structure)

Method & ParameterDescription
breakExits a loop or switch statement.
continueSkips the rest of a loop iteration.
do...whileExecutes a block of code repeatedly while a specified condition is true.
elsePart of the if-else statement.
forCreates a loop with a specified initialization, condition, and increment.
gotoTransfers control to a labeled statement.
ifConditional statement for decision-making.
returnExits a function and optionally returns a value.
switch...caseMulti-way branch statement.
whileCreates a loop with a specified condition.

Дополнительный синтаксис (Further Syntax)

Method & ParameterDescription
#define (define)Macro definition for code substitution.
#include (include)Includes a file in the source code.
/* */ (block comment)Block comment for multiple lines.
// (single line comment)Single line comment.
; (semicolon)Statement terminator.
{} (curly braces)Block of code, often used with control structures.

Арифметические операторы (Arithmetic Operators)

Method & ParameterDescription
% (remainder)Modulo operator for finding the remainder of a division.
* (multiplication)Multiplication operator.
+ (addition)Addition operator.
- (subtraction)Subtraction operator.
/ (division)Division operator.
= (assignment operator)Assignment operator.

Операторы сравнения (Comparison Operators)

Method & ParameterDescription
!= (not equal to)Checks if two values are not equal.
< (less than)Checks if the left value is less than the right value.
<= (less than or equal to)Checks if the left value is less than or equal to the right value.
== (equal to)Checks if two values are equal.
> (greater than)Checks if the left value is greater than the right value.
>= (greater than or equal to)Checks if the left value is greater than or equal to the right value.

Логические операторы (Boolean Operators)

Method & ParameterDescription
! (logical not)Inverts the logical value, true becomes false and vice versa.
&& (logical and)Logical AND operator, returns true if both operands are true.
`|(logical or)`Logical OR operator, returns true if at least one operand is true.

Операторы доступа к указателям (Pointer Access Operators)

Method & ParameterDescription
& (reference operator)Returns the memory address of a variable.
* (dereference operator)Accesses the value pointed to by a pointer.

Побитовые операторы (Bitwise Operators)

Method & ParameterDescription
& (bitwise and)Performs bitwise AND operation.
<< (bitshift left)Shifts bits to the left.
>> (bitshift right)Shifts bits to the right.
^ (bitwise xor)Performs bitwise XOR (exclusive OR) operation.
| (bitwise or)Performs bitwise OR operation.
~ (bitwise not)Inverts all bits.

Составные операторы (Compound Operators)

Method & ParameterDescription
%= (compound remainder)Performs a modulo operation and assigns the result to the left operand.
&= (compound bitwise and)Performs a bitwise AND operation and assigns the result to the left operand.
*= (compound multiplication)Multiplies the left operand by the right operand and assigns the result to the left operand.
++ (increment)Increments the value of the operand by 1.
+= (compound addition)Adds the right operand to the left operand and assigns the result to the left operand.
-- (decrement)Decrements the value of the operand by 1.
-= (compound subtraction)Subtracts the right operand from the left operand and assigns the result to the left operand.
/= (compound division)Divides the left operand by the right operand and assigns the result to the left operand.
^= (compound bitwise xor)Performs a bitwise XOR operation and assigns the result to the left operand.
|= (compound bitwise or)Performs a bitwise OR operation and assigns the result to the left operand.