Basic Structure Commands
void setup() {
// Runs once at startup
}
void loop() {
// Runs continuously
}
Digital I/O Commands
Command | Description | Example |
---|
pinMode(pin, mode) | Configure pin as INPUT, OUTPUT, or INPUT_PULLUP | pinMode(13, OUTPUT); |
digitalWrite(pin, value) | Write HIGH or LOW to digital pin | digitalWrite(13, HIGH); |
digitalRead(pin) | Read digital pin (returns HIGH or LOW) | int buttonState = digitalRead(2); |
HIGH / LOW | Digital pin states (5V or 0V) | digitalWrite(13, HIGH); |
Analog I/O Commands
Command | Description | Example |
---|
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 voltage | analogReference(EXTERNAL); |
Time Commands
Command | Description | Example |
---|
delay(ms) | Pause program for milliseconds | delay(1000); |
delayMicroseconds(us) | Pause program for microseconds | delayMicroseconds(10); |
millis() | Milliseconds since program start | unsigned long time = millis(); |
micros() | Microseconds since program start | unsigned long time = micros(); |
Math Functions
Command | Description | Example |
---|
min(x, y) | Return smaller of two values | int lower = min(value1, value2); |
max(x, y) | Return larger of two values | int higher = max(value1, value2); |
abs(x) | Absolute value | int distance = abs(position - target); |
constrain(x, min, max) | Constrains value within range | int safe = constrain(value, 0, 255); |
map(value, fromLow, fromHigh, toLow, toHigh) | Re-map a number from one range to another | int brightness = map(sensorValue, 0, 1023, 0, 255); |
sq(x) | Square | long area = sq(side); |
sqrt(x) | Square root | float hypotenuse = sqrt(sq(a) + sq(b)); |
sin(rad) , cos(rad) , tan(rad) | Trigonometric functions (radians) | float y = sin(radians); |
radians(deg) | Convert degrees to radians | float rad = radians(180); |
degrees(rad) | Convert radians to degrees | float deg = degrees(PI); |
random(max) or random(min, max) | Generate random number | int dice = random(1, 7); |
Serial Communication Commands
Command | Description | Example |
---|
Serial.begin(baudRate) | Initialize serial communication | Serial.begin(9600); |
Serial.print(data) | Send data to serial port | Serial.print("Value: "); |
Serial.println(data) | Send data followed by newline | Serial.println(sensorValue); |
Serial.available() | Get number of bytes available to read | if (Serial.available() > 0) {...} |
Serial.read() | Read incoming serial data | char c = Serial.read(); |
Serial.readString() | Read characters into a string | String msg = Serial.readString(); |
Serial.write(val) | Write binary data to serial port | Serial.write(byteArray, length); |
Serial.flush() | Wait for transmission to complete | Serial.flush(); |
Data Types
Type | Size | Range | Example |
---|
boolean | 1 byte | true/false | boolean isOn = true; |
byte | 1 byte | 0 to 255 | byte counter = 255; |
char | 1 byte | -128 to 127 | char letter = 'A'; |
int | 2 bytes | -32,768 to 32,767 | int position = -7652; |
unsigned int | 2 bytes | 0 to 65,535 | unsigned int distance = 42500; |
long | 4 bytes | -2,147,483,648 to 2,147,483,647 | long population = 1250000; |
unsigned long | 4 bytes | 0 to 4,294,967,295 | unsigned long time = 3600000; |
float | 4 bytes | -3.4028235E+38 to 3.4028235E+38 | float pi = 3.14159; |
double | 4 bytes | Same as float (on Arduino) | double precise = 3.141592653589; |
String | variable | Limited by memory | String message = "Hello"; |
array | variable | Limited by memory | int readings[6] = {5, 10, 15, 20, 25, 30}; |
Pin Accessing Commands
Command | Description | Example |
---|
Digital pins | 0-13 on Uno | digitalWrite(13, HIGH); |
Analog inputs | A0-A5 on Uno | analogRead(A0); |
LED_BUILTIN | Built-in LED pin | digitalWrite(LED_BUILTIN, HIGH); |
Bit Manipulation Commands
Command | Description | Example |
---|
bitRead(value, bit) | Read a bit | if (bitRead(value, 3)) {...} |
bitWrite(value, bit, state) | Write a bit | bitWrite(value, 3, HIGH); |
bitSet(value, bit) | Set bit to 1 | bitSet(value, 3); |
bitClear(value, bit) | Set bit to 0 | bitClear(value, 3); |
bit(n) | Returns value with bit n set | value = bit(3); // Returns 8 (binary 1000) |
lowByte(value) | Returns low byte | byte lowValue = lowByte(1024); |
highByte(value) | Returns high byte | byte highValue = highByte(1024); |
Advanced I/O Commands
Command | Description | Example |
---|
tone(pin, frequency) | Generate square wave | tone(8, 440); // 440 Hz on pin 8 |
tone(pin, frequency, duration) | Generate tone for duration | tone(8, 440, 1000); // 1 second tone |
noTone(pin) | Stop tone generation | noTone(8); |
pulseIn(pin, value) | Measure pulse duration | unsigned long duration = pulseIn(7, HIGH); |
pulseInLong(pin, value) | Measure long pulse | unsigned long duration = pulseInLong(7, HIGH); |
shiftIn(dataPin, clockPin, bitOrder) | Shift in data | byte data = shiftIn(dataPin, clockPin, MSBFIRST); |
shiftOut(dataPin, clockPin, bitOrder, value) | Shift out data | shiftOut(dataPin, clockPin, MSBFIRST, value); |
Interrupt Commands
Command | Description | Example |
---|
attachInterrupt(digitalPinToInterrupt(pin), function, mode) | Attach interrupt | attachInterrupt(digitalPinToInterrupt(2), buttonPressed, FALLING); |
detachInterrupt(digitalPinToInterrupt(pin)) | Detach interrupt | detachInterrupt(digitalPinToInterrupt(2)); |
interrupts() | Enable interrupts | interrupts(); |
noInterrupts() | Disable interrupts | noInterrupts(); |
Interrupt modes | LOW , CHANGE , RISING , FALLING | attachInterrupt(digitalPinToInterrupt(2), buttonPressed, RISING); |
Common Constants
Constant | Value | Usage |
---|
HIGH / LOW | 1 / 0 | Digital pin states |
INPUT / OUTPUT / INPUT_PULLUP | 0 / 1 / 2 | Pin modes |
LED_BUILTIN | Board-specific | Built-in LED pin |
true / false | 1 / 0 | Boolean values |
MSBFIRST / LSBFIRST | 1 / 0 | Bit order |
PI | 3.14159… | Mathematical constant |
HALF_PI , TWO_PI , EULER | Constants | Mathematical 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