0% found this document useful (0 votes)
26 views42 pages

Introduction To IOT Lab Manual

iot lab questions

Uploaded by

Prasoon Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views42 pages

Introduction To IOT Lab Manual

iot lab questions

Uploaded by

Prasoon Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Experiment 1

Setting Up the Arduino Development Environment

1. Install the Arduino IDE:


o Go to the official Arduino website: https://www.arduino.cc/en/software.
o Download the version appropriate for your operating system (Windows, macOS, or Linux).
o Install the Arduino IDE following the provided instructions for your OS.
2. Install Drivers (if necessary):
o If you're using Windows, the IDE should automatically install the necessary drivers when you
plug in the Arduino board.
o If you're using a non-Windows system or your device is not recognized, you might need to
manually install drivers, which you can find on the Arduino website.
3. Set Up Your Arduino Board:
o Open the Arduino IDE.
o Select your board type and port:
 Go to Tools > Board > [Your Arduino Board Type] (e.g., Arduino Uno, Arduino
Mega).
 Go to Tools > Port > [Your Port] (e.g., COM3 on Windows or /dev/ttyUSB0 on
Linux).
4. Test the Setup with a Simple Sketch:
o To verify everything is working, load the Blink example:
 Go to File > Examples > Basics > Blink.
 Click the Upload button (arrow pointing right) in the IDE to upload the sketch to the
Arduino board.
o The built-in LED on the board (usually on pin 13) should blink on and off, confirming the IDE is
working properly.

Connecting Analog Sensors to an Arduino

Analog sensors can output varying voltage levels that the Arduino can read and process. To connect an analog
sensor:

1. Wiring the Analog Sensor:


o Identify the pins of your analog sensor. Most analog sensors have 3 pins:
 VCC (Power) Pin: This connects to the 5V or 3.3V pin on the Arduino board
(depending on your sensor's voltage requirement).
 GND (Ground) Pin: Connect to the GND pin on the Arduino.
 Signal Pin: Connect this pin to one of the Arduino's analog input pins (e.g., A0, A1, A2,
etc.).
o Example with a potentiometer (adjustable resistor):
 Connect the VCC pin to 5V on the Arduino.
 Connect the GND pin to GND.
 Connect the Signal Pin to the analog input pin (e.g., A0).
2. Powering the Arduino:
o Make sure the Arduino is powered either through a USB connection to your computer or through
an external power supply (if necessary).

Reading Analog Sensor Data

The Arduino board can read analog data using its analogRead() function. The Arduino has built-in analog-to-
digital converters (ADC) that convert the analog voltage input into a digital value.
1. Basic Code to Read Analog Sensor Data:
o The following code reads an analog value from the sensor and prints it to the Serial Monitor.

cpp
Copy code
// Define the analog pin where the sensor is connected
const int sensorPin = A0; // Connect sensor to pin A0

void setup() {
// Initialize serial communication at 9600 baud rate
Serial.begin(9600);
}

void loop() {
// Read the analog value from the sensor
int sensorValue = analogRead(sensorPin);

// Print the value to the Serial Monitor


Serial.println(sensorValue);

// Wait for a moment before reading again


delay(500);
}

2. Explanation of the Code:


o analogRead(sensorPin) reads the voltage on pin A0 (connected to the sensor). The value
returned is a number between 0 and 1023, corresponding to voltages between 0V and 5V (on
most Arduino boards).
o Serial.begin(9600) sets up serial communication so you can view the data in the Serial
Monitor.
o Serial.println(sensorValue) sends the value to the Serial Monitor.
o delay(500) pauses the program for half a second between readings.
3. Upload and Monitor Data:
o Upload the code to your Arduino board by clicking the Upload button in the IDE.
o Open the Serial Monitor in the IDE (Tools > Serial Monitor) to view the sensor data. You
should see numbers printed that correspond to the sensor's analog values.

Troubleshooting

 No Data in Serial Monitor:


o Ensure the correct port and board are selected in Tools > Board and Tools > Port.
o Verify that the sensor is connected correctly (VCC to 5V, GND to GND, Signal to the correct
analog pin).
 Inconsistent Data:
o Analog sensors may need some time to stabilize or require calibration. Consider adding a small
delay (delay(100)) in the loop if readings jump erratically.
o Make sure the sensor is powered correctly.
Experiment 2

Digital Input and Output with an Arduino Board

In addition to reading analog signals, Arduino also supports digital input and digital output operations. Digital
pins can either be HIGH (1) or LOW (0), representing binary values of 5V or 0V, respectively. Digital inputs
allow you to read on/off signals from devices like switches, while digital outputs can be used to control devices
like LEDs or relays.

Setting Up Digital Input and Output

1. Digital Output:
o You can use a digital output pin to control an external device such as an LED. The pin will either provide
a HIGH (5V) or LOW (0V) signal.

2. Digital Input:
o You can use a digital input pin to read the state of an external device, such as a button or a switch. The
input will either be HIGH (1) or LOW (0), depending on whether the device is activated or not.

Wiring Digital Devices

1. Controlling an LED (Digital Output):


o LED Connection:
 Connect the longer leg (anode) of the LED to one of the Arduino's digital output pins (e.g., pin
13).
 Connect the shorter leg (cathode) to a 220Ω resistor, and then connect the other side of the
resistor to GND.
2. Reading a Button (Digital Input):
o Button Connection:
 Connect one terminal of the push button to a digital input pin (e.g., pin 7).
 Connect the other terminal of the push button to GND.
 Optionally, connect a 10kΩ pull-up resistor between the input pin and 5V (for a stable HIGH
signal when the button is not pressed, though this is not strictly necessary as Arduino has built-
in pull-up resistors).

Writing Code for Digital Input and Output

Here’s how you can control an LED using a button. When the button is pressed, the LED will turn on, and
when it’s released, the LED will turn off.

1. Digital Output: Blink an LED

This simple example turns an LED on and off every second using a digital output pin.

cpp
Copy code
// Define the pin where the LED is connected
const int ledPin = 13; // Built-in LED on many Arduino boards (e.g., Arduino Uno)

void setup() {
// Set the LED pin as an output
pinMode(ledPin, OUTPUT);
}

void loop() {
// Turn the LED on (HIGH is the voltage level)
digitalWrite(ledPin, HIGH);
// Wait for a second (1000 milliseconds)
delay(1000);
// Turn the LED off by making the voltage LOW
digitalWrite(ledPin, LOW);
// Wait for another second
delay(1000);
}

 Explanation:
o pinMode(ledPin, OUTPUT) tells the Arduino that pin 13 is an output pin.
o digitalWrite(ledPin, HIGH) turns the LED on by sending 5V to pin 13.
o digitalWrite(ledPin, LOW) turns the LED off by sending 0V (ground).
o delay(1000) pauses the program for 1 second (1000 milliseconds).

2. Digital Input: Read a Button

