0% found this document useful (0 votes)
20 views

Mod-5 Arduino & Raspberry Pi

Uploaded by

Sahoo Harish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Mod-5 Arduino & Raspberry Pi

Uploaded by

Sahoo Harish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

MODULE – 5

Introduction To Arduino:
Arduino is a prototype platform (open-source) based on an easy-to-use hardware and software. It consists
of a circuit board, which can be programmed (referred to as a microcontroller) and a ready-made software
called Arduino IDE (Integrated Development Environment), which is used to write and upload the
computer code to the physical board.
Key Features:
 Arduino boards are able to read analog or digital input signals from different sensors and turn it into an
output such as activating a motor, turning LED on/off, connect to the cloud and many other actions.
 You can control your board functions by sending a set of instructions to the microcontroller on the board
via Arduino IDE (referred to as uploading software).
 Unlike most previous programmable circuit boards, Arduino does not need an extra piece of hardware
(called a programmer) in order to load a new code onto the board. You can simply use a USB cable.
 The Arduino IDE uses a simplified version of C++, making it easier to learn to program.
 Arduino provides a standard form factor that breaks the functions of the micro-controller into a more
accessible package.

Various kinds of Arduino boards are available depending on different microcontrollers used. However, all
Arduino boards have one thing in common: they are programed through the Arduino IDE.
The differences are based on the number of inputs and outputs (the number of sensors, LEDs, and buttons
you can use on a single board), speed, operating voltage, form factor etc. Some boards are designed to be
embedded and have no programming interface (hardware), which you would need to buy separately.
Some can run directly from a 3.7V battery, others need at least 5V.
Different components of the Arduino UNO board:
It is the most popular board in the Arduino board family. It is the best board to get started with electronics
and coding.
Power USB
Arduino board can be powered by using the USB cable from your computer. All you need to do is
connect the USB cable to the USB connection (1).

Power (Barrel Jack)


Arduino boards can be powered directly from the AC mains power supply by connecting it to the
Barrel Jack (2).

Voltage Regulator
The function of the voltage regulator is to control the voltage given to the Arduino board and
stabilize the DC voltages used by the processor and other elements.

Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues. How does Arduino calculate time?
The answer is, by using the crystal oscillator. The number printed on top of the Arduino crystal is
16.000H9H. It tells us that the frequency is 16,000,000 Hertz or 16 MHz.

Arduino Reset
You can reset your Arduino board, i.e., start your program from the beginning. You can reset the
UNO board in two ways. First, by using the reset button (17) on the board. Second, you can connect
an external reset button to the Arduino pin labelled RESET (5).

Pins (3.3, 5, GND, Vin)


3.3V (6) − Supply 3.3 output volt
5V (7) − Supply 5 output volt
Most of the components used with Arduino board works fine with 3.3 volt and 5 volt.
GND (8)(Ground) − There are several GND pins on the Arduino, any of which can be used to ground
your circuit.
Vin (9) − This pin also can be used to power the Arduino board from an external power source, like
AC mains power supply.

Analog pins
The Arduino UNO board has six analog input pins A0 through A5. These pins can read the signal
from an analog sensor like the humidity sensor or temperature sensor and convert it into a digital
value that can be read by the microprocessor.

Main microcontroller
Each Arduino board has its own microcontroller (11). You can assume it as the brain of your board.
The main IC (integrated circuit) on the Arduino is slightly different from board to board. The
microcontrollers are usually of the ATMEL Company. You must know what IC your board has before
loading up a new program from the Arduino IDE. This information is available on the top of the IC.
For more details about the IC construction and functions, you can refer to the data sheet.

ICSP pin
Mostly, ICSP (12) is an AVR, a tiny programming header for the Arduino consisting of MOSI,
MISO, SCK, RESET, VCC, and GND. It is often referred to as an SPI (Serial Peripheral Interface),
which could be considered as an "expansion" of the output. Actually, you are slaving the output
device to the master of the SPI bus.

