Skip to content

Sensors Coding Practice (Arduino)

This file contains simple sensor examples I learn with clear line-by-line explanations. It needs more read, then explain each marked line in once own words.


1. PIR Sensor (Motion)

int pirPin = 2;            // pin connected to PIR sensor
int ledPin = 13;          // pin connected to LED
int pirState = 0;         // variable to store sensor value (HIGH or LOW)

void setup() {
  pinMode(pirPin, INPUT);     // PIR sends signal to Arduino
  pinMode(ledPin, OUTPUT);    // Arduino controls LED
  Serial.begin(9600);         // start communication with computer
}

void loop() {
  pirState = digitalRead(pirPin);   // read sensor: HIGH = motion, LOW = no motion

  if (pirState == HIGH) {           // check if motion exists
    digitalWrite(ledPin, HIGH);     // turn LED ON
    Serial.println("Motion");      // print message
  } else {                          // if no motion
    digitalWrite(ledPin, LOW);      // turn LED OFF
    Serial.println("No motion");   // print message
  }

  delay(500);                       // wait before next read
}

Practice: Explain this line: pirState = digitalRead(pirPin);


2. Capacitive Touch Sensor

int touchPin = 2;          // touch sensor pin
int ledPin = 13;           // LED pin
int touchState = 0;        // store touch value

void setup() {
  pinMode(touchPin, INPUT);    // read touch input
  pinMode(ledPin, OUTPUT);     // control LED
}

void loop() {
  touchState = digitalRead(touchPin);   // HIGH = touched, LOW = not touched

  if (touchState == HIGH) {             // if finger touches sensor
    digitalWrite(ledPin, HIGH);         // LED ON
  } else {                              // no touch
    digitalWrite(ledPin, LOW);          // LED OFF
  }
}

3. Step Response Sensor (Analog Read)

int sensorPin = A0;        // analog input pin
int value = 0;             // store sensor value

void setup() {
  Serial.begin(9600);      // start serial monitor
}

void loop() {
  value = analogRead(sensorPin);   // read value from 0 to 1023

  Serial.println(value);           // show value on screen

  delay(200);                      // small delay
}

4. Ultrasonic Sensor (Distance)

int trigPin = 9;          // send signal
int echoPin = 10;         // receive signal
long duration;            // time of signal travel
int distance;             // calculated distance

void setup() {
  pinMode(trigPin, OUTPUT);   // trigger output
  pinMode(echoPin, INPUT);    // echo input
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);   // send pulse
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);   // measure return time

  distance = duration * 0.034 / 2;     // convert to cm

  Serial.println(distance);

  delay(500);
}

5. LDR (Light Sensor)

int ldrPin = A0;        // light sensor pin
int ledPin = 13;        // LED pin
int lightValue = 0;     // store light value

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  lightValue = analogRead(ldrPin);   // read light level

  if (lightValue < 500) {            // if dark
    digitalWrite(ledPin, HIGH);      // LED ON
  } else {
    digitalWrite(ledPin, LOW);       // LED OFF
  }

  Serial.println(lightValue);
  delay(300);
}

6. Temperature Sensor (LM35)

int tempPin = A0;        // temperature sensor pin
float temperature;       // store temperature value

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

void loop() {
  int value = analogRead(tempPin);    // read sensor value

  temperature = value * (5.0 / 1023.0) * 100;  // convert to Celsius

  Serial.print("Temp: ");
  Serial.println(temperature);

  delay(500);
}

How to Practice

  1. Read one sensor at a time
  2. Explain one line in simple words
  3. If not clear, rewrite simpler
  4. Repeat until confident

You can come back and we continue step by step.


Mini Dictionary (Core Arduino Concepts)

Commands (Functions you call)

pinMode()

pinMode(13, OUTPUT); // set pin 13 as OUTPUT
  • Definition: tells Arduino if a pin is INPUT or OUTPUT
  • Purpose: prepare a pin before using it
  • Arguments: (pin number, mode)

Serial.begin()

Serial.begin(9600); // start serial communication
  • Definition: starts communication with computer
  • Purpose: send/receive data via Serial Monitor
  • Argument: speed (baud rate)

digitalWrite()

digitalWrite(13, HIGH); // turn LED ON
  • Definition: write HIGH or LOW to a digital pin
  • Purpose: control devices (LED, relay)
  • Arguments: (pin, value)

analogRead()

int v = analogRead(A0); // read analog value
  • Definition: reads analog value (0–1023)
  • Purpose: get sensor levels (light, temp)
  • Argument: analog pin

Serial.println()

Serial.println(v); // print value with new line
  • Definition: prints data to Serial Monitor
  • Purpose: debugging and observing values
  • Argument: data to print

Core Concepts

function

void setup() { }
  • Definition: a block of code that does a task
  • Use: organize code (setup runs once, loop repeats)

command

digitalWrite(13, HIGH);
  • Definition: an instruction you give to Arduino
  • Use: performs an action immediately

arguments

pinMode(13, OUTPUT);
  • Definition: values passed into a function
  • Use: tell the function what to work with

variable

int x = 5;
  • Definition: named storage for a value
  • Use: save and reuse data

datatype

int a = 1;        // integer (whole number)
float b = 2.5;    // decimal number
String s = "Hi"; // text
bool f = true;    // true/false
  • Definition: type of data a variable holds
  • Use: choose based on needed value

conditional

if (a == 1) { }
  • Definition: decision making (if/else)
  • Use: run code based on a condition

math operators

int c = a + 2; // + - * /
  • Definition: arithmetic operations
  • Use: calculations

comparison operators

if (a == 1) { }
if (a != 2) { }
  • Definition: compare values
  • Use: conditions (true/false)

library

#include <Servo.h>
  • Definition: pre-written code you can use
  • Use: add features (servo, sensors)

Small Combined Example

int led = 13;                 // variable (int)
int sensor = A0;              // variable (int)

void setup() {                // function
  pinMode(led, OUTPUT);       // command with arguments
  Serial.begin(9600);         // command
}

void loop() {                 // function
  int value = analogRead(sensor);   // read sensor

  if (value > 500) {          // conditional + comparison
    digitalWrite(led, HIGH);  // command
  } else {
    digitalWrite(led, LOW);   // command
  }

  int doubled = value * 2;    // math operator
  Serial.println(doubled);    // print result
}