Site Guide

Find your way around the Engineering Club.

Know what you need? Search for a component, concept or project.

Around the site

Start

Labs

TestingExperimental

Build

Club

LearnExperimental

Go a little deeper

Entry points to larger collections. Use Search for individual records.

Learning paths & reference

Inside PiCrawlerExperimental

Inside Inventory

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

SyntaxWhat it meansExample
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 */
#includeIncludes declarations from a header or library.#include <Servo.h>
#defineCreates a preprocessor macro.#define LED_PIN 13
#if, #ifdef, #endifConditionally includes or excludes code during compilation.#ifdef DEBUG
#pragma onceCommon 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()

2. Variables, data types, and constants

SyntaxWhat it meansExample
intSigned whole number.int speed = 50;
unsigned intNonnegative whole number.unsigned int count = 10;
longSigned integer with at least 32 bits.long distance = 100000;
unsigned longUnsigned integer commonly used with millis().unsigned long time = 0;
floatFloating-point number.float voltage = 3.3;
doubleFloating-point type; precision varies by board.double result = 1.25;
boolStores true or false.bool enabled = true;
charStores a character or small integer value.char letter = 'A';
StringArduino string object for manipulating text.String name = "Arduino";
char[]Character array often used for C-style strings.char name[] = "Arduino";
byteArduino 8-bit unsigned data type.byte value = 255;
uint8_tUnsigned integer with exactly 8 bits.uint8_t level = 100;
uint16_tUnsigned 16-bit integer.uint16_t reading = 1000;
uint32_tUnsigned 32-bit integer.uint32_t elapsed = 0;
constPrevents modification through that variable.const int ledPin = 13;
constexprDefines a value usable as a compile-time constant.constexpr int maxLEDs = 8;
autoLets C++ infer the variable's type.auto count = 5;
staticCan preserve a local variable between function calls.static int calls = 0;
volatileIndicates a value may change outside ordinary code flow, such as through an interrupt.volatile bool triggered = false;
enumDefines named integer constants.enum Mode { OFF, ON };
structGroups 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.

3. Operators and symbols

SyntaxWhat it meansExample
=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
sizeofReturns the size of a type or object in bytes.sizeof(int)

4. Conditions, loops, and program flow

SyntaxWhat it meansExample
ifRuns code when a condition is true.if (x > 10) { ... }
elseRuns an alternative when the preceding condition is false.else { ... }
else ifChecks another condition.else if (x > 5) { ... }
switchChooses between multiple cases based on a value.switch (mode) { ... }
caseIdentifies a choice inside switch.case 1:
defaultHandles cases that haven't matched.default:
forRepeats code with initialization, condition, and update.for (int i=0; i<5; i++)
whileRepeats while a condition remains true.while (x < 10)
do...whileExecutes a block at least once, then checks a condition.do { x++; } while (x<5);
breakExits a loop or switch.break;
continueSkips to the next loop iteration.continue;
returnExits a function, optionally returning a value.return result;

5. Functions, arrays, and custom code

SyntaxWhat it meansExample
voidIndicates a function does not return a value.void blinkLED()
int function()Declares a function returning an integer.int readSensor()
ParametersDefine information a function receives.void setSpeed(int speed)
ArgumentsValues 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};
structDefines a custom data structure.struct Point { int x, y; };
classDefines 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;
nullptrRepresents a null pointer.int* ptr = nullptr;
namespaceGroups related names.namespace Sensors { ... }
usingCan introduce a type alias or make names available.using Count = uint32_t;
templateEnables generic code that works with different types or values.template<typename T>

6. Arduino digital and analog I/O

Function or constantWhat it meansExample
pinMode()Configures a pin as an input or output.pinMode(13, OUTPUT);
INPUTConfigures a digital input.pinMode(2, INPUT);
INPUT_PULLUPEnables a digital input's internal pull-up resistor.pinMode(2, INPUT_PULLUP);
OUTPUTConfigures 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)
HIGHLogical high state.digitalWrite(13, HIGH)
LOWLogical 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()

7. Timing, Serial, math, and utilities

FunctionWhat it meansExample
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)

8. Libraries and communication

Library or syntaxWhat it allows you to doExample
#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.

Important distinctions worth placing below the tables

These are recurring mistakes that are especially useful for beginners:

Don't confuseDifference
= vs. ==Assignment versus equality comparison.
&& vs. &Logical AND versus bitwise AND.
|| vs. |Logical OR versus bitwise OR.
char vs. StringA character value versus an Arduino string object.
'A' vs. "A"Character literal versus string literal.
int vs. floatInteger 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 libraryIncluding a header does not install the dependency.
Compiling vs. uploadingCompiling checks and produces the program; uploading transfers it to the board.

External references for the page

← Back to Learn