Power LED indicator


This LED should light up when you plug your Arduino into a power source to indicate that your
board is powered up correctly. If this light does not turn on, then there is something wrong with the
connection.

TX and RX LEDs
On your board, you will find two labels: TX (transmit) and RX (receive). They appear in two places
on the Arduino UNO board. First, at the digital pins 0 and 1, to indicate the pins responsible for serial
communication. Second, the TX and RX led (13). The TX led flashes with different speed while
sending the serial data. The speed of flashing depends on the baud rate used by the board. RX flashes
during the receiving process.

Digital I/O
The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM (Pulse Width
Modulation) output. These pins can be configured to work as input digital pins to read logic values (0
or 1) or as digital output pins to drive different modules like LEDs, relays, etc. The pins labeled “~”
can be used to generate PWM.

AREF
AREF stands for Analog Reference. It is sometimes, used to set an external reference voltage
(between 0 and 5 Volts) as the upper limit for the analog input pins.

Arduino IDE:
The Arduino IDE (Integrated Development Environment) is the software you use to write, edit, and upload
code to an Arduino board. It’s the tool that helps you communicate with your Arduino and make it do what you
want.
1. Need of the Arduino IDE
 Write Code: You write code in a programming language based on C/C++. The code consists of
instructions (called a sketch) that tell your Arduino what to do, like turning on an LED or reading sensor
data.
 Upload Code: After writing the code, you connect your Arduino board to your computer with a USB cable,
and with a click of a button in the IDE, the code is sent (or uploaded) to the Arduino. Then, the Arduino
starts running the code.
2. Main Parts of the Arduino IDE
 Text Editor: This is where you write and edit your code. It’s simple and has features like auto-coloring to
make the code easier to read.
 Verify Button: This checks your code for errors. If something’s wrong, it will highlight the problem so you
can fix it before uploading it to the Arduino.
 Upload Button: This sends the code to your Arduino so it can run your instructions.
 Serial Monitor: This is a tool that allows you to see real-time data from your Arduino on your computer
screen. It’s useful when you want to debug or see sensor readings, for example.
3. Libraries
The Arduino IDE lets you use libraries, which are collections of pre-written code that make it easier to work with
sensors, displays, or other devices. Instead of writing everything from scratch, you can include a library to simplify
the coding process.
4. Pre-written Examples
The IDE comes with many example codes. These are pre-written sketches for common tasks like blinking an LED,
reading a temperature sensor, or controlling a motor. It’s a great way to learn by doing.
5. How It Works
 Write: You write the code (the sketch) in the IDE.
 Check: The IDE verifies your code to make sure it’s correct.
 Upload: Once verified, you can upload the code to the Arduino board.
 Run: The Arduino executes your code and interacts with the physical world (turning lights on, moving
motors, etc.).

Arduino Installation & LED Blinking Program:

Infrared (IR) Sensor & Ultrasonic Sensor:


These sensors are commonly used for object detection and distance measurement in robotics, automation, and
obstacle avoidance systems.

1. Infrared (IR) Sensor:


How it Works:
An IR sensor uses infrared light to detect objects. It consists of an IR LED that emits infrared light and a
photodiode or receiver that detects the reflection of that light. When an object comes near the sensor, the infrared
light is reflected back to the photodiode, and the sensor detects the object.
Wiring/Connections:
 VCC (Power): Connect this pin to the 5V pin of the Arduino.
 GND (Ground): Connect to the GND pin of the Arduino.
 OUT (Signal Pin): This pin sends the detection signal to the Arduino. Connect it to any digital pin (e.g.,
D2).
Program for IR Sensor:
int irPin = 2; // Signal pin of IR sensor connected to D2
int ledPin = 13; // Built-in LED for indication

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

