Introduction To IOT Lab Manual
Introduction To IOT Lab Manual
Analog sensors can output varying voltage levels that the Arduino can read and process. To connect an analog
sensor:
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);
Troubleshooting
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.
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.
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.
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).
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);
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.
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).
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);
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:
Step-by-Step Guide
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.
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);
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.
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.
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
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.
bash
Copy code
nano read_arduino_data.py
python
Copy code
import serial
import time
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.
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
bash
Copy code
sudo usermod -aG dialout $USER
sudo reboot
bash
Copy code
ls /dev/tty*
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:
The Raspberry Pi typically comes with Python pre-installed, but you may want to ensure you're using the latest
version.
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.
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
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
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.
Now, let's create a Python script to read the data sent from the Arduino.
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);
Create a Python script on the Raspberry Pi to read the sensor data from the Arduino.
bash
Copy code
nano read_arduino_data.py
# Set up the serial connection to the Arduino (replace with your serial port)
arduino = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
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.
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*
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:
To use the Raspberry Pi Camera Module, you need to enable the camera interface via the Raspberry Pi
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.
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.
bash
Copy code
sudo apt update
sudo apt install python3-picamera
This will install the Python bindings for the Raspberry Pi Camera.
Once the camera is connected and the necessary software is installed, you can start capturing images and
videos.
bash
Copy code
nano capture_image.py
python
Copy code
import time
import picamera
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.
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.
To capture video, you can use the record_video function from the picamera library.
bash
Copy code
nano capture_video.py
python
Copy code
import picamera
import time
# Stop recording
camera.stop_recording()
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.
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
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. 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
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
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
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.
bash
Copy code
python server.py
bash
Copy code
python3 client.py
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.
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.
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:
You can use Mosquitto, which is one of the most popular MQTT brokers. Here’s how to set it up on your 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.
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
On the Raspberry Pi, you will create a simple Python script to publish messages to the MQTT broker running
on the PC.
Open a terminal on the Raspberry Pi and create a new Python file called mqtt_publish.py:
bash
Copy code
nano mqtt_publish.py
python
Copy code
import paho.mqtt.client as mqtt
import time
# Publish a message
client.publish("test/topic", "Hello from Raspberry Pi!")
bash
Copy code
python3 mqtt_publish.py
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.
Open a terminal on the Raspberry Pi and create a new Python file called mqtt_subscribe.py:
bash
Copy code
nano mqtt_subscribe.py
python
Copy code
import paho.mqtt.client as mqtt
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.
bash
Copy code
python3 mqtt_subscribe.py
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.
csharp
Copy code
Message received: Hello from PC!
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.
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).
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.
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.
You’ll use the Paho MQTT client library for Python to connect the Raspberry Pi to the MQTT broker.
bash
Copy code
sudo apt update
sudo apt install python3-pip
pip3 install paho-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.
bash
Copy code
mosquitto_pub -h <Raspberry_Pi_IP> -t "led/control" -m "1"
bash
Copy code
mosquitto_pub -h <Raspberry_Pi_IP> -t "led/control" -m "0"
The Raspberry Pi will listen for messages on the led/control topic and send corresponding commands to the
Arduino.
On the Raspberry Pi, create a Python script to listen to the topic and send commands to the Arduino
over the serial connection.
bash
Copy code
nano mqtt_led_control.py
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
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
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.
bash
Copy code
python3 mqtt_led_control.py
bash
Copy code
mosquitto_pub -h <Raspberry_Pi_IP> -t "led/control" -m "1"
bash
Copy code
mosquitto_pub -h <Raspberry_Pi_IP> -t "led/control" -m "0"
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
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:
AWS:
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.
We’ll use Flask, a lightweight Python web framework, to create a simple HTTP server that will accept images.
bash
Copy code
sudo apt update
sudo apt install python3-pip
pip3 install Flask
2. Create the Flask Server:
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
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.
To start the server, run the following command on your Raspberry Pi:
bash
Copy code
python3 app.py
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
python
Copy code
import time
import picamera
import requests
# Capture an image
image_path = '/home/pi/Desktop/captured_image.jpg'
camera.capture(image_path)
camera.close()
# 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.
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.
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)
bash
Copy code
pip3 install boto3
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
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.
bash
Copy code
pip3 install google-cloud-storage
python
Copy code
from google.cloud import storage
from werkzeug.utils import secure_filename
@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
o Explanation: This code uses google-cloud-storage to upload the file to Google 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.
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.
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
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.
bash
Copy code
mkdir ~/camera_images
python
Copy code
from flask import Flask, send_file
import time
import picamera
import os
app = Flask(__name__)
if __name__ == '__main__':
# Make sure the image folder exists
os.makedirs(image_folder, exist_ok=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.
bash
Copy code
python3 app.py
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.
bash
Copy code
flutter create camera_viewer
cd camera_viewer
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
bash
Copy code
flutter pub get
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());
}
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.
To test the app, connect your phone or use an emulator. Run the app using the following command:
bash
Copy code
flutter run
bash
Copy code
python3 app.py
bash
Copy code
flutter run
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
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.