This example reads the state of a button connected to a digital input pin and lights up an LED when the button
is pressed.

cpp
Copy code
// Define the pins for the button and LED
const int buttonPin = 7; // Pin where the button is connected
const int ledPin = 13; // Pin where the LED is connected

void setup() {
// Set the button pin as an input and the LED pin as an output
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}

void loop() {
// Read the state of the button (HIGH or LOW)
int buttonState = digitalRead(buttonPin);

// Check if the button is pressed (buttonState is HIGH)


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

 Explanation:
o pinMode(buttonPin, INPUT) sets pin 7 as an input for reading the button state.
o digitalRead(buttonPin) reads the state of the button and stores it in the buttonState variable.
o if (buttonState == HIGH) checks if the button is pressed (buttonState is HIGH when the button is
pressed and connected to GND).
o If the button is pressed, the LED turns on with digitalWrite(ledPin, HIGH). If the button is not
pressed, the LED is off.

Adding a Pull-up Resistor to the Button

By default, the Arduino input pins are floating when no voltage is applied. This could cause unpredictable
readings when the button is not pressed. To avoid this, you can enable the internal pull-up resistor for the
button pin. This eliminates the need for an external resistor.
Modify the code in the setup() function like this:

cpp
Copy code
pinMode(buttonPin, INPUT_PULLUP); // Enable the internal pull-up resistor

When using the internal pull-up resistor, you connect the button between the input pin and GND (instead of
5V). When the button is not pressed, the input pin will read HIGH (because of the pull-up resistor), and when
the button is pressed, it will read LOW (because it's connected to GND).

Example with Pull-up Resistor:


cpp
Copy code
// Define the pins for the button and LED
const int buttonPin = 7; // Pin where the button is connected
const int ledPin = 13; // Pin where the LED is connected

void setup() {
// Set the button pin as an input with an internal pull-up resistor
pinMode(buttonPin, INPUT_PULLUP);
// Set the LED pin as an output
pinMode(ledPin, OUTPUT);
}

void loop() {
// Read the state of the button (LOW when pressed, HIGH when not pressed)
int buttonState = digitalRead(buttonPin);

// Check if the button is pressed (buttonState is LOW because of pull-up)


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

Conclusion

With digital input and digital output, you can interact with external devices like switches, sensors, LEDs, and
relays using the Arduino board. By reading simple HIGH or LOW states, you can create interactive circuits
that respond to buttons or other digital signals.
Experiment 3

Integrating an Arduino board with a Raspberry Pi (R Pi) to send sensor data from the Arduino to the
Raspberry Pi is a common and useful project. The most straightforward way to achieve this communication is
by using the serial interface over USB or UART (Universal Asynchronous Receiver-Transmitter). We'll
use the USB method in this case, as it's simple to set up and doesn't require additional hardware.

Overview of Steps:

1. Connect the Arduino to the Raspberry Pi via USB.


2. Write a program on the Arduino to send sensor data over the serial connection.
3. Write a Python script on the Raspberry Pi to read the sensor data from the Arduino.

Step-by-Step Guide

1. Wiring and Connecting the Arduino to Raspberry Pi

 Physical Connection:
o Simply connect the Arduino to the Raspberry Pi using a USB cable. The Arduino will appear as a serial
device on the Raspberry Pi.

2. Arduino Code to Send Sensor Data via Serial

Let's assume you're using an analog sensor (like a temperature sensor or potentiometer) and want to send its
data to the Raspberry Pi.

 Open the Arduino IDE, write the following code to read the sensor and send the data to the Raspberry Pi via the
USB serial connection.

cpp
Copy code
// Define the analog input pin
const int sensorPin = A0; // Connect your sensor to A0

void setup() {
// Initialize serial communication at 9600 baud rate
Serial.begin(9600);
}

void loop() {
// Read the analog value from the sensor (0 to 1023)
int sensorValue = analogRead(sensorPin);

// Send the sensor data to the Raspberry Pi via serial


Serial.println(sensorValue);

// Wait a short time before reading again


delay(500);
}

 Explanation:
o The analogRead(sensorPin) reads the sensor value from the analog pin (A0).
o Serial.println(sensorValue) sends the value to the Raspberry Pi.
o delay(500) makes the Arduino wait 500 milliseconds before sending the next reading.

3. Upload the Arduino Code to the Board

 In the Arduino IDE, select the correct Board and Port under the Tools menu, then click the Upload button.
 Your Arduino should now be sending sensor data over the USB serial connection.
4. Set Up the Raspberry Pi

 Make sure your Raspberry Pi is set up with Raspberry Pi OS and is connected to the internet if needed.
 Open a terminal on the Raspberry Pi to install the required software and libraries for serial communication.

5. Install PySerial on the Raspberry Pi

PySerial is a Python library that makes it easy to interact with serial ports. If it's not already installed on your
Raspberry Pi, you can install it using pip.

bash
Copy code
sudo apt update
sudo apt install python3-pip
pip3 install pyserial

6. Python Script on the Raspberry Pi to Read Data from the Arduino

Create a Python script to read the sensor data sent from the Arduino. The serial port that the Arduino uses on
the Raspberry Pi is usually /dev/ttyUSB0 or /dev/ttyACM0, depending on the model of Arduino and how it's
recognized by the Raspberry Pi.

Create a new Python script:

bash
Copy code
nano read_arduino_data.py

Then add the following code to the script:

python
Copy code
import serial
import time

# Set up the serial connection to the Arduino (use correct port)


arduino = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)

# Wait for the serial connection to initialize


time.sleep(2)

# Continuously read and print data from Arduino


while True:
if arduino.in_waiting > 0:
sensor_data = arduino.readline().decode('utf-8').strip()
print(f"Sensor Data: {sensor_data}")

 Explanation:
o serial.Serial('/dev/ttyUSB0', 9600, timeout=1) initializes the serial connection to the
Arduino. If you're using a different port, you may need to change /dev/ttyUSB0 to /dev/ttyACM0 or
whatever port is assigned to your Arduino.
o time.sleep(2) ensures that the serial connection has time to initialize before the program starts
reading.
o arduino.readline() reads the data from the Arduino serial buffer.
o decode('utf-8').strip() decodes the byte string to a regular string and removes any extraneous
whitespace or newlines.

7. Run the Python Script on the Raspberry Pi

Now, run the Python script to start receiving data from the Arduino:

bash
Copy code
python3 read_arduino_data.py

 You should start seeing sensor readings printed on the screen from the Arduino every 500 milliseconds.

8. Troubleshooting Tips

 Permission Error on Serial Port:


o If you get a permission error when trying to access the serial port (/dev/ttyUSB0 or /dev/ttyACM0),
you can add your user to the dialout group to grant access to serial ports:

bash
Copy code
sudo usermod -aG dialout $USER
sudo reboot

 Incorrect Serial Port:


o If you're unsure which serial port the Arduino is connected to, you can use the following command to
list all connected devices:

bash
Copy code
ls /dev/tty*

Your Arduino device should appear as something like /dev/ttyUSB0 or /dev/ttyACM0.

9. Extended Use Cases

 Send Commands from Raspberry Pi to Arduino:


o You can also send commands or data from the Raspberry Pi to the Arduino by writing to the serial port.
You can modify your Arduino code to read data sent from the Raspberry Pi and take action accordingly
(e.g., turning on/off LEDs or adjusting sensor thresholds).

Example to send a command from Raspberry Pi to Arduino:

python
Copy code
arduino.write(b'ON\n') # Send an 'ON' command to the Arduino

Conclusion

By following these steps, you've integrated an Arduino board with a Raspberry Pi to send sensor data via a
serial communication channel. This opens up many possibilities for projects where you want to collect data
from sensors on the Arduino and process or display it on the Raspberry Pi, enabling more advanced processing,
storage, or web-based control.
Experiment 4

o set up Python on your Raspberry Pi and read data from an Arduino using Python, you need to follow these
steps. This guide will help you install Python, set up the necessary libraries, and run a sample Python program
to read data from the Arduino.

Steps:

1. Set Up Python on Raspberry Pi


2. Install Required Libraries
3. Connect Arduino to Raspberry Pi
4. Write Python Code to Read Data from Arduino
5. Run the Python Script

1. Set Up Python on Raspberry Pi

The Raspberry Pi typically comes with Python pre-installed, but you may want to ensure you're using the latest
version.

Check Python Version

Open a terminal on your Raspberry Pi and run:

bash
Copy code
python3 --version

This should output the version of Python 3 installed. The latest version at the time of writing is Python 3.x.

Install Python (if necessary)

If Python is not installed or you want to upgrade, run the following commands to install or update Python:

bash
Copy code
sudo apt update
sudo apt install python3 python3-pip

This will install Python 3 and pip3 (Python's package manager).

2. Install Required Libraries

To communicate with the Arduino via serial port, you need the PySerial library.

Install PySerial

Run the following command to install the pyserial library, which allows Python to read data from the Arduino
through the serial interface:

bash
Copy code
pip3 install pyserial

3. Connect Arduino to Raspberry Pi


Physical Setup

1. Connect the Arduino to the Raspberry Pi using a USB cable.


o The Arduino will appear as a serial device on the Raspberry Pi, typically under the name /dev/ttyUSB0
or /dev/ttyACM0.

2. Verify the Arduino connection:


o After plugging in the Arduino, check which serial device it is using by running:

bash
Copy code
ls /dev/tty*

o This will list all serial devices. If your Arduino is connected, you'll see something like
/dev/ttyUSB0 or /dev/ttyACM0.

4. Write Python Code to Read Data from Arduino

Now, let's create a Python script to read the data sent from the Arduino.

Arduino Code (to send data)

This code will read an analog sensor and send the data to the Raspberry Pi. Upload this to your Arduino first.

cpp
Copy code
// Define the analog input pin (e.g., a temperature sensor connected to A0)
const int sensorPin = A0;

void setup() {
// Start serial communication with the Raspberry Pi
Serial.begin(9600);
}

void loop() {
// Read the analog value (0 to 1023) from the sensor
int sensorValue = analogRead(sensorPin);

// Send the sensor value to the Raspberry Pi via serial


Serial.println(sensorValue);

// Wait a short period before reading again


delay(500);
}

Python Code (to read data from Arduino)

Create a Python script on the Raspberry Pi to read the sensor data from the Arduino.

1. Create a new Python file:

In the terminal, create a Python script:

bash
Copy code
nano read_arduino_data.py

2. Write the Python code:

Add the following code to the script:


python
Copy code
import serial
import time

# Set up the serial connection to the Arduino (replace with your serial port)
arduino = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)

# Wait for the serial connection to initialize


time.sleep(2)

# Continuously read data from the Arduino


while True:
if arduino.in_waiting > 0: # Check if there's data to read
sensor_data = arduino.readline().decode('utf-8').strip() # Read and decode
the data
print(f"Sensor Data: {sensor_data}")

o Explanation:
 serial.Serial('/dev/ttyUSB0', 9600, timeout=1) establishes a connection to the
Arduino over the serial port (/dev/ttyUSB0), with a baud rate of 9600.
 time.sleep(2) ensures the serial connection has time to initialize before the Python script
starts reading.
 arduino.readline() reads a line of data from the serial port.
 .decode('utf-8').strip() decodes the data into a readable string and removes any extra
whitespace or newline characters.

3. Save and exit the file:

Press Ctrl + X, then press Y to save and Enter to confirm.

5. Run the Python Script

Now, run the Python script to read the data from the Arduino.

bash
Copy code
python3 read_arduino_data.py

If everything is set up correctly, the Raspberry Pi will start displaying the sensor data sent from the Arduino.

Sample Output

You should see output similar to this, depending on the sensor connected to the Arduino:

yaml
Copy code
Sensor Data: 512
Sensor Data: 523
Sensor Data: 531
...

These values are the analog sensor readings sent from the Arduino over the serial connection.

Troubleshooting
 Permission Denied on Serial Port: If you get a PermissionError related to the serial port (e.g.,
/dev/ttyUSB0), you may need to add your user to the dialout group to grant permission to access the
serial port:

bash
Copy code
sudo usermod -aG dialout $USER
sudo reboot

 Incorrect Serial Port: If the script doesn't work because the serial port is incorrect, check which device
the Arduino is connected to:

bash
Copy code
ls /dev/tty*

The Arduino will typically appear as /dev/ttyUSB0 or /dev/ttyACM0.

Conclusion

You’ve now successfully set up Python on the Raspberry Pi, established a serial connection with an Arduino,
and used Python to read data from the Arduino. This setup is perfect for a variety of projects where the
Raspberry Pi processes sensor data collected by the Arduino. You can easily extend this by adding more
sensors, sending commands to the Arduino, or even controlling actuators like motors and LEDs from the
Raspberry Pi.
Experiment 5
To capture still images and video using the Raspberry Pi Camera Module with Python programming,
follow these steps to set up the hardware, install necessary software, and write the Python scripts.

Steps:

1. Connect the Raspberry Pi Camera Module


2. Enable the Camera Interface on the Raspberry Pi
3. Install the Necessary Software
4. Write Python Code to Capture Images and Video
5. Run the Python Scripts

1. Connect the Raspberry Pi Camera Module

1. Connect the Camera Module:


o Make sure the Raspberry Pi is powered off.
o Insert the Raspberry Pi Camera Module into the Camera Serial Interface (CSI) port on the Raspberry Pi.
This is a small, flat connector near the HDMI port.
o Gently pull up the plastic latch on the CSI port, insert the camera ribbon (blue side facing out), and push
the latch back down.

2. Check Camera Connection:


o After connecting the camera, power on your Raspberry Pi and proceed to the next steps.

2. Enable the Camera Interface on the Raspberry Pi

To use the Raspberry Pi Camera Module, you need to enable the camera interface via the Raspberry Pi
configuration tool.

1. Open the Raspberry Pi Configuration Tool:


o Open a terminal on the Raspberry Pi.
o Run the following command to open the configuration tool:

bash
Copy code
sudo raspi-config

2. Enable Camera:
o Navigate to Interfacing Options > Camera.
o Select Enable to turn on the camera module.
o After enabling, it will ask you to reboot the Raspberry Pi. Select Yes and press Enter to restart the
system.

3. Test the Camera (Optional):


o After rebooting, you can test the camera using the command:

bash
Copy code
raspistill -o test.jpg

o This command will capture a still image and save it as test.jpg. If this works, the camera module
is properly set up.

3. Install the Necessary Software


For Python programming, you’ll use the picamera library to interact with the camera module.

1. Install the picamera library:

To install the picamera Python library, run:

bash
Copy code
sudo apt update
sudo apt install python3-picamera

This will install the Python bindings for the Raspberry Pi Camera.

4. Write Python Code to Capture Images and Video

Once the camera is connected and the necessary software is installed, you can start capturing images and
videos.

Python Code to Capture a Still Image

1. Create a Python script:

Open a terminal and create a new Python file:

bash
Copy code
nano capture_image.py

2. Write the following code to capture an image:

python
Copy code
import time
import picamera

# Create a PiCamera object


camera = picamera.PICamera()

# Give the camera time to initialize


time.sleep(2)

# Capture a still image


camera.capture('image.jpg')

# Close the camera


camera.close()

o Explanation:
 picamera.PICamera() creates a camera object.
 camera.capture('image.jpg') captures a still image and saves it as image.jpg.
 time.sleep(2) gives the camera some time to initialize properly.
 camera.close() shuts down the camera after capturing the image.

3. Run the Python script:

To capture the image, run the Python script:

bash
Copy code
python3 capture_image.py
o After running the script, you should find the image saved as image.jpg in your current directory.

Python Code to Capture Video

To capture video, you can use the record_video function from the picamera library.

1. Create a Python script for video capture:

Open a new Python file:

bash
Copy code
nano capture_video.py

2. Write the following code to capture a video:

python
Copy code
import picamera
import time

# Create a PiCamera object


camera = picamera.PICamera()

# Give the camera time to initialize


time.sleep(2)

# Start recording a video


camera.start_recording('video.h264')

# Record for 10 seconds


time.sleep(10)

# Stop recording
camera.stop_recording()

# Close the camera


camera.close()

o Explanation:
 camera.start_recording('video.h264') starts recording a video and saves it as
video.h264.
 time.sleep(10) allows the video to record for 10 seconds.
 camera.stop_recording() stops the video recording.
 camera.close() shuts down the camera after recording.

3. Run the Python script:

To capture the video, run the Python script:

bash
Copy code
python3 capture_video.py

o After running the script, you should find the video saved as video.h264 in your current directory.
o Note: The .h264 file is in raw format, so you may want to convert it to a more common format
like .mp4 for playback using the following command:

bash
Copy code
MP4Box -add video.h264 video.mp4
If MP4Box is not installed, you can install it using:

bash
Copy code
sudo apt install gpac

5. Run the Python Scripts

Now that you’ve written the Python scripts, you can run them to capture still images and video.

 To capture an image:

bash
Copy code
python3 capture_image.py

 To capture a video:

bash
Copy code
python3 capture_video.py

Once the scripts are run, the Raspberry Pi Camera will capture the image or video as specified and save it to
your working directory.

Conclusion

You’ve successfully connected the Raspberry Pi Camera Module to your Raspberry Pi, enabled the camera,
installed necessary software, and written Python programs to capture both still images and video. This setup is
perfect for projects that involve photography, surveillance, time-lapse photography, or video streaming.
Experiment 6

Setting up a TCP/IP socket server on a PC and sending a message from a Raspberry Pi (R Pi) to the PC
using socket communication involves creating a server program on the PC (which listens for connections) and
a client program on the Raspberry Pi (which sends the message to the server). Here's how to do this step-by-
step:

1. Set Up a TCP/IP Socket Server on the PC

Python Server Program (PC Side)

1. Install Python (if not installed): Make sure Python is installed on the PC. If not, install it from the
official Python website.
2. Create the Server Script:
o Open a text editor or terminal and create a Python script (let's name it server.py).

3. Write the Python Server Code: The Python server listens for connections on a specified IP address
and port number.

python
Copy code
import socket

# Set up the server socket


host = '0.0.0.0' # Listen on all available network interfaces
port = 12345 # Port to listen on (ensure this is not in use by other applications)

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a TCP


socket
server_socket.bind((host, port)) # Bind the socket to the host and port
server_socket.listen(1) # Listen for incoming connections (max 1 connection)

print(f"Server listening on {host}:{port}...")

# Accept a connection from a client (Raspberry Pi)


client_socket, client_address = server_socket.accept()
print(f"Connection established with {client_address}")

# Receive and print the message from the client


message = client_socket.recv(1024).decode('utf-8')
print(f"Message from client: {message}")

# Close the connection


client_socket.close()
server_socket.close()

4. Explanation:
o socket.socket(socket.AF_INET, socket.SOCK_STREAM): Creates a TCP socket using IPv4.
o server_socket.bind((host, port)): Binds the socket to the specified IP address and port.
o server_socket.listen(1): Tells the server to listen for incoming connections (up to 1 connection in
this case).
o client_socket.recv(1024): Receives data from the client (Raspberry Pi) with a buffer size of 1024
bytes.
o The message received from the Raspberry Pi is printed on the console.

5. Run the Server Script: Open a terminal on your PC and run the server program:

bash
Copy code
python server.py

The server will start listening on all network interfaces (0.0.0.0) on port 12345. Ensure that the
firewall on the PC allows incoming connections on this port.
2. Send a Message from the Raspberry Pi to the PC

Python Client Program (Raspberry Pi Side)

1. Ensure Python is Installed: Python should already be installed on the Raspberry Pi by default. You can
verify this by running:

bash
Copy code
python3 --version

2. Create the Client Script: Open a terminal on the Raspberry Pi and create a Python script (let's name it
client.py).
3. Write the Python Client Code: The Python client will send a message to the server (running on the
PC).

python
Copy code
import socket

# Define the server address and port


server_ip = 'PC_IP_ADDRESS' # Replace with the actual IP address of your PC
server_port = 12345 # The same port number used in the server

# Create a socket object


client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server


client_socket.connect((server_ip, server_port))

# Send a message to the server


message = "Hello from Raspberry Pi!"
client_socket.send(message.encode('utf-8'))

# Close the connection


client_socket.close()

4. Explanation:
o client_socket.connect((server_ip, server_port)): Connects to the server using the
specified IP address and port number.
o client_socket.send(message.encode('utf-8')): Sends the message to the server. The
message is encoded to bytes because sockets transmit data as bytes.
o client_socket.close(): Closes the socket after sending the message.

5. Run the Client Script: Open a terminal on the Raspberry Pi and run the client program:

bash
Copy code
python3 client.py

Make sure that the server_ip in the client code is the actual IP address of the PC.

3. Testing the Communication

1. Run the Server on the PC:


o Open a terminal on the PC and run the server.py script.

bash
Copy code
python server.py

The server should now be waiting for a connection.

2. Run the Client on the Raspberry Pi:


o On the Raspberry Pi, open a terminal and run the client.py script.

bash
Copy code
python3 client.py

3. Check the Output:


o On the PC, you should see the following message printed by the server:

vbnet
Copy code
Server listening on 0.0.0.0:12345...
Connection established with ('<Raspberry Pi IP>', 12345)
Message from client: Hello from Raspberry Pi!

o On the Raspberry Pi, the script will complete, having sent the message to the server.

4. Firewall and Network Configuration

1. Firewall on PC: Ensure that your PC firewall is not blocking the incoming connection on the port
you're using (12345 in this case). You can temporarily disable the firewall or allow incoming
connections on that port.
2. Network Configuration:
o Ensure that both the Raspberry Pi and the PC are on the same local network (connected to the same Wi-
Fi or LAN).
o If your PC has multiple network interfaces (e.g., Wi-Fi and Ethernet), ensure you are using the correct IP
address of the PC.

5. Enhancements and Error Handling

You can improve this basic communication setup by:

 Handling exceptions (e.g., connection errors, timeouts).


 Sending more complex messages (e.g., multiple lines or binary data).
 Setting up multi-threading for handling multiple clients.

Example of Error Handling (Client):


python
Copy code
try:
client_socket.connect((server_ip, server_port))
client_socket.send(message.encode('utf-8'))
except Exception as e:
print(f"Error: {e}")
finally:
client_socket.close()

Conclusion
You’ve successfully set up a TCP/IP socket server on a PC and a client on the Raspberry Pi to send
messages between them. This basic setup allows you to establish a communication channel over a network,
which can be expanded for more complex applications such as remote control, sensor data transmission, or
chatting between devices.

Experiment 7

Setting up an MQTT broker on your PC and using the MQTT protocol to send and receive data between the
Raspberry Pi (R Pi) and the PC involves several steps. MQTT is a lightweight messaging protocol designed
for small sensors and mobile devices, making it ideal for communication between devices in IoT applications.

We'll set up the MQTT broker (a server that manages message delivery) on the PC and use the Raspberry Pi
to publish and subscribe to messages. Below are the detailed steps to set this up:

Steps Overview:

1. Set Up an MQTT Broker on the PC


2. Install MQTT Client Libraries on Raspberry Pi
3. Publish Data from R Pi to PC
4. Receive Data from PC to R Pi
5. Test the Communication

1. Set Up an MQTT Broker on the PC

You can use Mosquitto, which is one of the most popular MQTT brokers. Here’s how to set it up on your PC.

Install Mosquitto MQTT Broker on PC

1. Install Mosquitto: Open a terminal on the PC and install the Mosquitto broker:
o On Ubuntu/Debian-based systems:

bash
Copy code
sudo apt update
sudo apt install mosquitto mosquitto-clients

o On Windows or other OS, download the Mosquitto installer from the official site: Mosquitto
Downloads
2. Start the Mosquitto Service:
o On Linux:

bash
Copy code
sudo systemctl enable mosquitto
sudo systemctl start mosquitto

o On Windows, run Mosquitto from the Start Menu or manually launch the Mosquitto service.
3. Verify Mosquitto is Running:
o To check if Mosquitto is running properly, use the following command on the PC (Linux):

bash
Copy code
systemctl status mosquitto

4. This will show the status of the MQTT broker. If it's running correctly, the service should be active.
2. Install MQTT Client Libraries on Raspberry Pi

The Paho MQTT Python client library allows your Raspberry Pi to communicate with the MQTT broker.

1. Install the Paho MQTT Python library on the Raspberry Pi:

bash
Copy code
sudo apt update
sudo apt install python3-pip
pip3 install paho-mqtt

2. Verify Installation: To verify that the Paho MQTT library has been installed, open Python and try
importing it:

bash
Copy code
python3
>>> import paho.mqtt.client as mqtt

If there are no errors, the installation was successful.

3. Publish Data from Raspberry Pi to PC

On the Raspberry Pi, you will create a simple Python script to publish messages to the MQTT broker running
on the PC.

1. Create a Python script to publish a message:

Open a terminal on the Raspberry Pi and create a new Python file called mqtt_publish.py:

bash
Copy code
nano mqtt_publish.py

2. Write the publish code:

python
Copy code
import paho.mqtt.client as mqtt
import time

# MQTT broker details


broker_address = "PC_IP_ADDRESS" # Replace with the actual IP address of your PC
port = 1883 # Default MQTT port

# Define the MQTT client


client = mqtt.Client()

# Connect to the MQTT broker


client.connect(broker_address, port=port)

# Publish a message
client.publish("test/topic", "Hello from Raspberry Pi!")

# Wait for the message to be sent


time.sleep(1)

# Disconnect from the broker


client.disconnect()
o Explanation:
 client.connect(broker_address, port=port) connects the Raspberry Pi to the MQTT
broker on the PC.
 client.publish("test/topic", "Hello from Raspberry Pi!") sends the message
"Hello from Raspberry Pi!" to the test/topic topic.
 The Raspberry Pi disconnects after sending the message.

3. Run the script:

bash
Copy code
python3 mqtt_publish.py

4. Check for the message on the PC (using Mosquitto client):

Open a terminal on your PC and subscribe to the topic to receive messages:

bash
Copy code
mosquitto_sub -h localhost -t "test/topic"

o Explanation: mosquitto_sub subscribes to the test/topic and listens for messages on that topic.
o You should see the message "Hello from Raspberry Pi!" printed in the terminal.

4. Receive Data from PC to Raspberry Pi

Now, you’ll send data from the PC to the Raspberry Pi.

1. Create a Python script to subscribe to the topic:

Open a terminal on the Raspberry Pi and create a new Python file called mqtt_subscribe.py:

bash
Copy code
nano mqtt_subscribe.py

2. Write the subscribe code:

python
Copy code
import paho.mqtt.client as mqtt

# MQTT broker details


broker_address = "PC_IP_ADDRESS" # Replace with the actual IP address of your PC
port = 1883 # Default MQTT port

# Callback function for when a message is received


def on_message(client, userdata, message):
print(f"Message received: {message.payload.decode()}")

# Define the MQTT client


client = mqtt.Client()

# Attach the callback function


client.on_message = on_message

# Connect to the broker


client.connect(broker_address, port=port)

# Subscribe to the topic


client.subscribe("test/topic")
# Loop forever, listening for messages
client.loop_forever()

o Explanation:
 client.on_message = on_message: This attaches a callback function (on_message) to
handle incoming messages.
 client.subscribe("test/topic"): The Raspberry Pi subscribes to the test/topic topic.
 client.loop_forever(): This makes the client continuously listen for messages.

3. Run the subscribe script:

bash
Copy code
python3 mqtt_subscribe.py

4. Send a message from the PC:

Open a terminal on the PC and publish a message to the same topic:

bash
Copy code
mosquitto_pub -h localhost -t "test/topic" -m "Hello from PC!"

o Explanation: mosquitto_pub sends the message "Hello from PC!" to the test/topic topic.

5. Check the message on the Raspberry Pi:


o The Raspberry Pi will receive the message and print it to the terminal as:

csharp
Copy code
Message received: Hello from PC!

5. Test the Communication

You’ve successfully set up MQTT communication between the Raspberry Pi and the PC. Here's how you can
test it:

1. Publish from Raspberry Pi to PC: Run mqtt_publish.py on the Raspberry Pi and use mosquitto_sub on the
PC to receive messages.
2. Publish from PC to Raspberry Pi: Run mqtt_subscribe.py on the Raspberry Pi and use mosquitto_pub on
the PC to send messages.

Conclusion

You’ve now set up a Mosquitto MQTT broker on your PC and used MQTT to send and receive data between
the Raspberry Pi and the PC. This setup is ideal for IoT applications where devices communicate with each
other via lightweight, publish-subscribe messaging protocols. You can extend this communication by adding
more topics, more devices, and even more complex message structures like JSON.
Experiment 8

To achieve this task, we’ll integrate an Arduino with a Raspberry Pi (R Pi), use MQTT to send a message
from a PC to the Raspberry Pi, and have the Raspberry Pi control the LED lights connected to the Arduino
based on the received message.

Overview of the Steps:

1. Set up the Arduino with LEDs.


2. Connect the Arduino to the Raspberry Pi.
3. Install MQTT libraries on Raspberry Pi.
4. Set up MQTT communication:
o Send a message from the PC to the Raspberry Pi via MQTT.
o On receipt of the message, toggle the LED on the Arduino from the Raspberry Pi.
5. Test the system.

1. Set up the Arduino with LEDs

Hardware Setup for Arduino:

 LED Connections:
o Connect an LED to one of the digital pins (for example, Pin 13) on the Arduino.
o Use a 220-ohm resistor in series with the LED to prevent excess current.
o Connect the anode (longer leg) of the LED to pin 13 on the Arduino and the cathode (shorter leg) to the
ground (GND).

Arduino Sketch (Code) to Control the LED:

Here is a simple Arduino code to control an LED connected to pin 13.

cpp
Copy code
int ledPin = 13; // Pin where the LED is connected

void setup() {
pinMode(ledPin, OUTPUT); // Set LED pin as output
Serial.begin(9600); // Start serial communication
}

void loop() {
if (Serial.available()) { // Check if data is available on serial port
char receivedChar = Serial.read(); // Read the incoming byte
if (receivedChar == '1') {
digitalWrite(ledPin, HIGH); // Turn LED ON
} else if (receivedChar == '0') {
digitalWrite(ledPin, LOW); // Turn LED OFF
}
}
}

 Explanation: The Arduino listens for data on the serial port. If it receives '1', it turns the LED on, and if it
receives '0', it turns the LED off.
2. Connect the Arduino to the Raspberry Pi

To communicate between the Raspberry Pi and the Arduino, you will use the serial connection over USB.

1. Connect the Arduino to the Raspberry Pi via the USB cable.


2. Open a terminal on the Raspberry Pi and verify the connection by checking the serial ports:

bash
Copy code
ls /dev/tty*

You should see something like /dev/ttyUSB0 or /dev/ttyACM0 (the exact name may vary). This is the
serial port where the Arduino is connected.

3. Install MQTT Libraries on Raspberry Pi

You’ll use the Paho MQTT client library for Python to connect the Raspberry Pi to the MQTT broker.

1. Install the Paho MQTT library:

bash
Copy code
sudo apt update
sudo apt install python3-pip
pip3 install paho-mqtt

4. Set up MQTT Communication

PC: Publish a Message via MQTT

On the PC, you’ll use the Mosquitto MQTT broker (which we installed earlier) to publish a message that will
toggle the LED on the Raspberry Pi.

1. Install MQTT Client on PC: If you haven't installed Mosquitto yet on the PC, you can install it via:

bash
Copy code
sudo apt install mosquitto mosquitto-clients

2. Publish a message to toggle the LED: Open a terminal on the PC and use the following command to
publish a message to the led/control topic.

To turn the LED ON (send '1'):

bash
Copy code
mosquitto_pub -h <Raspberry_Pi_IP> -t "led/control" -m "1"

To turn the LED OFF (send '0'):

bash
Copy code
mosquitto_pub -h <Raspberry_Pi_IP> -t "led/control" -m "0"

Replace <Raspberry_Pi_IP> with the IP address of your Raspberry Pi.


Raspberry Pi: Subscribe to the MQTT Topic

The Raspberry Pi will listen for messages on the led/control topic and send corresponding commands to the
Arduino.

1. Python Script to Subscribe to MQTT Topic:

On the Raspberry Pi, create a Python script to listen to the topic and send commands to the Arduino
over the serial connection.

o Open a terminal on the Raspberry Pi and create a Python script mqtt_led_control.py:

bash
Copy code
nano mqtt_led_control.py

o Write the following code:

python
Copy code
import paho.mqtt.client as mqtt
import serial
import time

# MQTT Setup
broker_address = "localhost" # Use PC IP if the broker is running on the PC
port = 1883
topic = "led/control"

# Serial Setup for Arduino (adjust the serial port name as needed)
arduino = serial.Serial('/dev/ttyUSB0', 9600) # Replace with your Arduino
port
time.sleep(2) # Wait for the Arduino to initialize

# Callback function when a message is received from the MQTT broker


def on_message(client, userdata, message):
msg = message.payload.decode()
print(f"Received message: {msg}")

if msg == "1":
arduino.write(b'1') # Send '1' to Arduino to turn LED ON
elif msg == "0":
arduino.write(b'0') # Send '0' to Arduino to turn LED OFF

# MQTT Client Setup


client = mqtt.Client()
client.on_message = on_message

# Connect to the MQTT broker


client.connect(broker_address, port=port)

# Subscribe to the topic


client.subscribe(topic)

# Start the loop to listen for messages


client.loop_forever()

o Explanation:
 The script connects to the MQTT broker (running on your PC or Raspberry Pi) and subscribes to
the led/control topic.
 When a message is received ("1" or "0"), it writes that message to the Arduino's serial port,
which will toggle the LED.

2. Run the Python Script:


Run the script on the Raspberry Pi:

bash
Copy code
python3 mqtt_led_control.py

5. Test the System

1. Run the Arduino Sketch:


o Upload the Arduino sketch (led_control.ino) to your Arduino board using the Arduino IDE.

2. Run the MQTT Client on the PC:


o Open a terminal on the PC and use mosquitto_pub to publish messages to the led/control
topic to toggle the LED.
o To turn the LED ON, run:

bash
Copy code
mosquitto_pub -h <Raspberry_Pi_IP> -t "led/control" -m "1"

o To turn the LED OFF, run:

bash
Copy code
mosquitto_pub -h <Raspberry_Pi_IP> -t "led/control" -m "0"

3. Observe the LED on the Arduino:


o When the Raspberry Pi receives the message, it will forward it to the Arduino, which will toggle the LED
on or off based on the received message.

Conclusion

You’ve successfully set up an MQTT-based communication system where the PC sends messages to the
Raspberry Pi, and the Raspberry Pi controls an Arduino to toggle an LED based on those messages. This
setup can be expanded for controlling multiple devices, sensors, or actuators.
Experiment 9

o complete this task, we will walk through the following steps:

1. Set up an account with a cloud service (Google Cloud, AWS, or Azure).


2. Set up a simple HTTP server using Python (Flask).
3. Capture an image with the Raspberry Pi Camera Module.
4. Push the captured image to the HTTP server.
5. Store the image in the cloud service (in a database or file).

1. Set Up an Account with a Cloud Service

You can choose any of the following cloud providers: Google Cloud, AWS, or Azure. Let's proceed with a
general overview of the steps to set up an account with these services.

Google Cloud:

 Go to Google Cloud Console.


 Sign in with your Google account.
 Create a new project.
 Enable APIs for Google Cloud Storage to store images or Google Cloud Firestore/Datastore if you want to store
metadata in a database.
 Set up Cloud Storage Bucket (or Firestore if you prefer).

AWS:

 Go to AWS Management Console.


 Sign in with your AWS account.
 Create a new S3 bucket (for storing images) or set up Amazon RDS (for storing metadata).
 Enable AWS SDK for Python (Boto3) for communication.

Azure:

 Go to Azure Portal.
 Sign in with your Microsoft account.
 Create a new Storage Account (for file storage) or set up Azure Cosmos DB (if you want to store metadata).
 You’ll use Azure SDK for Python to interact with Azure services.

2. Set Up a Simple HTTP Server Using Python (Flask)

We’ll use Flask, a lightweight Python web framework, to create a simple HTTP server that will accept images.

1. Install Flask on the Raspberry Pi:

bash
Copy code
sudo apt update
sudo apt install python3-pip
pip3 install Flask
2. Create the Flask Server:

Create a new Python script, app.py, on your Raspberry Pi.

bash
Copy code
nano app.py

Add the following code to create a simple HTTP server that will accept image uploads:

python
Copy code
from flask import Flask, request
import os

app = Flask(__name__)

# Set the folder where you want to save the uploaded images
UPLOAD_FOLDER = '/path/to/store/images' # e.g., '/home/pi/uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/upload', methods=['POST'])
def upload_image():
if 'file' not in request.files:
return "No file part", 400

file = request.files['file']

if file.filename == '':
return "No selected file", 400

# Save the file to the server


file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(file_path)
return f"Image uploaded successfully: {file_path}", 200

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)

o Explanation:
 This Flask app listens for POST requests at /upload.
 The uploaded image file is saved to the specified UPLOAD_FOLDER.
 You need to replace /path/to/store/images with a valid directory on the Raspberry Pi.

3. Run the Flask Server:

To start the server, run the following command on your Raspberry Pi:

bash
Copy code
python3 app.py

The server should be running and listening on port 5000, accessible at


http://<raspberry_pi_ip>:5000/upload.

3. Capture an Image with the Raspberry Pi Camera

1. Install PiCamera Library:

You need the PiCamera library to interact with the Raspberry Pi Camera.
bash
Copy code
sudo apt update
sudo apt install python3-picamera

2. Capture an Image:

Create a Python script called capture_image.py to capture an image and send it to the HTTP server.

bash
Copy code
nano capture_image.py

Add the following code:

python
Copy code
import time
import picamera
import requests

# Initialize the camera


camera = picamera.PICamera()

# Capture an image
image_path = '/home/pi/Desktop/captured_image.jpg'
camera.capture(image_path)
camera.close()

# URL of the Flask HTTP server


url = 'http://<raspberry_pi_ip>:5000/upload'

# Open the image and send it to the server via POST request
with open(image_path, 'rb') as img_file:
files = {'file': (image_path, img_file, 'image/jpeg')}
response = requests.post(url, files=files)

print(response.text)

o Explanation:
 This script uses the picamera library to capture an image from the Raspberry Pi camera.
 The image is saved as captured_image.jpg.
 The image is sent via an HTTP POST request to the Flask server using the requests library.
 You should replace <raspberry_pi_ip> with your Raspberry Pi's IP address.

3. Run the Script to Capture and Upload the Image:

Execute the script on your Raspberry Pi:

bash
Copy code
python3 capture_image.py

This will capture the image from the camera and send it to your Flask HTTP server running on the
Raspberry Pi.

4. Store the Image in the Cloud

You now need to send the uploaded image to a cloud service, such as AWS S3, Google Cloud Storage, or
Azure Blob Storage.
AWS (S3)

1. Install AWS SDK (Boto3) on your Raspberry Pi:

bash
Copy code
pip3 install boto3

2. Modify Flask Code to Upload to S3:

Add the following code in app.py to upload the image to AWS S3:

python
Copy code
import boto3
from werkzeug.utils import secure_filename

# AWS credentials (set environment variables or use IAM roles for security)
s3_client = boto3.client('s3', region_name='us-east-1') # Change region if needed
bucket_name = 'your-s3-bucket-name' # Replace with your S3 bucket name

@app.route('/upload', methods=['POST'])
def upload_image():
if 'file' not in request.files:
return "No file part", 400

file = request.files['file']

if file.filename == '':
return "No selected file", 400

# Generate a unique filename and upload to S3


filename = secure_filename(file.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)

try:
# Upload the image to AWS S3
s3_client.upload_file(file_path, bucket_name, filename)
return f"Image uploaded successfully to S3: {filename}", 200
except Exception as e:
return f"Error uploading to S3: {str(e)}", 500

o Explanation: This code uses the boto3 library to upload the image to an S3 bucket.

3. Ensure AWS Credentials: Make sure your AWS credentials are set up on the Raspberry Pi. You can
set environment variables or use IAM roles if running on an EC2 instance.

Google Cloud Storage (GCS)

1. Install Google Cloud Storage Library:

bash
Copy code
pip3 install google-cloud-storage

2. Modify Flask Code to Upload to GCS:

python
Copy code
from google.cloud import storage
from werkzeug.utils import secure_filename

# Google Cloud Storage client


client = storage.Client()
bucket = client.get_bucket('your-bucket-name') # Replace with your GCS bucket name

@app.route('/upload', methods=['POST'])
def upload_image():
if 'file' not in request.files:
return "No file part", 400

file = request.files['file']

if file.filename == '':
return "No selected file", 400

# Generate a unique filename and upload to GCS


filename = secure_filename(file.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)

# Upload file to Google Cloud Storage


blob = bucket.blob(filename)
blob.upload_from_filename(file_path)
return f"Image uploaded to GCS successfully: {filename}", 200

o Explanation: This code uses google-cloud-storage to upload the file to Google Cloud Storage.

5. Test the System

1. Capture an Image and Upload:


o Run the capture_image.py script on the Raspberry Pi.
o The image will be captured and uploaded to your cloud storage.

2. Verify:
o Check your cloud service (AWS S3, Google Cloud Storage) to ensure the image has been uploaded.
o You can also verify it by checking the response from the HTTP server.

Conclusion

You’ve successfully set up a system where a Raspberry Pi captures an image using the Pi Camera, sends it
via HTTP to a Flask server, and uploads it to a cloud service such as AWS S3 or Google Cloud Storage. You
can now modify the server to store metadata or integrate further processing if needed.
Experiment 10

Developing a mobile application to view images captured by the Raspberry Pi camera involves several steps,
including setting up the Raspberry Pi to serve the images over the network, creating the mobile app, and
ensuring both components can communicate with each other effectively.

Below is a detailed guide on how to approach this:

Step 1: Set up the Raspberry Pi to Serve Images

First, we need to configure the Raspberry Pi to capture images from its camera and serve them over HTTP, so
the mobile application can fetch and display them.

1. Install Necessary Libraries on Raspberry Pi

Ensure that your Raspberry Pi has the required libraries for the camera module and serving HTTP content.

bash
Copy code
sudo apt update
sudo apt install python3-picamera
sudo apt install python3-flask

2. Create a Simple Flask Server to Serve Images

We’ll set up a basic Flask web server on the Raspberry Pi that will capture images from the camera and serve
them over HTTP.

1. Create a directory to store images (optional but recommended):

bash
Copy code
mkdir ~/camera_images

2. Create the Flask Application (app.py):

python
Copy code
from flask import Flask, send_file
import time
import picamera
import os

app = Flask(__name__)

# Path to store the captured images


image_folder = '/home/pi/camera_images'

# Route to capture and serve images


@app.route('/capture_image')
def capture_image():
# Capture the image using the Pi Camera
timestamp = time.strftime('%Y%m%d_%H%M%S')
image_path = os.path.join(image_folder, f"image_{timestamp}.jpg")

# Create a PiCamera object


with picamera.PICamera() as camera:
camera.capture(image_path)

# Return the image as a response


return send_file(image_path, mimetype='image/jpeg')

if __name__ == '__main__':
# Make sure the image folder exists
os.makedirs(image_folder, exist_ok=True)

# Run the Flask server on the Raspberry Pi


app.run(host='0.0.0.0', port=5000, debug=True)

 Explanation:
o The /capture_image endpoint captures an image using the Raspberry Pi camera and stores it with a
timestamped filename.
o The image is then served back as a response to the HTTP request using send_file.

3. Run the Flask server:

bash
Copy code
python3 app.py

 The server will now be running on http://<raspberry_pi_ip>:5000/capture_image.


 The Raspberry Pi will capture an image each time this endpoint is accessed and return the image file.

Step 2: Develop the Mobile Application

Now, let’s develop a mobile application to access and display these images.

We will create a cross-platform mobile app using Flutter. Flutter allows you to develop applications for both
iOS and Android from a single codebase.

1. Install Flutter

If you haven't already, follow the Flutter installation guide to set up Flutter on your machine.

2. Create a New Flutter Project

In the terminal, create a new Flutter project:

bash
Copy code
flutter create camera_viewer
cd camera_viewer

3. Modify the pubspec.yaml File to Add Dependencies

You will need the http package to make network requests and image to display the images. Open the
pubspec.yaml file and add the dependencies:

yaml
Copy code
dependencies:
flutter:
sdk: flutter
http: ^0.14.0
cached_network_image: ^3.2.0

Run the following command to install the packages:

bash
Copy code
flutter pub get

4. Write the Mobile Application Code

Edit the lib/main.dart file to create the user interface and network logic:

dart
Copy code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:cached_network_image/cached_network_image.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Raspberry Pi Camera Viewer',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CameraPage(),
);
}
}

