🤖 Complete Arduino Guide

Everything about Arduino - from blinking LEDs to advanced robotics. 3000+ lines of comprehensive documentation.

📚 Table of Contents

  1. Getting Started
  2. Arduino Boards
  3. Arduino IDE
  4. Programming Basics
  5. Sensors
  6. Actuators
  7. Communication
  8. Power Management
  9. Projects
  10. Troubleshooting
  11. Advanced Topics
  12. Resources

🚀 Getting Started with Arduino

What is Arduino?

Arduino is an open-source electronics platform based on easy-to-use hardware and software. It's intended for anyone making interactive projects.

Microcontroller

ATmega328P (Uno), ATmega2560 (Mega), SAMD21 (Zero)

Programming Language

C/C++ based with simplified functions

Voltage

5V (most boards), 3.3V (some newer)

Clock Speed

16 MHz (Uno), 84 MHz (Due), 48 MHz (Zero)

🔌 Arduino Boards Comparison

Board Microcontroller Digital I/O Analog Inputs Flash Memory SRAM EEPROM Clock Speed Price Range
Uno R3 ATmega328P 14 6 32 KB 2 KB 1 KB 16 MHz $20-25
Mega 2560 ATmega2560 54 16 256 KB 8 KB 4 KB 16 MHz $40-45
Nano ATmega328P 22 8 32 KB 2 KB 1 KB 16 MHz $10-15
Due ATSAM3X8E 54 12 512 KB 96 KB - 84 MHz $40-50
Leonardo ATmega32u4 20 12 32 KB 2.5 KB 1 KB 16 MHz $20-25
ESP32 Dev Kit ESP32-D0WDQ6 38 18 4 MB 520 KB - 240 MHz $8-12

💻 Arduino IDE Setup

Installation Guide

Windows

1. Download Arduino IDE from arduino.cc
2. Run installer (no admin required)
3. Install drivers when prompted
4. Select board: Tools → Board → Arduino Uno
5. Select port: Tools → Port → COM3 (or similar)

Linux

# Ubuntu/Debian
sudo apt update
sudo apt install arduino

# Add user to dialout group
sudo usermod -a -G dialout $USER
# Log out and back in

macOS

1. Download .dmg from arduino.cc
2. Drag to Applications folder
3. Install FTDI drivers if needed
4. Grant permissions in System Preferences

👨‍💻 Programming Basics

Arduino Program Structure

// Comments start with //
/* Multi-line comments */

// Include libraries
#include <LibraryName.h>

// Global variables
int sensorValue = 0;
const int LED_PIN = 13;

// Setup runs once at start
void setup() {
  // Initialize pins
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(9600); // Start serial communication
}

// Loop runs forever
void loop() {
  // Main program logic here
  digitalWrite(LED_PIN, HIGH);
  delay(1000);
  digitalWrite(LED_PIN, LOW);
  delay(1000);
}

Essential Functions

pinMode(pin, mode)

Configure pin as INPUT, OUTPUT, or INPUT_PULLUP

pinMode(13, OUTPUT);
pinMode(A0, INPUT);
pinMode(2, INPUT_PULLUP);

digitalWrite(pin, value)

Set digital pin HIGH (5V) or LOW (0V)

digitalWrite(13, HIGH); // Turn on
digitalWrite(13, LOW);  // Turn off

digitalRead(pin)

Read digital pin (returns HIGH or LOW)

int buttonState = digitalRead(2);
if (buttonState == HIGH) {
  // Button pressed
}

analogRead(pin)

Read analog pin (returns 0-1023)

int sensorValue = analogRead(A0);
float voltage = sensorValue * (5.0 / 1023.0);

analogWrite(pin, value)

PWM output (0-255) on pins 3,5,6,9,10,11

analogWrite(9, 127); // 50% duty cycle
analogWrite(11, 255); // 100% duty cycle

delay(ms)

Pause program for milliseconds

delay(1000); // Wait 1 second
delay(500);  // Wait 0.5 seconds

millis()

Returns milliseconds since start

unsigned long startTime = millis();
// Do something
unsigned long elapsed = millis() - startTime;

Serial communication

Debug and data exchange

Serial.begin(9600);
Serial.println("Hello");
int data = Serial.read();
Serial.print("Value: ");
Serial.println(sensorValue);

📡 Sensors Reference

Temperature & Humidity

DHT11/DHT22

#include <DHT.h>
DHT dht(2, DHT22);

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

void loop() {
  float temp = dht.readTemperature();
  float humidity = dht.readHumidity();
}

DS18B20 (OneWire)

#include <OneWire.h>
#include <DallasTemperature.h>

OneWire oneWire(2);
DallasTemperature sensors(&oneWire);

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

