Learn / Arduino
Arduino
C++ & Arduino Syntax Reference
Arduino programs are written in C++. Some things, like if, int, and ==, belong to C++ itself. Others, like digitalWrite() and analogRead(), are functions supplied by Arduino.
Code walkthroughs
Cyclone code walkthrough — Follow a six-LED game through setup, loops, timing and button input.
1. Basic syntax and program structure
| Syntax | What it means | Example |
|---|---|---|
setup() | Runs once when the Arduino starts or resets. | void setup() { } |
loop() | Runs repeatedly after setup(). | void loop() { } |
{ } | Groups statements into a block. | if (ready) { ... } |
; | Ends a statement. | int x = 5; |
( ) | Groups expressions or holds function arguments. | delay(1000) |
[ ] | Declares an array size or accesses an element. | values[0] |
// | Single-line comment, ignored by the compiler. | // Turn on LED |
/* ... */ | Multiline comment. | /* Explanation */ |
#include | Includes declarations from a header or library. | #include <Servo.h> |
#define | Creates a preprocessor macro. | #define LED_PIN 13 |
#if, #ifdef, #endif | Conditionally includes or excludes code during compilation. | #ifdef DEBUG |
#pragma once | Common header directive preventing repeated inclusion. | #pragma once |
. | Accesses a member of an object. | Serial.begin(9600) |
:: | Accesses a name within a namespace, class, or enum. | Mode::BLINK |
-> | Accesses a member through a pointer. | sensor->read() |
Documentation: Arduino language referenceC++ language reference
2. Variables, data types, and constants
| Syntax | What it means | Example |
|---|---|---|
int | Signed whole number. | int speed = 50; |
unsigned int | Nonnegative whole number. | unsigned int count = 10; |
long | Signed integer with at least 32 bits. | long distance = 100000; |
unsigned long | Unsigned integer commonly used with millis(). | unsigned long time = 0; |
float | Floating-point number. | float voltage = 3.3; |
double | Floating-point type; precision varies by board. | double result = 1.25; |
bool | Stores true or false. | bool enabled = true; |
char | Stores a character or small integer value. | char letter = 'A'; |
String | Arduino string object for manipulating text. | String name = "Arduino"; |
char[] | Character array often used for C-style strings. | char name[] = "Arduino"; |
byte | Arduino 8-bit unsigned data type. | byte value = 255; |
uint8_t | Unsigned integer with exactly 8 bits. | uint8_t level = 100; |
uint16_t | Unsigned 16-bit integer. | uint16_t reading = 1000; |
uint32_t | Unsigned 32-bit integer. | uint32_t elapsed = 0; |
const | Prevents modification through that variable. | const int ledPin = 13; |
constexpr | Defines a value usable as a compile-time constant. | constexpr int maxLEDs = 8; |
auto | Lets C++ infer the variable's type. | auto count = 5; |
static | Can preserve a local variable between function calls. | static int calls = 0; |
volatile | Indicates a value may change outside ordinary code flow, such as through an interrupt. | volatile bool triggered = false; |
enum | Defines named integer constants. | enum Mode { OFF, ON }; |
struct | Groups related variables into one custom type. | struct Sensor { int pin; }; |
On an Uno or Mega, int is typically 16-bit, while on many 32-bit boards it is 32-bit. Fixed-width types like uint16_t are useful when exact sizes matter.
Documentation: C++ fundamental typesArduino reference
3. Operators and symbols
| Syntax | What it means | Example |
|---|---|---|
= | Assigns a value. | x = 10; |
== | Tests whether two values are equal. | x == 10 |
!= | Tests whether values are different. | x != 10 |
> | Greater than. | x > 5 |
< | Less than. | x < 5 |
>= | Greater than or equal to. | x >= 5 |
<= | Less than or equal to. | x <= 5 |
+ | Addition. | x + 3 |
- | Subtraction. | x - 3 |
* | Multiplication. | x * 3 |
/ | Division. | x / 3 |
% | Remainder after integer division. | 10 % 3 gives 1 |
++ | Increases by one. | count++ |
-- | Decreases by one. | count-- |
+= | Adds and assigns. | x += 5 |
-= | Subtracts and assigns. | x -= 5 |
*= | Multiplies and assigns. | x *= 2 |
/= | Divides and assigns. | x /= 2 |
&& | Logical AND; both conditions must be true. | ready && enabled |
|| | Logical OR; at least one condition must be true. | ready || override |
! | Logical NOT; reverses a Boolean condition. | !ready |
& | Bitwise AND; also used in reference declarations and address operations depending on context. | flags & 0x01 |
| | Bitwise OR. | flags | 0x02 |
^ | Bitwise XOR. | a ^ b |
~ | Bitwise NOT. | ~flags |
<< | Shifts bits left. | 1 << 3 |
>> | Shifts bits right. | value >> 2 |
? : | Chooses between two expressions. | ready ? 100 : 0 |
sizeof | Returns the size of a type or object in bytes. | sizeof(int) |
Documentation: C++ operatorsOperator precedence
4. Conditions, loops, and program flow
| Syntax | What it means | Example |
|---|---|---|
if | Runs code when a condition is true. | if (x > 10) { ... } |
else | Runs an alternative when the preceding condition is false. | else { ... } |
else if | Checks another condition. | else if (x > 5) { ... } |
switch | Chooses between multiple cases based on a value. | switch (mode) { ... } |
case | Identifies a choice inside switch. | case 1: |
default | Handles cases that haven't matched. | default: |
for | Repeats code with initialization, condition, and update. | for (int i=0; i<5; i++) |
while | Repeats while a condition remains true. | while (x < 10) |
do...while | Executes a block at least once, then checks a condition. | do { x++; } while (x<5); |
break | Exits a loop or switch. | break; |
continue | Skips to the next loop iteration. | continue; |
return | Exits a function, optionally returning a value. | return result; |
Documentation: C++ statements and control flow
5. Functions, arrays, and custom code
| Syntax | What it means | Example |
|---|---|---|
void | Indicates a function does not return a value. | void blinkLED() |
int function() | Declares a function returning an integer. | int readSensor() |
Parameters | Define information a function receives. | void setSpeed(int speed) |
Arguments | Values supplied when calling a function. | setSpeed(50) |
return value; | Returns information to the calling code. | return temperature; |
int values[5] | Creates an array of five integers. | int values[5]; |
values[0] | Accesses the first array element. | values[0] = 10; |
int values[] = {...} | Initializes an array with known elements. | int values[] = {2,4,6}; |
struct | Defines a custom data structure. | struct Point { int x, y; }; |
class | Defines a type with data and methods. | class Motor { ... }; |
public: | Makes class members accessible to outside code. | public: void start(); |
private: | Restricts class members to the class and its friends. | private: int speed; |
& | Declares a reference in certain contexts. | void change(int& x) |
* | Declares a pointer in certain contexts. | int* ptr = &x; |
nullptr | Represents a null pointer. | int* ptr = nullptr; |
namespace | Groups related names. | namespace Sensors { ... } |
using | Can introduce a type alias or make names available. | using Count = uint32_t; |
template | Enables generic code that works with different types or values. | template<typename T> |
Documentation: C++ functionsArraysClasses
6. Arduino digital and analog I/O
| Function or constant | What it means | Example |
|---|---|---|
pinMode() | Configures a pin as an input or output. | pinMode(13, OUTPUT); |
INPUT | Configures a digital input. | pinMode(2, INPUT); |
INPUT_PULLUP | Enables a digital input's internal pull-up resistor. | pinMode(2, INPUT_PULLUP); |
OUTPUT | Configures a digital output. | pinMode(13, OUTPUT); |
digitalWrite() | Sets a digital output HIGH or LOW. | digitalWrite(13, HIGH); |
digitalRead() | Reads a digital pin's HIGH/LOW state. | digitalRead(2) |
HIGH | Logical high state. | digitalWrite(13, HIGH) |
LOW | Logical low state. | digitalWrite(13, LOW) |
analogRead() | Reads an analog voltage as a digital number. | analogRead(A0) |
analogWrite() | Sets PWM duty cycle on supported pins; some boards support true analog output. | analogWrite(9, 128) |
analogReference() | Configures the analog conversion reference on supported boards. | analogReference(DEFAULT) |
analogReadResolution() | Sets ADC resolution on supported boards. | analogReadResolution(12) |
tone() | Generates a tone on a pin. | tone(8, 440) |
noTone() | Stops tone generation. | noTone(8) |
pulseIn() | Measures a pulse duration. | pulseIn(7, HIGH) |
shiftOut() | Shifts data through a digital interface. | shiftOut(data, clock, MSBFIRST, value) |
attachInterrupt() | Attaches an interrupt handler to a supported interrupt source. | attachInterrupt(digitalPinToInterrupt(2), handler, RISING) |
noInterrupts() | Temporarily disables interrupts. | noInterrupts() |
interrupts() | Re-enables interrupts. | interrupts() |
Documentation: Arduino I/O referencedigitalWrite()
7. Timing, Serial, math, and utilities
| Function | What it means | Example |
|---|---|---|
delay() | Pauses the program for milliseconds. | delay(1000) |
delayMicroseconds() | Pauses for microseconds. | delayMicroseconds(50) |
millis() | Returns milliseconds since program startup. | unsigned long now = millis(); |
micros() | Returns microseconds since startup. | micros() |
Serial.begin() | Initializes serial communication. | Serial.begin(9600) |
Serial.print() | Sends readable text without adding a newline. | Serial.print(value) |
Serial.println() | Sends readable text followed by a newline. | Serial.println(value) |
Serial.write() | Transmits raw byte data. | Serial.write(65) |
Serial.available() | Reports bytes waiting to be read. | Serial.available() |
Serial.read() | Reads the next available byte. | Serial.read() |
Serial.parseInt() | Parses an integer from incoming serial data. | Serial.parseInt() |
map() | Linearly scales an integer from one range to another. | map(x, 0, 1023, 0, 255) |
constrain() | Restricts a number to a specified range. | constrain(x, 0, 100) |
min() / max() | Returns the smaller or larger value. | max(a, b) |
abs() | Returns absolute value. | abs(-10) |
pow() | Raises a number to a power. | pow(2, 3) |
sqrt() | Calculates square root. | sqrt(25) |
sin() / cos() / tan() | Trigonometric functions, using radians. | sin(angle) |
random() | Generates a pseudorandom integer. | random(1, 7) |
randomSeed() | Initializes the pseudorandom number generator. | randomSeed(seed) |
Documentation: Arduino function referenceSerial.begin()Serial.write()
8. Libraries and communication
| Library or syntax | What it allows you to do | Example |
|---|---|---|
#include <Wire.h> | Use I²C communication. | Wire.begin(); |
Wire.beginTransmission() | Begin addressing an I²C device. | Wire.beginTransmission(0x27); |
Wire.endTransmission() | Complete an I²C transmission and obtain a status. | Wire.endTransmission(); |
Wire.requestFrom() | Request bytes from an I²C device. | Wire.requestFrom(0x27, 2); |
#include <SPI.h> | Use SPI communication. | SPI.begin(); |
SPI.transfer() | Exchange a byte through SPI. | SPI.transfer(0x55); |
#include <Servo.h> | Control compatible servo outputs. | servo.attach(9); |
servo.write() | Command an angle-like servo position value in the standard Servo API. | servo.write(90); |
#include <EEPROM.h> | Access nonvolatile EEPROM where supported. | EEPROM.read(0); |
#include <LiquidCrystal.h> | Control compatible character LCDs using a parallel interface. | lcd.print("Hello"); |
#include <SD.h> | Access files on compatible SD-card hardware. | SD.begin(10); |
Library availability and specific APIs depend on the board and installed libraries. Arduino’s Wire, SPI, and Servo libraries are not C++ language keywords.
Documentation: Arduino programming and librariesArduino Learn
Important distinctions worth placing below the tables
These are recurring mistakes that are especially useful for beginners:
| Don't confuse | Difference |
|---|---|
= vs. == | Assignment versus equality comparison. |
&& vs. & | Logical AND versus bitwise AND. |
|| vs. | | Logical OR versus bitwise OR. |
char vs. String | A character value versus an Arduino string object. |
'A' vs. "A" | Character literal versus string literal. |
int vs. float | Integer arithmetic versus floating-point arithmetic. |
digitalWrite() vs. analogWrite() | Digital HIGH/LOW versus PWM or supported analog output. |
analogRead() vs. digitalRead() | Numerical analog measurement versus HIGH/LOW input. |
delay() vs. millis() | Blocking a program versus reading elapsed time for scheduling. |
Serial.print() vs. Serial.write() | Human-readable representation versus raw byte transmission. |
setup() vs. loop() | One-time initialization versus repeated execution. |
#include vs. installing a library | Including a header does not install the dependency. |
Compiling vs. uploading | Compiling checks and produces the program; uploading transfers it to the board. |
External references for the page
- Arduino Language Reference — Built-in functions, values, and structure.
- Arduino Built-in Examples — Actual sketches demonstrating common operations.
- Arduino Programming and Libraries — Library and API documentation.
- C++ Language Reference — Syntax, variables, functions, operators, types, and advanced features.
- C++ Operator Precedence — Useful when expressions get complicated.