Mod-5 Arduino & Raspberry Pi
Mod-5 Arduino & Raspberry Pi
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).
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).
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.
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.).
void setup() {
pinMode(irPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
int sensorValue = digitalRead(irPin);
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).
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);
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.
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:
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);
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.
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:
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 humidity
float humidity = dht.readHumidity();
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:
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).
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.
Write and explain traffic light control program using aurdino uno
import serial
import time
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
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.
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.
GPIO.setmode(GPIO.BCM)
GPIO.setup(LDR_PIN, GPIO.OUT)
def read_LDR():
count = 0
# 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).
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.
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.