Arduino Commands Cheat Sheet

Basic Structure Commands

void setup() {
  // Runs once at startup
}

void loop() {
  // Runs continuously
}

Digital I/O Commands

CommandDescriptionExample
pinMode(pin, mode)Configure pin as INPUT, OUTPUT, or INPUT_PULLUPpinMode(13, OUTPUT);
digitalWrite(pin, value)Write HIGH or LOW to digital pindigitalWrite(13, HIGH);
digitalRead(pin)Read digital pin (returns HIGH or LOW)int buttonState = digitalRead(2);
HIGH / LOWDigital pin states (5V or 0V)digitalWrite(13, HIGH);

Analog I/O Commands

CommandDescriptionExample
analogRead(pin)Read analog input (returns 0-1023)int sensorValue = analogRead(A0);
analogWrite(pin, value)Write PWM to pin (0-255)analogWrite(9, 128);
analogReference(type)Set analog reference voltageanalogReference(EXTERNAL);

Time Commands

CommandDescriptionExample
delay(ms)Pause program for millisecondsdelay(1000);
delayMicroseconds(us)Pause program for microsecondsdelayMicroseconds(10);
millis()Milliseconds since program startunsigned long time = millis();
micros()Microseconds since program startunsigned long time = micros();

Math Functions

CommandDescriptionExample
min(x, y)Return smaller of two valuesint lower = min(value1, value2);
max(x, y)Return larger of two valuesint higher = max(value1, value2);
abs(x)Absolute valueint distance = abs(position - target);
constrain(x, min, max)Constrains value within rangeint safe = constrain(value, 0, 255);
map(value, fromLow, fromHigh, toLow, toHigh)Re-map a number from one range to anotherint brightness = map(sensorValue, 0, 1023, 0, 255);
sq(x)Squarelong area = sq(side);
sqrt(x)Square rootfloat hypotenuse = sqrt(sq(a) + sq(b));
sin(rad), cos(rad), tan(rad)Trigonometric functions (radians)float y = sin(radians);
radians(deg)Convert degrees to radiansfloat rad = radians(180);
degrees(rad)Convert radians to degreesfloat deg = degrees(PI);
random(max) or random(min, max)Generate random numberint dice = random(1, 7);

Serial Communication Commands

CommandDescriptionExample
Serial.begin(baudRate)Initialize serial communicationSerial.begin(9600);
Serial.print(data)Send data to serial portSerial.print("Value: ");
Serial.println(data)Send data followed by newlineSerial.println(sensorValue);
Serial.available()Get number of bytes available to readif (Serial.available() > 0) {...}
Serial.read()Read incoming serial datachar c = Serial.read();
Serial.readString()Read characters into a stringString msg = Serial.readString();
Serial.write(val)Write binary data to serial portSerial.write(byteArray, length);
Serial.flush()Wait for transmission to completeSerial.flush();

Data Types

TypeSizeRangeExample
boolean1 bytetrue/falseboolean isOn = true;
byte1 byte0 to 255byte counter = 255;
char1 byte-128 to 127char letter = 'A';
int2 bytes-32,768 to 32,767int position = -7652;
unsigned int2 bytes0 to 65,535unsigned int distance = 42500;
long4 bytes-2,147,483,648 to 2,147,483,647long population = 1250000;
unsigned long4 bytes0 to 4,294,967,295unsigned long time = 3600000;
float4 bytes-3.4028235E+38 to 3.4028235E+38float pi = 3.14159;
double4 bytesSame as float (on Arduino)double precise = 3.141592653589;
StringvariableLimited by memoryString message = "Hello";
arrayvariableLimited by memoryint readings[6] = {5, 10, 15, 20, 25, 30};

Pin Accessing Commands

CommandDescriptionExample
Digital pins0-13 on UnodigitalWrite(13, HIGH);
Analog inputsA0-A5 on UnoanalogRead(A0);
LED_BUILTINBuilt-in LED pindigitalWrite(LED_BUILTIN, HIGH);

Bit Manipulation Commands

CommandDescriptionExample
bitRead(value, bit)Read a bitif (bitRead(value, 3)) {...}
bitWrite(value, bit, state)Write a bitbitWrite(value, 3, HIGH);
bitSet(value, bit)Set bit to 1bitSet(value, 3);
bitClear(value, bit)Set bit to 0bitClear(value, 3);
bit(n)Returns value with bit n setvalue = bit(3); // Returns 8 (binary 1000)
lowByte(value)Returns low bytebyte lowValue = lowByte(1024);
highByte(value)Returns high bytebyte highValue = highByte(1024);

