Iot Lab
Iot Lab
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:
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);
}
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.
3. Install PySerial:
PySerial is a Python library for reading and writing data over a serial connection.
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.
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.
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.
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:-