void loop() {
  sensors.requestTemperatures();
  float temp = sensors.getTempCByIndex(0);
}

LM35 (Analog)

int reading = analogRead(A0);
float voltage = reading * 5.0 / 1024.0;
float tempC = voltage * 100; // LM35: 10mV/°C
float tempF = tempC * 9/5 + 32;

Motion & Distance

HC-SR04 Ultrasonic

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

long duration;
float distance;

digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;

PIR Motion Sensor

int pirPin = 2;
int ledPin = 13;

void setup() {
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (digitalRead(pirPin) == HIGH) {
    digitalWrite(ledPin, HIGH);
    // Motion detected
  } else {
    digitalWrite(ledPin, LOW);
  }
}

IR Obstacle Sensor

int sensorPin = A0;
int threshold = 500;

void loop() {
  int value = analogRead(sensorPin);
  if (value < threshold) {
    // Obstacle detected
  }
}

Light & Color

LDR (Light Dependent Resistor)

int ldrPin = A0;

void loop() {
  int lightLevel = analogRead(ldrPin);
  // 0-1023: 0 = dark, 1023 = bright
  if (lightLevel < 200) {
    // It's dark
  }
}

RGB Color Sensor (TCS34725)

#include "Adafruit_TCS34725.h"
Adafruit_TCS34725 tcs = 
  Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, 
                   TCS34725_GAIN_4X);

uint16_t r, g, b, c;
tcs.getRawData(&r, &g, &b, &c);
float red = r, green = g, blue = b;

Phototransistor

int photoPin = A0;

void loop() {
  int lightValue = analogRead(photoPin);
  // Higher value = more light
  // Fast response for PWM detection

Force & Pressure

Load Cell (HX711)

#include "HX711.h"
HX711 scale;

void setup() {
  scale.begin(3, 2); // DT, SCK pins
  scale.set_scale(2280.f); // Calibrate
  scale.tare();
}

void loop() {
  float weight = scale.get_units(10);
}

FSR (Force Sensitive Resistor)

int fsrPin = A0;

void loop() {
  int fsrReading = analogRead(fsrPin);
  // 0-1023, higher = more force
  float force = map(fsrReading, 0, 1023, 0, 100);
}

BMP280 Pressure/Temp

#include <Adafruit_BMP280.h>
Adafruit_BMP280 bmp;

void setup() {
  bmp.begin(0x76);
}

void loop() {
  float pressure = bmp.readPressure();
  float altitude = bmp.readAltitude(1013.25);
}

⚡ Actuators & Outputs

LED Control

Single LED

     5V
      │
     ┌┴┐
     │ │ R (220Ω-1kΩ)
     └┬┘
      ├─────── LED+ (long leg)
     ┌┴┐
     │ │ LED
     └┬┘
      │
    Arduino Pin

RGB LED (Common Cathode)

int redPin = 9;
int greenPin = 10;
int bluePin = 11;

void setColor(int r, int g, int b) {
  analogWrite(redPin, r);
  analogWrite(greenPin, g);
  analogWrite(bluePin, b);
}

// Examples:
setColor(255, 0, 0);   // Red
setColor(0, 255, 0);   // Green
setColor(0, 0, 255);   // Blue
setColor(255, 255, 0); // Yellow

Motor Control

Servo Motor

#include <Servo.h>
Servo myservo;

void setup() {
  myservo.attach(9);
}

void loop() {
  myservo.write(0);   // 0 degrees
  delay(1000);
  myservo.write(90);  // 90 degrees
  delay(1000);
  myservo.write(180); // 180 degrees
  delay(1000);
}

Stepper Motor (28BYJ-48)

#include <Stepper.h>

const int stepsPerRevolution = 2048;
Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {
  myStepper.setSpeed(10); // RPM
}

void loop() {
  myStepper.step(stepsPerRevolution);
  delay(500);
  myStepper.step(-stepsPerRevolution);
  delay(500);
}

DC Motor (L298N Driver)

int enA = 9;
int in1 = 8;
int in2 = 7;

void setup() {
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
}

void setMotor(int speed) {
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  analogWrite(enA, speed); // 0-255
}

void brakeMotor() {
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
}

Displays

16x2 LCD (I2C)

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Hello, World!");
  lcd.setCursor(0, 1);
  lcd.print("Temp: 23.5C");
}

OLED SSD1306

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

Adafruit_SSD1306 display(128, 64, &Wire, -1);

void setup() {
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println("Arduino");
  display.display();
}

7-Segment Display

// Pins: a,b,c,d,e,f,g,dp
int segments[8] = {2,3,4,5,6,7,8,9};