Advanced I/O Commands

CommandDescriptionExample
tone(pin, frequency)Generate square wavetone(8, 440); // 440 Hz on pin 8
tone(pin, frequency, duration)Generate tone for durationtone(8, 440, 1000); // 1 second tone
noTone(pin)Stop tone generationnoTone(8);
pulseIn(pin, value)Measure pulse durationunsigned long duration = pulseIn(7, HIGH);
pulseInLong(pin, value)Measure long pulseunsigned long duration = pulseInLong(7, HIGH);
shiftIn(dataPin, clockPin, bitOrder)Shift in databyte data = shiftIn(dataPin, clockPin, MSBFIRST);
shiftOut(dataPin, clockPin, bitOrder, value)Shift out datashiftOut(dataPin, clockPin, MSBFIRST, value);

Interrupt Commands

CommandDescriptionExample
attachInterrupt(digitalPinToInterrupt(pin), function, mode)Attach interruptattachInterrupt(digitalPinToInterrupt(2), buttonPressed, FALLING);
detachInterrupt(digitalPinToInterrupt(pin))Detach interruptdetachInterrupt(digitalPinToInterrupt(2));
interrupts()Enable interruptsinterrupts();
noInterrupts()Disable interruptsnoInterrupts();
Interrupt modesLOW, CHANGE, RISING, FALLINGattachInterrupt(digitalPinToInterrupt(2), buttonPressed, RISING);

Common Constants

ConstantValueUsage
HIGH / LOW1 / 0Digital pin states
INPUT / OUTPUT / INPUT_PULLUP0 / 1 / 2Pin modes
LED_BUILTINBoard-specificBuilt-in LED pin
true / false1 / 0Boolean values
MSBFIRST / LSBFIRST1 / 0Bit order
PI3.14159…Mathematical constant
HALF_PI, TWO_PI, EULERConstantsMathematical constants

Common Libraries Commands

Servo Library

#include <Servo.h>
Servo myServo;                   // Create servo object
myServo.attach(9);               // Attach to pin
myServo.write(90);               // Move to position (0-180)
myServo.writeMicroseconds(1500); // Raw pulse width (1000-2000)
int pos = myServo.read();        // Read position
myServo.detach();                // Detach from pin

Wire Library (I2C)

#include <Wire.h>
Wire.begin();                    // Initialize as master
Wire.begin(address);             // Initialize as slave
Wire.requestFrom(address, size); // Request data
Wire.available();                // Available bytes
Wire.read();                     // Read a byte
Wire.beginTransmission(address); // Begin transmission
Wire.write(byte);                // Write a byte
Wire.endTransmission();          // End transmission
Wire.onReceive(handler);         // Register receive handler
Wire.onRequest(handler);         // Register request handler

SPI Library

#include <SPI.h>
SPI.begin();                           // Initialize SPI
SPI.beginTransaction(SPISettings(speed, order, mode));  // Begin transaction
uint8_t result = SPI.transfer(value);  // Send/receive a byte
SPI.transfer(buffer, size);            // Transfer buffer
SPI.endTransaction();                  // End transaction
SPI.end();                             // End SPI

EEPROM Library

#include <EEPROM.h>
byte value = EEPROM.read(address);     // Read byte
EEPROM.write(address, value);          // Write byte
EEPROM.update(address, value);         // Write only if different
EEPROM.get(address, variable);         // Read object
EEPROM.put(address, variable);         // Write object
EEPROM.length();                       // EEPROM size

LiquidCrystal Library (LCD)

#include <LiquidCrystal.h>
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);  // Create LCD object
lcd.begin(16, 2);                      // Initialize 16x2 LCD
lcd.clear();                           // Clear display
lcd.home();                            // Move cursor home
lcd.setCursor(column, row);            // Set cursor position
lcd.print("text");                     // Print text
lcd.cursor();                          // Show cursor
lcd.noCursor();                        // Hide cursor
lcd.display();                         // Turn on display
lcd.noDisplay();                       // Turn off display

SD Library

#include <SD.h>
SD.begin(chipSelectPin);               // Initialize SD card
File file = SD.open("file.txt", FILE_READ);  // Open file
file.available();                      // Check for available data
file.read();                           // Read a byte
file.close();                          // Close file
SD.exists("file.txt");                 // Check if file exists
SD.mkdir("dir");                       // Create directory
SD.remove("file.txt");                 // Delete file
SD.rmdir("dir");                       // Remove directory

Non-Blocking Timing Template

unsigned long previousMillis = 0;
const long interval = 1000;      // Interval in milliseconds

