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

Iot Lab

This document provides steps to connect LED lights to an Arduino board and control the LEDs remotely via messages sent over MQTT. The key steps are: 1. Connect LED lights to digital pins on an Arduino board. 2. Upload code to the Arduino to toggle the LEDs when it receives messages via its serial port. 3. On a Raspberry Pi, write a Python script to subscribe to an MQTT topic. The script will receive messages and send them to the Arduino serial port to control the LEDs remotely. 4. Set up an MQTT broker on a PC to publish messages to the topic to allow remote control of the LEDs via the MQTT network.

Uploaded by

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

Iot Lab

This document provides steps to connect LED lights to an Arduino board and control the LEDs remotely via messages sent over MQTT. The key steps are: 1. Connect LED lights to digital pins on an Arduino board. 2. Upload code to the Arduino to toggle the LEDs when it receives messages via its serial port. 3. On a Raspberry Pi, write a Python script to subscribe to an MQTT topic. The script will receive messages and send them to the Arduino serial port to control the LEDs remotely. 4. Set up an MQTT broker on a PC to publish messages to the topic to allow remote control of the LEDs via the MQTT network.

Uploaded by

uditgautam0101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Experiment :- 01

AIM:- Setting up the Arduino Development Environment, connecting analog sensors to an Arduino
Boarding and reading analog sensor data.
Setting up the Arduino development environment and connecting analog sensors to an Arduino board is a
common task for electronics and DIY enthusiasts. Here's a step-by-step guide to help you get started:

Step 1: Install Arduino IDE


Download Arduino IDE:
Visit the Arduino Software page.
Download the latest version of the Arduino IDE for your operating system (Windows, macOS, or Linux).

Step 2: Connect Arduino Board


Connect Arduino Board:
Connect your Arduino board to your computer using a USB cable.

Install Drivers (if needed):


In some cases, you might need to install drivers for your specific Arduino board. Check the manufacturer's
website for instructions.

Step 3: Open Arduino IDE


Launch Arduino IDE:
Open the Arduino IDE on your computer.
Select Board and Port:
Go to "Tools" > "Board" and select your Arduino board model (e.g., Arduino Uno, Arduino Nano).
Go to "Tools" > "Port" and select the port that corresponds to your connected Arduino board.

Step 4: Write and Upload a Simple Sketch


Open a New Sketch:
Click on "File" > "New" to open a new sketch.

Write a Simple Sketch:


Write a basic Arduino sketch to read analog sensor data. Here's an example for reading from an analog
sensor connected to analog pin A0:
const int analogPin = A0;
int sensorValue = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(analogPin);
Serial.println(sensorValue);
delay(1000);
}

Step 5: Connect Analog Sensor


Connect Analog Sensor:
Connect your analog sensor to one of the analog pins on the Arduino board.
Make sure to connect the sensor's power (VCC), ground (GND), and signal/data pin to the appropriate pins
on the Arduino.

Step 6: Monitor Sensor Data


Open Serial Monitor:
Go to "Tools" > "Serial Monitor" to open the Serial Monitor in the Arduino IDE.

View Sensor Data:


The sensor data should be displayed in the Serial Monitor in real-time.
Experiment :- 02
AIM :- Digital Input and Output reading using and Arduino board and Arduino Development Environment.
Reading Digital Input:
Step 1: Connect a Digital Input Device (Push Button):
Connect Push Button:
Connect a push button to one of the digital pins on the Arduino board. Connect one leg of the button to the
digital pin and the other leg to ground. You may also use a resistor (e.g., 10k ohms) as a pull-up or pull-
down resistor depending on your button's configuration.

Adjust Code:
Open the Arduino IDE.
Write a simple sketch to read the state of the button.
const int buttonPin = 2;
int buttonState = 0;
void setup() {
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(buttonPin);
Serial.println(buttonState);
delay(1000);
}

Controlling Digital Output:

Step 2: Connect a Digital Output Device (e.g., LED):


Connect LED:
Connect an LED to another digital pin on the Arduino. Connect the LED's longer leg (anode) to the digital
pin and the shorter leg (cathode) to a current-limiting resistor, then connect the other end of the resistor to
ground.
Adjust Code:
Modify the code to control the LED based on the button state.
const int buttonPin = 2;
const int ledPin = 13;
int buttonState = 0;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
Serial.println(buttonState);
delay(1000);
}