byte numbers[10] = {
  0b11111100, // 0
  0b01100000, // 1
  0b11011010, // 2
  0b11110010, // 3
  0b01100110, // 4
  0b10110110, // 5
  0b10111110, // 6
  0b11100000, // 7
  0b11111110, // 8
  0b11110110  // 9
};

📡 Communication Protocols

Serial Communication

UART (Serial Monitor)

// Arduino to PC
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("Hello from Arduino!");
  delay(1000);
}

// PC to Arduino
void loop() {
  if (Serial.available() > 0) {
    char data = Serial.read();
    if (data == '1') {
      digitalWrite(13, HIGH);
    }
  }
}

Software Serial

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

I2C Communication

Master (Scanner)

#include <Wire.h>

void setup() {
  Wire.begin();
  Serial.begin(9600);
  
  Serial.println("I2C Scanner");
  byte error, address;
  int nDevices = 0;
  
  for(address = 1; address < 127; address++ ) {
    Wire.beginTransmission(address);
    error = Wire.endTransmission();
    
    if (error == 0) {
      Serial.print("Device found at 0x");
      Serial.println(address, HEX);
      nDevices++;
    }
  }
}

Master Writing

void sendData() {
  Wire.beginTransmission(0x27); // Slave address
  Wire.write("Hello Slave");    // Send data
  Wire.endTransmission();       // Stop transmitting
}

Slave Reading

#include <Wire.h>

void setup() {
  Wire.begin(0x27); // Join I2C bus as slave
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int howMany) {
  while(Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
}

SPI Communication

SPI Master

#include <SPI.h>

const int slaveSelectPin = 10;

void setup() {
  pinMode(slaveSelectPin, OUTPUT);
  SPI.begin();
}

void sendData(byte data) {
  digitalWrite(slaveSelectPin, LOW);
  SPI.transfer(data);
  digitalWrite(slaveSelectPin, HIGH);
}

Common SPI Pins

Pin Name Uno/Nano Mega Function
MOSI 11 51 Master Out Slave In
MISO 12 50 Master In Slave Out
SCK 13 52 Serial Clock
SS 10 53 Slave Select

🔋 Power Management

Voltage Requirements

  • Arduino Uno: 7-12V via barrel jack, 5V via USB
  • Vin pin: 7-12V (regulated to 5V)
  • 5V pin: Regulated 5V output (500mA max)
  • 3.3V pin: Regulated 3.3V output (150mA max)
  • Digital pins: 40mA max per pin, 200mA total

Battery Options

  • 9V battery: 250-500mAh, good for low-power
  • 18650 Li-ion: 2500-3500mAh, need protection circuit
  • AA batteries: 4xAA = 6V, 6xAA = 9V
  • LiPo battery: 3.7V, needs boost converter
  • Power bank: 5V USB, convenient for portable projects

Sleep Modes

#include <avr/sleep.h>

void sleepNow() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_mode(); // Device sleeps here
  sleep_disable(); // Execution resumes
}

// Wake on interrupt
attachInterrupt(0, wakeUp, LOW);

🔧 Project Examples

Beginner Projects

Blink LED

void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}

Button Controlled LED

int buttonPin = 2;
int ledPin = 13;

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