void loop() {
int sensorValue = digitalRead(irPin);

if (sensorValue == LOW) { // Object detected (depends on sensor model)


digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
digitalWrite(ledPin, LOW); // Turn off the LED
}
}

Program Working:
IR Sensor Program: It checks whether the sensor detects an object (LOW output) or not (HIGH output). When an
object is detected, the onboard LED turns on.

2. Ultrasonic Sensor:
How it Works:
An ultrasonic sensor (like the HC-SR04) uses sound waves to measure distance. It emits ultrasonic waves from
the TRIG pin, and the waves bounce back when they hit an object. The sensor receives the reflected waves through
the ECHO pin and calculates the time difference to determine the distance.
Wiring/Connections:
 VCC (Power): Connect to the 5V pin on the Arduino.
 GND (Ground): Connect to GND on the Arduino.
 TRIG (Trigger Pin): Connect to any digital pin (e.g., D9).
 ECHO (Echo Pin): Connect to any digital pin (e.g., D10).

Program for Ultrasonic Sensor:

const int trigPin = 9; // Trigger Pin connected to D9


const int echoPin = 10; // Echo Pin connected to D10
long duration;
int distance;

void setup() {
pinMode(trigPin, OUTPUT); // Trigger pin as output
pinMode(echoPin, INPUT); // Echo pin as input
Serial.begin(9600); // Initialize serial communication for debugging
}

void loop() {
// Send a 10 microsecond pulse to the TRIG pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Measure the duration of pulse on the ECHO pin


duration = pulseIn(echoPin, HIGH);

// Calculate the distance (speed of sound is 343 m/s, or 29.1 microseconds/cm)


distance = duration * 0.034 / 2;

// Print distance to the Serial Monitor


Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

delay(500); // Wait for 500 ms before next measurement


}

Programs Working:
Ultrasonic Sensor Program: It sends a short pulse from the TRIG pin, measures the time it takes for the
pulse to return via the ECHO pin, and calculates the distance to an object based on this time. The distance
is displayed in the Serial Monitor.
Soil Moisture Sensor & Temperature Sensor (DHT11 or DHT22):
These sensors are commonly used in agriculture, gardening, and environmental monitoring to track soil
moisture, temperature, and humidity for automated systems like watering plants or climate control.

3. Soil Moisture Sensor:

How it Works:
A soil moisture sensor measures the water content in the soil by detecting the electrical conductivity between two
probes. Wet soil conducts electricity better than dry soil, so the sensor can tell how moist the soil is based on the
resistance.
 When the soil is wet, the resistance is low (high conductivity).
 When the soil is dry, the resistance is high (low conductivity).
Wiring/Connections:
 VCC (Power): Connect to the 5V pin of the Arduino.
 GND (Ground): Connect to the GND pin of the Arduino.
 A0 (Analog Signal Pin): Connect to any analog pin on the Arduino (e.g., A0). This pin gives an analog
value (0-1023) representing the moisture level.
Program for Soil Moisture Sensor:

int moisturePin = A0; // Moisture sensor connected to A0


int moistureValue;

void setup() {
Serial.begin(9600); // Initialize serial communication for debugging
}

void loop() {
moistureValue = analogRead(moisturePin); // Read moisture level
Serial.print("Moisture Value: ");
Serial.println(moistureValue);

// Optional: Use the value to trigger an event


if (moistureValue < 300) {
Serial.println("Soil is dry!");
} else if (moistureValue < 700) {
Serial.println("Soil is moist.");
} else {
Serial.println("Soil is wet!");
}

delay(1000); // Wait for 1 second before reading again


}

Program Working:
Soil Moisture Sensor Program:
 The sensor measures the moisture level in the soil by reading the analog voltage on the A0 pin. The value
ranges from 0 (very dry) to 1023 (very wet).
 Based on this value, you can decide when to water plants.

4. Temperature Sensor (DHT11 or DHT22):