void loop() {
  unsigned long currentMillis = millis();
  
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    
    // Code to execute at specified interval
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));  // Toggle LED
  }
  
  // Other code runs without blocking
}

Multiple Non-Blocking Tasks Template

unsigned long task1Previous = 0;
unsigned long task2Previous = 0;
const long task1Interval = 1000;  // Task 1 interval (1 second)
const long task2Interval = 5000;  // Task 2 interval (5 seconds)

void loop() {
  unsigned long currentMillis = millis();
  
  // Task 1
  if (currentMillis - task1Previous >= task1Interval) {
    task1Previous = currentMillis;
    // Task 1 code
  }
  
  // Task 2
  if (currentMillis - task2Previous >= task2Interval) {
    task2Previous = currentMillis;
    // Task 2 code
  }
  
  // Other non-timing-dependent code
}

Button Debounce Template

const int buttonPin = 2;
int buttonState = HIGH;          // Current button state
int lastButtonState = HIGH;      // Previous button state
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;  // Debounce time in ms

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  int reading = digitalRead(buttonPin);
  
  // If button state changed, reset debounce timer
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
  
  // If the debounce delay has passed, update the button state
  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      
      // If the button is pressed (LOW when using INPUT_PULLUP)
      if (buttonState == LOW) {
        // Button press action here
      }
    }
  }
  
  lastButtonState = reading;
}

Common Sensor Reading Templates

Analog Sensor Reading with Smoothing

const int sensorPin = A0;
const int numReadings = 10;
int readings[numReadings];
int readIndex = 0;
int total = 0;

void setup() {
  // Initialize all readings to 0
  for (int i = 0; i < numReadings; i++) {
    readings[i] = 0;
  }
}

int smoothAnalogRead() {
  // Subtract the last reading
  total = total - readings[readIndex];
  // Read the sensor
  readings[readIndex] = analogRead(sensorPin);
  // Add the reading to the total
  total = total + readings[readIndex];
  // Advance to the next position
  readIndex = (readIndex + 1) % numReadings;
  // Calculate the average
  return total / numReadings;
}

Ultrasonic Sensor (HC-SR04)

const int trigPin = 9;
const int echoPin = 10;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

float readDistanceCm() {
  // Clear the trigger pin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  
  // Send 10μs pulse to trigger
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Read the echo pin, convert time to distance
  long duration = pulseIn(echoPin, HIGH);
  float distance = duration * 0.034 / 2;  // Speed of sound wave / 2 (go and back)
  
  return distance;
}

DHT11/DHT22 Temperature and Humidity Sensor

#include <DHT.h>

#define DHTPIN 2        // Pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT 22 (AM2302)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  dht.begin();
}

void readDHT() {
  delay(2000);  // DHT sensors need ~2s between readings
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();  // Celsius
  float temperatureF = dht.readTemperature(true);  // Fahrenheit
  
  // Check if any reads failed
  if (isnan(humidity) || isnan(temperature) || isnan(temperatureF)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  
  // Heat index calculation
  float heatIndex = dht.computeHeatIndex(temperature, humidity, false);  // Celsius
}

Common Output Device Templates

LED Fading

const int ledPin = 9;  // Must be PWM pin
int brightness = 0;
int fadeAmount = 5;

void loop() {
  analogWrite(ledPin, brightness);
  brightness = brightness + fadeAmount;
  
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
  delay(30);
}

RGB LED Control

const int redPin = 9;    // Must be PWM pins
const int greenPin = 10;
const int bluePin = 11;

void setup() {
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void setColor(int red, int green, int blue) {
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

// Example usage:
// setColor(255, 0, 0);  // Red
// setColor(0, 255, 0);  // Green
// setColor(0, 0, 255);  // Blue
// setColor(255, 255, 0);  // Yellow
// setColor(80, 0, 80);  // Purple

OLED Display (SSD1306)

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1  // Reset pin (-1 if sharing Arduino reset pin)

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // Address 0x3C for 128x64
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println("Hello, world!");
  display.display();
}

Resources for Arduino Commands

Official Arduino References

Board-Specific Command References

  • Arduino Uno/Nano/Mini – ATmega328P-based boards
  • Arduino Mega – ATmega2560-based boards
  • Arduino Leonardo/Micro – ATmega32U4-based boards
  • Arduino Due – SAM3X8E ARM Cortex-M3 board
  • ESP8266 Arduino Core – ESP8266-based boards
  • ESP32 Arduino Core – ESP32-based boards

Library Documentation

Scroll to Top