class CameraPage extends StatefulWidget {


@override
_CameraPageState createState() => _CameraPageState();
}

class _CameraPageState extends State<CameraPage> {


String _imageUrl = '';

// Function to fetch the image from the Raspberry Pi server


void _fetchImage() async {
final response = await
http.get(Uri.parse('http://<raspberry_pi_ip>:5000/capture_image'));

if (response.statusCode == 200) {
setState(() {
_imageUrl = 'http://<raspberry_pi_ip>:5000/capture_image';
});
} else {
print('Failed to load image');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Raspberry Pi Camera Viewer'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_imageUrl.isEmpty
? Text('No image available.')
: CachedNetworkImage(
imageUrl: _imageUrl,
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _fetchImage,
child: Text('Fetch New Image'),
),
],
),
),
);
}
}

 Explanation:
o The app has a button that, when pressed, sends a GET request to the Flask server on the Raspberry Pi.
o The response from the server is the image, which is displayed using the CachedNetworkImage widget.
o Replace <raspberry_pi_ip> with the actual IP address of your Raspberry Pi.

5. Run the Flutter App

To test the app, connect your phone or use an emulator. Run the app using the following command:

bash
Copy code
flutter run

 The app should display a button labeled "Fetch New Image".


 When the button is pressed, the app will request an image from the Raspberry Pi and display it on the screen.

Step 3: Testing the Mobile App

1. Start the Flask Server on the Raspberry Pi if it’s not running:

bash
Copy code
python3 app.py

2. Run the Flutter Mobile App on your device or emulator:

bash
Copy code
flutter run

3. Fetch and View the Image:


o Press the "Fetch New Image" button in the mobile app to fetch and display the latest image captured by
the Raspberry Pi camera.

Step 4: Deploying the App (Optional)

If you want to make the app available on the app stores (Google Play or Apple App Store), you can:
 Build the APK (for Android):

bash
Copy code
flutter build apk

 Build the iOS App (for iPhone):

bash
Copy code
flutter build ios

Follow the necessary steps for publishing to Google Play or Apple App Store based on the platform.

Conclusion

You’ve successfully created a system where a Raspberry Pi captures images using its camera, and a mobile
app displays those images. The Flask web server on the Raspberry Pi serves the images, and the Flutter app
fetches and displays them. You can extend this system by adding more features such as image gallery, real-time
streaming, or additional camera control.

You might also like