Arduino Sensor and Actuator Projects

1. Push Button LED Control

This example demonstrates how to control an LED using a push button. When the button is pressed, the LED turns on; otherwise, it remains off. The button state is also printed to the serial monitor.


int led = 13;
int pushButton = 2;

void setup() {
  Serial.begin(9600);
  pinMode(pushButton, INPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  int buttonState = digitalRead(pushButton);
  Serial.println(buttonState);
  if (buttonState == HIGH) {
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
  delay(1);
}

2. Traffic Light Sequence Simulation

This code simulates a basic traffic light sequence using three LEDs (red, yellow, green) with specific timing for each state. The yellow LED blinks multiple times before the green light turns on, and again before the red light turns on.


int red = 9;
int yellow = 8;
int green = 7;

void setup() {
  pinMode(red, OUTPUT);
  pinMode(yellow, OUTPUT);
  pinMode(green, OUTPUT);
}

void loop() {
  // Red light
  digitalWrite(red, HIGH);
  delay(15000); // Red light on for 15 seconds
  digitalWrite(red, LOW);

  // Yellow light blinks before green
  for (int i = 0; i < 5; i++) { // Blinks 5 times
    digitalWrite(yellow, HIGH);
    delay(1000);
    digitalWrite(yellow, LOW);
    delay(500);
  }

  // Green light
  digitalWrite(green, HIGH);
  delay(20000); // Green light on for 20 seconds
  digitalWrite(green, LOW);

  // Yellow light blinks before red
  for (int i = 0; i < 3; i++) { // Blinks 3 times
    digitalWrite(yellow, HIGH);
    delay(1000);
    digitalWrite(yellow, LOW);
    delay(500);
  }
}

3. LED Fading with PWM

This sketch demonstrates how to fade an LED in and out using Pulse Width Modulation (PWM). The brightness smoothly increases and decreases, creating a breathing effect.


int ledPin = 9;      // The PWM pin the LED is connected to
int brightness = 0;  // How bright the LED is
int fadeAmount = 5;  // How many points to change brightness each time

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

void loop() {
  analogWrite(ledPin, brightness);

  // Change the brightness for next time through the loop:
  brightness += fadeAmount;

  // Reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
  // Wait for 30 milliseconds to see the dimming effect
  delay(30);
}

4. Alternating LED Pattern (Example 1)

This code creates an alternating pattern with four LEDs. It turns on odd-indexed LEDs while turning off even-indexed LEDs, then reverses the pattern, creating a simple back-and-forth effect.


const int ledPins[] = {6, 7, 8, 9}; // Array of LED pins

void setup() {
  for (int i = 0; i < 4; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  // Turn on odd-indexed LEDs, turn off even-indexed LEDs
  for (int i = 1; i < 4; i += 2) {
    digitalWrite(ledPins[i], HIGH);
  }
  for (int i = 0; i < 4; i += 2) {
    digitalWrite(ledPins[i], LOW);
  }
  delay(500); // Wait for 500 milliseconds

  // Reverse the pattern: turn off odd-indexed, turn on even-indexed
  for (int i = 1; i < 4; i += 2) {
    digitalWrite(ledPins[i], LOW);
  }
  for (int i = 0; i < 4; i += 2) {
    digitalWrite(ledPins[i], HIGH);
  }
  delay(500);
}

5. Alternating LED Pattern (Example 2)

This is another example demonstrating an alternating LED pattern, identical to the previous one. It cycles between two states: odd-indexed LEDs on/even-indexed LEDs off, and vice-versa, with a half-second delay between changes.


const int ledPins[] = {6, 7, 8, 9}; // Array of LED pins

void setup() {
  for (int i = 0; i < 4; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  // Turn on odd-indexed LEDs, turn off even-indexed LEDs
  for (int i = 1; i < 4; i += 2) {
    digitalWrite(ledPins[i], HIGH);
  }
  for (int i = 0; i < 4; i += 2) {
    digitalWrite(ledPins[i], LOW);
  }
  delay(500); // Wait for 500 milliseconds

  // Reverse the pattern: turn off odd-indexed, turn on even-indexed
  for (int i = 1; i < 4; i += 2) {
    digitalWrite(ledPins[i], LOW);
  }
  for (int i = 0; i < 4; i += 2) {
    digitalWrite(ledPins[i], HIGH);
  }
  delay(500);
}

6. LDR-Controlled LED Brightness

This example uses a Light Dependent Resistor (LDR) to automatically adjust the brightness of an LED. As the ambient light changes, the LED’s brightness will respond accordingly. The LDR value is also sent to the serial monitor.


const int ldrPin = A0; // Analog pin connected to the LDR
const int ledPin = 9;  // PWM pin connected to the LED

void setup() {
  Serial.begin(115200); // Initialize serial communication
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int ldrValue = analogRead(ldrPin); // Read the LDR sensor value
  Serial.print("LDR Value: ");
  Serial.println(ldrValue);

  // Map the LDR value (0-1023) to LED brightness (0-255)
  // The original map range (0, 100, 10, 255) is kept as per instructions.
  int ledBrightness = map(ldrValue, 0, 100, 10, 255);
  analogWrite(ledPin, ledBrightness); // Set the LED brightness

  delay(100); // Small delay for stable readings
}

7. Potentiometer LED Dimmer

This sketch allows you to control the brightness of an LED using a potentiometer. Turning the potentiometer knob will smoothly adjust the LED’s intensity from off to full brightness.


const int POT_PIN = A0; // Analog pin connected to the potentiometer
const int LED_PIN = 9;  // PWM pin connected to the LED

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

void loop() {
  int potValue = analogRead(POT_PIN); // Read the potentiometer value (0-1023)
  // Map the potentiometer value to LED brightness (0-255)
  int ledBrightness = map(potValue, 0, 1023, 0, 255);
  analogWrite(LED_PIN, ledBrightness); // Set the LED brightness

  delay(10); // Small delay for smooth operation
}

8. DHT11 Temperature on I2C LCD

This code reads temperature data from a DHT11 sensor and displays it on a 16×2 I2C Liquid Crystal Display (LCD). It also outputs the temperature to the serial monitor. Error handling is included for sensor reading failures.


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

#define DHTPIN 2    // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11 sensor type

DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD I2C address (0x27 is common), 16 columns, 2 rows

void setup() {
  Serial.begin(9600); // Initialize serial communication
  dht.begin();        // Initialize DHT sensor
  lcd.begin();        // Initialize the LCD
  lcd.backlight();    // Turn on the LCD backlight
  lcd.setCursor(0, 0);
  lcd.print("Room Temp: ");
}

void loop() {
  delay(2000); // Wait a few seconds between measurements

  // Read temperature as Celsius (the default)
  float temperature = dht.readTemperature();

  // Check if any reads failed and exit early (to try again).
  if (isnan(temperature)) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Failed to read");
    lcd.setCursor(0, 1);
    lcd.print("temperature");
    return;
  }

  // Display temperature on LCD
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Room Temp: ");
  lcd.print(temperature);
  lcd.print(" C");

  // Output temperature to Serial Monitor
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" C");
}

9. Knight Rider LED Sweep Effect

This code creates a classic “Knight Rider” style LED sweep effect, where a single LED moves back and forth across a row of LEDs. This is achieved by incrementing or decrementing the currentLed index and reversing direction at the ends.


const int ledPin[] = {5, 6, 7, 8, 9}; // Array of LED pins
const int numLeds = 5;                 // Number of LEDs in the array
int direction = 1;                     // Direction of the sweep (1 for forward, -1 for backward)
int currentLed = 0;                    // Index of the currently lit LED

void setup() {
  for (int i = 0; i < numLeds; i++) {
    pinMode(ledPin[i], OUTPUT);
  }
}

void loop() {
  // Turn off all LEDs
  for (int i = 0; i < numLeds; i++) {
    digitalWrite(ledPin[i], LOW);
  }

  // Turn on the current LED
  digitalWrite(ledPin[currentLed], HIGH);

  // Move to the next LED
  currentLed += direction;

  // Reverse direction if at the ends of the array
  if (currentLed == numLeds || currentLed == -1) {
    direction = -direction; // Reverse direction
    currentLed += direction; // Move one step in the new direction
  }

  delay(200); // Delay for sweep speed
}

10. Ultrasonic Distance Measurement

This sketch uses an HC-SR04 ultrasonic sensor to measure the distance to an object. It sends out a sound pulse and calculates the distance based on the time it takes for the echo to return. The distance is then printed to the serial monitor.


const int trigPin = 9;  // Trigger pin of the ultrasonic sensor
const int echoPin = 10; // Echo pin of the ultrasonic sensor

long duration; // Variable for the duration of sound travel
int distance;  // Variable for the distance measurement

void setup() {
  Serial.begin(9600); // Initialize serial communication
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT);  // Sets the echoPin as an Input
}

void loop() {
  // Clears the trigPin by setting it LOW for 2 microseconds
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 microseconds to send a pulse
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  // Speed of sound is 0.0344 cm/µs (or 344 meters/second)
  // Distance = (duration * speed of sound) / 2 (because sound travels to and from the object)
  distance = duration * 0.0344 / 2;

  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(500); // Wait for 500 milliseconds before the next measurement
}

11. Button Control for Built-in LED

This simple sketch demonstrates how to control the Arduino’s built-in LED using an external push button connected to digital pin 2. When the button is pressed, the built-in LED turns on; when released, it turns off.


int buttonState = 0; // Variable to store the button's state

void setup() {
  pinMode(2, INPUT);           // Set digital pin 2 as an input for the button
  pinMode(LED_BUILTIN, OUTPUT); // Set the built-in LED pin as an output
}

void loop() {
  buttonState = digitalRead(2); // Read the state of the button

  // Check if the button is pressed (HIGH)
  if (buttonState == HIGH) {
    digitalWrite(LED_BUILTIN, HIGH); // Turn on the built-in LED
  } else {
    digitalWrite(LED_BUILTIN, LOW);  // Turn off the built-in LED
  }
  delay(10); // Small delay for debouncing
}

12. DHT22 Temperature, Humidity, Heat Index

This code utilizes a DHT22 sensor to measure ambient temperature and humidity. It then calculates the heat index and prints all three values to the serial monitor. This provides a comprehensive environmental reading.


#include <DHT.h>

#define DHTPIN 2    // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 sensor type (AM2302, AM2321)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600); // Initialize serial communication
  dht.begin();        // Initialize DHT sensor
}

void loop() {
  delay(2000); // Wait a few seconds between measurements

  // Read humidity and temperature
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();

  // Check if any reads failed and exit early (to try again).
  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Celsius (isFahrenheit = false)
  float heatIndex = dht.computeHeatIndex(temperature, humidity, false);

  // Print results to Serial Monitor
  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.print("%  ");

  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.print("C  ");

  Serial.print("Heat Index: ");
  Serial.print(heatIndex);
  Serial.println("C");
}