How it Works:
The DHT11 or DHT22 sensor measures temperature and humidity. It uses a capacitive humidity sensor and a
thermistor (for temperature) to measure the surrounding air and send the data to the Arduino.
 DHT11 is cheaper but less accurate than DHT22.
 They both communicate via a single digital pin.
Wiring/Connections:
 VCC (Power): Connect to the 5V pin of the Arduino.
 GND (Ground): Connect to the GND pin of the Arduino.
 DATA (Signal Pin): Connect to any digital pin (e.g., D2).
 Pull-up Resistor: You need a 10k ohm resistor between the VCC and DATA pin for stable
communication.
Program for Temperature Sensor (DHT11/DHT22):
First, install the DHT library:
 In the Arduino IDE, go to Sketch > Include Library > Manage Libraries.
 Search for DHT sensor library by Adafruit and install it.
Then, use the following program:

#include "DHT.h" // Include the DHT library

#define DHTPIN 2 // Pin connected to the DATA pin


#define DHTTYPE DHT11 // Change to DHT22 if using a DHT22 sensor

DHT dht(DHTPIN, DHTTYPE); // Initialize DHT object

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

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

// Read temperature as Celsius


float tempC = dht.readTemperature();

// Read humidity
float humidity = dht.readHumidity();

// Check if any readings failed


if (isnan(tempC) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

// Print temperature and humidity


Serial.print("Temperature: ");
Serial.print(tempC);
Serial.println(" °C");

Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
}

Program Working:
Temperature and Humidity Sensor Program (DHT11/DHT22):
 The DHT11/DHT22 sensor reads the temperature and humidity from the air. The DHT library simplifies
communication with the sensor.
 The program prints the temperature in Celsius and humidity in percentage on the serial monitor.
Difference between Arduino & Raspberry Pie:

Parameters Arduino Raspberry Pie

Control Unit The Control Unit of the Arduino is from The Control Unit of the Raspberry Pi is from
the ATmega family. the ARM family.

Basis Arduino works on the basis of a Raspberry Pi, on the other hand, works on
microcontroller. the basis of a microprocessor.

Use The Arduino basically helps in The Raspberry Pi primarily computes data
controlling all the electrical components and info for producing valuable outputs. It
that connect to a system’s circuit board. also controls the various components in any
given system on the basis of the outcome (of
the computation).

Structure of The Arduino boards have a very simple The Raspberry Pi boards consist of
Hardware and structure of software and hardware. comparatively complex software and
Software hardware architecture.

Type of CPU Arduino has an 8-bit architecture. Raspberry Pi has a 64-bit architecture.
Architecture

RAM Usage Arduino makes use of very little RAM of Raspberry Pi always requires more RAM
about 2 kB (Kilobytes). than Arduino of about 1 GB (Gigabytes).

Processing Speed Arduino clocks 16 MHz (Megahertz) of The Raspberry Pi clocks 1.4 GHz
processing speed in a system. (Gigahertz) of processing speed in a system.

Cost Efficiency It has a higher cost-efficiency because it It has a lower cost-efficiency because it is
is comparatively cheaper. comparatively more expensive.

I/O Drive The I/O current drive strength in the case The I/O current drive strength in the case of
Strength of Arduino is higher. Raspberry Pi is lower.

Power Arduino consumes power of about 200 Raspberry Pi consumes about 700 MW.
Consumption MW (Megawatts).

Write a python program for blinking LED.


# Set up the GPIO mode
GPIO.setmode(GPIO.BCM) # Use BCM pin numbering
GPIO.setwarnings(False) # Disable warnings

# Set the GPIO pin number where the LED is connected


LED_PIN = 18 # Replace with the GPIO pin number you are using

# Set up the LED pin as an output


GPIO.setup(LED_PIN, GPIO.OUT)

# Blink the LED in a loop


try:
while True:
GPIO.output(LED_PIN, GPIO.HIGH) # Turn LED on
print("LED ON")
time.sleep(1) # Wait for 1 second