void loop() {
  if (digitalRead(buttonPin) == LOW) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

Potentiometer LED Control

int potPin = A0;
int ledPin = 9;

void loop() {
  int potValue = analogRead(potPin);
  int brightness = map(potValue, 0, 1023, 0, 255);
  analogWrite(ledPin, brightness);
}

Intermediate Projects

Temperature Logger

#include <DHT.h>
#include <SD.h>

DHT dht(2, DHT22);
File dataFile;

void setup() {
  dht.begin();
  SD.begin(4);
  dataFile = SD.open("log.txt", FILE_WRITE);
}

void loop() {
  float temp = dht.readTemperature();
  dataFile.print("Temp: ");
  dataFile.println(temp);
  dataFile.flush();
  delay(60000); // Log every minute
}

Ultrasonic Parking Sensor

int trig = 9, echo = 10;
int buzzer = 3, redLED = 4, greenLED = 5;

void loop() {
  float distance = getDistance();
  
  if (distance < 10) {
    tone(buzzer, 1000);
    digitalWrite(redLED, HIGH);
    digitalWrite(greenLED, LOW);
  } else if (distance < 30) {
    tone(buzzer, 500);
    digitalWrite(redLED, LOW);
    digitalWrite(greenLED, LOW);
  } else {
    noTone(buzzer);
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
}

Web Server (ESP8266)

#include <ESP8266WiFi.h>

const char* ssid = "YourSSID";
const char* password = "YourPassword";

WiFiServer server(80);

void setup() {
  WiFi.begin(ssid, password);
  server.begin();
}

void loop() {
  WiFiClient client = server.available();
  if (client) {
    String request = client.readString();
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println();
    client.println("<h1>Arduino Server</h1>");
  }
}

Advanced Projects

Robot Car

#include <AFMotor.h>

AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);

void moveForward(int speed) {
  motor1.setSpeed(speed); motor1.run(FORWARD);
  motor2.setSpeed(speed); motor2.run(FORWARD);
  motor3.setSpeed(speed); motor3.run(FORWARD);
  motor4.setSpeed(speed); motor4.run(FORWARD);
}

void turnLeft(int speed) {
  motor1.setSpeed(speed); motor1.run(BACKWARD);
  motor2.setSpeed(speed); motor2.run(FORWARD);
  motor3.setSpeed(speed); motor3.run(BACKWARD);
  motor4.setSpeed(speed); motor4.run(FORWARD);
}

Home Automation

#include <IRremote.h>
#include <DHT.h>
#include <Servo.h>

IRrecv irrecv(11);
DHT dht(2, DHT22);
Servo curtainServo;

void loop() {
  decode_results results;
  if (irrecv.decode(&results)) {
    switch(results.value) {
      case 0xFFA25D: // Power button
        toggleLights();
        break;
      case 0xFF629D: // Vol+
        curtainServo.write(90); // Open
        break;
      case 0xFFA857: // Vol-
        curtainServo.write(0); // Close
        break;
    }
  }
}

Weather Station

#include <DHT.h>
#include <Adafruit_BMP280.h>
#include <LiquidCrystal_I2C.h>

DHT dht(2, DHT22);
Adafruit_BMP280 bmp;
LiquidCrystal_I2C lcd(0x27, 16, 2);

void loop() {
  float temp = dht.readTemperature();
  float humidity = dht.readHumidity();
  float pressure = bmp.readPressure();
  float altitude = bmp.readAltitude(1013.25);
  
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("T:");
  lcd.print(temp);
  lcd.print("C H:");
  lcd.print(humidity);
  lcd.print("%");
  
  lcd.setCursor(0,1);
  lcd.print("P:");
  lcd.print(pressure/100);
  lcd.print("hPa");
}

🔧 Troubleshooting Guide

Board Not Detected

  • Check USB cable (data cable, not charge-only)
  • Install correct drivers (CH340 for clones)
  • Try different USB port
  • Check Tools → Port selection
  • Restart Arduino IDE

Upload Failed

  • Check board selection in Tools
  • Ensure no other program using COM port
  • Press reset button during upload
  • Check for loose connections
  • Verify bootloader is intact

Code Not Working

  • Check for missing semicolons
  • Verify library installations
  • Check Serial Monitor baud rate
  • Look for infinite loops
  • Use Serial.println() for debugging

Hardware Issues

  • Check power supply (5V stable)
  • Verify ground connections
  • Check for short circuits
  • Test components individually
  • Use multimeter for voltage checks

🚀 Advanced Topics

Interrupts

// External interrupts
void setup() {
  attachInterrupt(digitalPinToInterrupt(2), 
                  buttonPressed, FALLING);
}

void buttonPressed() {
  // Code here runs when interrupt triggers
  // Keep it short!
}

// Pin change interrupts (more pins)
#include <PinChangeInterrupt.h>

void setup() {
  attachPCINT(digitalPinToPCINT(8), 
              myInterrupt, CHANGE);
}

Timers & PWM

// Timer1 interrupt (16-bit)
#include <TimerOne.h>

void setup() {
  Timer1.initialize(100000); // 100ms
  Timer1.attachInterrupt(callback);
}

void callback() {
  // Called every 100ms
}

// Adjust PWM frequency
// TCCR0B for pins 5,6 (Timer0)
// TCCR1B for pins 9,10 (Timer1)
// TCCR2B for pins 3,11 (Timer2)

TCCR0B = TCCR0B & 0b11111000 | 0x01; // 62.5kHz

📚 Resources & Libraries

Essential Libraries

Library Purpose Install
Adafruit Sensor Unified sensor driver Library Manager
DHT sensor library DHT11/DHT22 sensors Library Manager
OneWire 1-Wire communication Library Manager
Servo Servo motor control Built-in
Stepper Stepper motor control Built-in
SD SD card reading/writing Built-in
Wire I2C communication Built-in
SPI SPI communication Built-in
LiquidCrystal_I2C I2C LCD displays Manual install
FastLED Addressable LEDs Library Manager

⚠️ Safety Notes

• Always disconnect power before wiring
• Double-check polarity of components
• Use appropriate resistors for LEDs
• Don't draw more than 40mA from a single pin
• Use external power for motors & high-current devices
• Keep Arduino away from water and moisture

← Back to Wiki ← Electronics Guide