Upload the Sketch:


Upload the modified sketch to your Arduino board.

Observe LED Control:


Press and release the button to observe how the LED responds based on the button state.
Experiment :- 03
AIM :- Integrate an Arduino Board to a Raspberry Pi computer and send sensor data from Arduino to the
R Pi.

Hardware Setup:
Connect Arduino to Raspberry Pi:
Connect the Arduino to the Raspberry Pi using a USB cable. This allows the Raspberry Pi to communicate
with the Arduino over the USB serial connection.

Power Supply:
Power the Arduino using an external power source or the Raspberry Pi's USB ports.

Connect Sensors:
Connect your analog or digital sensors to the Arduino. Follow the wiring instructions for each sensor.

Software Setup:
Arduino Side:
Upload Sensor Reading Sketch:
Write an Arduino sketch to read sensor data and send it over the serial port
const int sensorPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
delay(1000);
}
Write Python Script:
Write a Python script to read data from the Arduino over the serial port.
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 9600)
try:
while True:
if ser.in_waiting > 0:
sensor_data = ser.readline().decode('utf-8').strip()
print("Sensor Data:", sensor_data)
time.sleep(1)
except KeyboardInterrupt:
ser.close()

Data Processing:
Modify the Python script to process the sensor data according to your application's requirements.
Experiment :- 04
AIM :- Setup Python on the R Pi and run sample R Pi programs on the R Pi. Read the data from Arduino
using Python language.

To read data from Arduino using Python on a Raspberry Pi


1. Install Python on Raspberry Pi:
Most Raspberry Pi distributions come with Python preinstalled. However.

2. Connect Arduino to Raspberry Pi:


Connect your Arduino to the Raspberry Pi using a USB cable, and make sure the Arduino is powered.

3. Install PySerial:
PySerial is a Python library for reading and writing data over a serial connection.

4. Write Python Script to Read Data from Arduino:


Create a Python script that reads data from the Arduino.
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 9600)
try:
while True:
if ser.in_waiting > 0:
sensor_data = ser.readline().decode('utf-8').strip()
sensor_value = int(sensor_data)
print("Sensor Data:", sensor_value)
threshold = 700
if sensor_value > threshold:
print("Threshold Exceeded!")
time.sleep(1)
except KeyboardInterrupt:
ser.close()
Output :-
Experiment :- 05
AIM:- Connect a R Pi Camera module to the Raspberry Pi and using Python programming capture still
images and video.

Capture Still Images:


from picamera import PiCamera
import time
camera = PiCamera()
image_name = "captured_image.jpg"
camera.capture(image_name)
time.sleep(1)
camera.close()
print(f"Image captured and saved as {image_name}")

Capture Video:
from picamera import PiCamera
import time
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 30
video_duration = 10 # Set the duration of the video in seconds
video_name = "captured_video.h264"
camera.start_recording(video_name)
camera.wait_recording(video_duration)
camera.stop_recording()
camera.close()
print(f"Video captured and saved as {video_name}")

Output:-
Experiment :- 06
AIM :- Set up TCP/IP socket server on a PC. Send a message from the R Pi to the PC using socket
communication.

Set Up TCP/IP Socket Server on PC:


import socket
HOST = '0.0.0.0'
PORT = 12345
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(1)
print(f"Server listening on {HOST}:{PORT}")
client_socket, client_address = server_socket.accept()
print(f"Connection established with {client_address}")
data = client_socket.recv(1024).decode('utf-8')
print(f"Received data: {data}")
client_socket.close()
server_socket.close()

Send Message from Raspberry Pi to PC:


import socket
SERVER_HOST = 'PC_IP_ADDRESS'
SERVER_PORT = 12345
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((SERVER_HOST, SERVER_PORT))
print(f"Connected to {SERVER_HOST}:{SERVER_PORT}")
message = "Hello from Raspberry Pi!"
client_socket.send(message.encode('utf-8'))
print(f"Message sent: {message}")
client_socket.close()
Output:-
Experiment :- 07
AIM:- Set up a MQTT broker on the PC. Send data from R Pi to PC using MQTT protocol. Receive data
from PC to R Pi using MQTT protocol.

Send Data from Raspberry Pi to PC:


import time
import random
import paho.mqtt.client as mqtt
broker_address = "PC_IP_ADDRESS"
port = 1883
topic = "sensor_data"
client = mqtt.Client()
client.connect(broker_address, port, 60)
try:
while True:
sensor_data = random.randint(1, 100)
client.publish(topic, f"Sensor Data: {sensor_data}")
print(f"Published: Sensor Data: {sensor_data}")
time.sleep(5)
except KeyboardInterrupt:
client.disconnect()

Receive Data from PC to Raspberry Pi:


import paho.mqtt.client as mqtt
broker_address = "localhost"
port = 1883
topic = "sensor_data"
def on_message(client, userdata, msg):
print(f"Received: {msg.payload.decode()}")
client = mqtt.Client()
client.on_message = on_message
client.connect(broker_address, port, 60)
client.subscribe(topic)
client.loop_forever()

Output:-
Experiment :- 08
AIM:- Connect LED lights to an Arduino. Connect the Arduino to the R Pi. Send Message from PC to R Pi
via MQTT protocol. On receipt of the message, toggle the LED lights on the Arduino.

To achieve the described setup, we need the following components:


Arduino board
LED lights
Raspberry Pi (R Pi)
PC
MQTT broker (such as Mosquitto)
Arduino Setup:
Connect the LED to one of the digital pins on the Arduino.
Connect the Arduino to your PC and upload a simple Arduino sketch to toggle the LED when it receives a
message through the serial port.

Python script to subscribe to the MQTT topic and send the messages to the Arduino via its serial
port:
import paho.mqtt.client as mqtt
import serial
import time
arduino_port = "/dev/ttyACM0"
mqtt_broker = "YOUR_MQTT_BROKER_IP"
mqtt_topic = "led_control"
ser = serial.Serial(arduino_port, 9600, timeout=1)
def on_connect(client, userdata, flags, rc):
print("Connected to MQTT broker with result code "+str(rc))
client.subscribe(mqtt_topic)
def on_message(client, userdata, msg):
message = msg.payload.decode('utf-8')
print(f"Received message: {message}")
ser.write(message.encode())
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(mqtt_broker, 1883, 60)
client.loop_start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
ser.close()
client.disconnect()
print("Disconnected from MQTT broker and Arduino.")

With this setup, when we send an MQTT message from your PC to the Raspberry Pi, the Python script on
the Raspberry Pi will forward the message to the Arduino, which will then toggle the LED based on the
received message.
Experiment :- 09
AIM:- Set up an account in a cloud service (such as Google / AWS or Azure). Set up a simple Http server
using a language of your choice. Push the image captured from the R Pi camera to this web service. On
receiving the image, store the image in a database or file.

AWS Setup:
Create an AWS Account:
Go to the AWS website and create an account.

Create an S3 Bucket:
Go to the AWS S3 Console.
Create a new bucket to store the images.

Get AWS Access Key and Secret Access Key:


In the AWS Console, go to the IAM dashboard.
Create a new user with programmatic access and attach the AmazonS3FullAccess policy.
Note down the Access Key ID and Secret Access Key.

Python HTTP Server Setup:


1. Install Flask
2. Write a Simple Flask Server
3. Run the Flask Server
Raspberry Pi Camera Setup:
1. Install Required Libraries
2. Capture and Upload Image

MongoDB Setup:
1. Install MongoDB
2. Install pymongo Library
3. Update Flask Server to Store Image in MongoDB.
Experiment :- 10
AIM:- Develop a mobile application to view the images captured by the R Pi camera.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Image Viewer',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<ImageInfo> imageList = [];
@override
void initState() {
super.initState();
fetchImageList(); }
Future<void> fetchImageList() async {
final response = await http.get('http://YOUR_FLASK_SERVER_IP:5000/images');
if (response.statusCode == 200) {
List<dynamic> data = jsonDecode(response.body);
setState(() {
imageList = data.map((item) => ImageInfo.fromJson(item)).toList();
});
} else {
throw Exception('Failed to load image list');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Viewer'),
),
body: ListView.builder(
itemCount: imageList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(imageList[index].filename),
subtitle: Image.network(imageList[index].url),
);
},
),
);
}
}
class ImageInfo {
final String filename;
final String url;
ImageInfo({required this.filename, required this.url});
factory ImageInfo.fromJson(Map<String, dynamic> json) {
return ImageInfo(
filename: json['filename'],
url: json['url'],
);
}
}

Output:-

You might also like