GPIO.output(LED_PIN, GPIO.LOW) # Turn LED off


print("LED OFF")
time.sleep(1) # Wait for 1 second

except KeyboardInterrupt:
print("Stopped by User")
GPIO.cleanup() # Clean up the GPIO settings

Explanation:
 GPIO.setmode(GPIO.BCM): Sets the pin numbering mode to BCM (Broadcom SOC channel) to use the
GPIO number rather than pin number.
 GPIO.setup(LED_PIN, GPIO.OUT): Configures the specified pin as an output.
 GPIO.output(LED_PIN, GPIO.HIGH): Turns the LED on.
 GPIO.output(LED_PIN, GPIO.LOW): Turns the LED off.
 time.sleep(1): Pauses the program for 1 second, creating the blinking effect.
 try/except KeyboardInterrupt: Allows the user to exit the program safely with CTRL+C and cleans up
the GPIO settings.

Differentiate between Raspberry Pi and desktop computer.


Raspberry Pi Desktop Computer
Size & Form A very small, credit-card-sized single- Larger, consisting of multiple components
Factor board computer. (CPU, monitor, keyboard, etc.).
Processing Power Has a less powerful ARM-based Equipped with powerful processors (Intel,
processor, suitable for lightweight tasks, AMD) capable of handling intensive tasks
hobbyist projects, and basic computing. like gaming, video editing, and software
development.
Storage Uses microSD cards for storage Uses hard drives (HDD) or solid-state
(expandable), typically up to 128GB or drives (SSD), often offering terabytes of
more. storage.
RAM Has limited RAM, usually between 1GB Offers much larger RAM, typically starting
and 8GB depending on the model. from 4GB and going up to 64GB or more
for high-performance use.
OS Limited connectivity options, but More extensive connectivity, with multiple
includes USB, HDMI, Ethernet, and USB ports, audio jacks, multiple display
GPIO pins for connecting peripherals outputs, and expansion slots for graphics
and sensors. cards or other hardware.
Power Extremely low power consumption (5- Higher power consumption, often between
Consumption 15W). 100W and 500W depending on usage.
Cost Highly affordable, typically costing Much more expensive, ranging from a few
between $35 and $75 depending on the hundred to thousands of dollars, depending
model. on specifications.
Expandability Limited to external accessories and Highly expandable with options to add
components like cameras, sensors, and RAM, storage drives, graphics cards, and
displays through GPIO pins. more peripherals.

Write and explain traffic light control program using aurdino uno

import RPi.GPIO as GPIO


import time

import serial
import time

# Establish connection to the Arduino


arduino = serial.Serial(port='COM3', baudrate=9600, timeout=1) # Replace 'COM3' with your Arduino's
port
# Allow time for the connection to be established
time.sleep(2)

# Function to send a command to the Arduino


def control_traffic_light(command):
arduino.write(command.encode()) # Send the command as a byte
time.sleep(1) # Delay to allow the command to take effect

try:
while True:
# Simulate traffic light sequence
print("Green light ON")
control_traffic_light('G') # Turn on green light
time.sleep(5) # Wait for 5 seconds

print("Yellow light ON")


control_traffic_light('Y') # Turn on yellow light
time.sleep(2) # Wait for 2 seconds

print("Red light ON")


control_traffic_light('R') # Turn on red light
time.sleep(5) # Wait for 5 seconds

except KeyboardInterrupt:
# Turn off all lights when the program is interrupted
control_traffic_light('O')
print("Program stopped by user")

finally:
# Close the serial connection
arduino.close()

Explanation:
 Arduino Sketch:
o The Arduino reads incoming commands from the serial port ('G', 'Y', 'R', 'O').
o The respective pin (LED) is turned on or off based on the command received.
 Python Program:
o Establishes a serial connection with the Arduino.
o Sends commands ('G', 'Y', 'R', 'O') to control the lights.
o The time.sleep() function is used to create delays for the traffic light sequence.
 Command Details:
o 'G': Turns on the green light.
o 'Y': Turns on the yellow light.
o 'R': Turns on the red light.
o 'O': Turns off all lights.

Q. Describe interfacing a light sensor (LDR) with Raspberry Pi:

Interfacing a Light Dependent Resistor (LDR) with a Raspberry Pi involves using the LDR as part of a
voltage divider circuit to measure the ambient light levels. An LDR's resistance decreases with increasing
light intensity, allowing it to be used as a light sensor.
Components Required:
 Raspberry Pi (any model with GPIO)
 LDR (Light Dependent Resistor)
 10kΩ resistor (or a value that suits your LDR)
 Breadboard and jumper wires
 Optional: MCP3008 ADC (Analog-to-Digital Converter) if more precise readings are needed
Basic Principle:
Raspberry Pi's GPIO pins can only read digital values (0 or 1), not analog signals. Since the LDR outputs
an analog signal, it requires an analog-to-digital conversion. This can be done using:
1. A simple timing method using GPIO (for basic on/off sensing).
2. An ADC chip like the MCP3008 (for more precise readings).
Circuit Design:
1. Voltage Divider Setup:
o Connect one leg of the LDR to the 3.3V power supply on the Raspberry Pi.
o Connect the other leg of the LDR to a GPIO pin and one side of the 10kΩ resistor.
o Connect the other side of the 10kΩ resistor to GND.
This forms a voltage divider circuit, with the GPIO pin reading the voltage between the LDR and the
resistor. The voltage varies based on the LDR's resistance (which changes with light levels).
Basic On/Off Sensing Method
This method uses a GPIO pin to time how long it takes for a capacitor to discharge, indirectly measuring
light levels.

import RPi.GPIO as GPIO


import time

# Set up the GPIO pin


LDR_PIN = 18 # Replace with your GPIO pin

GPIO.setmode(GPIO.BCM)
GPIO.setup(LDR_PIN, GPIO.OUT)

def read_LDR():
count = 0

# Discharge the capacitor


GPIO.setup(LDR_PIN, GPIO.OUT)
GPIO.output(LDR_PIN, False)
time.sleep(0.1)

# Change the pin to input mode and count until the pin goes high
GPIO.setup(LDR_PIN, GPIO.IN)
while GPIO.input(LDR_PIN) == GPIO.LOW:
count += 1

return count

try:
while True:
light_level = read_LDR()
print("Light Level:", light_level)
time.sleep(1)
except KeyboardInterrupt:
print("Stopped by User")
finally:
GPIO.cleanup()

Explanation:
 The read_LDR() function times how long it takes for the voltage to rise above a threshold
(determined by the LDR and the resistor).
 The lower the light level, the higher the resistance of the LDR, and the longer it takes for the
voltage to reach the threshold.
 The output value light_level is a count indicating the light intensity (higher counts mean lower
light levels).

Q. Briefly discuss the characteristic features of Raspberry Pi device.

The Raspberry Pi is a small, affordable, and versatile single-board computer designed for educational and hobbyist
use. Its key features include:

1. Compact Size: It's about the size of a credit card, making it highly portable.

2. Affordable: Priced to be accessible for students, developers, and hobbyists.

3. Broad Connectivity: Includes USB ports, HDMI, Ethernet, GPIO pins for hardware projects, and wireless
capabilities (Wi-Fi and Bluetooth) in newer models.

4. Linux-based OS: Runs a variety of operating systems, most commonly Raspbian (now called Raspberry Pi
OS), a Debian-based Linux distribution.

5. Energy Efficient: Low power consumption, suitable for projects requiring continuous operation.

6. Versatile Use Cases: It can be used for programming, electronics projects, DIY IoT devices, media centers,
robotics, and more.

7. Expandable: Supports external peripherals like cameras, sensors, and displays via its GPIO pins and other
ports.

You might also like