1 of 78

MODULE 5

2 of 78

Smart Lighting Home Automation System

IoT-based Intelligent Lighting using Django Framework

3 of 78

Overview

  • The Smart Lighting Home Automation System is an IoT-based solution designed using the Django framework. It allows automatic and manual control of home lighting via a web interface, combining sensors, actuators, and RESTful APIs.

4 of 78

What is RESTful API?

  • RESTful API means Representational State Transfer Application Programming Interface.
  • It helps different parts of a system talk to each other using the internet.
  • Works like a messenger between:
  • - Web App (Frontend): where user clicks
  • Auto/Manual or ON/OFF.

- Server (Backend - Django): processes the request.

- IoT Hardware (Raspberry Pi + Sensors): performs

the real action.

  • Communication happens using HTTP (like websites).

5 of 78

RESTful API in Smart Lighting System

Example:

1. User clicks Auto Mode on the web app.

2. App sends request → Django updates mode in the database.

3. Raspberry Pi reads it → checks LDR → turns light ON/OFF.

4. App checks again → gets reply: 'Auto'.

Key URLs:

  • - /home/mode/ → Switch between Auto or Manual.
  • - /home/state/ → Turn Light ON/OFF.

  • Simple meaning: RESTful API is the bridge connecting web app and IoT devices for real-time control.

6 of 78

Understanding LDR (Light Dependent Resistor)

  • LDR stands for Light Dependent Resistor.
  • It is a sensor that detects the brightness of the surrounding light.
  • Working principle:
  • - Bright light → Low resistance → More current flow.
  • - Darkness → High resistance → Less current flow.
  • The Raspberry Pi reads this change and decides when to turn the light ON or OFF.

  • In Auto Mode:
  • - Dark → LDR signals to turn light ON.
  • - Bright → LDR signals to turn light OFF.

Simple meaning: The LDR acts as the 'eyes' of your smart lighting system.

7 of 78

Figure 9.1 – Deployment Design of Home Automation IoT System

This diagram presents the overall architecture of the Smart Lighting Home Automation IoT system. It illustrates how the local Django-based application, REST APIs, database, and IoT hardware components communicate with each other within the local and cloud layers.

  • (See Figure Below)

8 of 78

9 of 78

Overview of the Deployment Design

Figure 9.1 illustrates the deployment architecture of the Smart Lighting Home Automation IoT System. The architecture is organized into two domains: the Local environment and the Cloud environment. The Local environment performs all the real-time data processing, decision-making, and device control operations, while the Cloud environment is an optional extension designed for scalability and remote data analytics. This structure enables modular design, allowing the system to function independently within a home environment and later expand to cloud-based monitoring if required.

10 of 78

Local Layer Description

The Local layer forms the operational core of the smart home automation system. It includes components that directly handle user input, data processing, control logic, and hardware communication. This layer ensures that even without internet connectivity, the system can continue to operate efficiently. All critical operations, such as reading sensor data, controlling light states, and managing automation, occur locally, ensuring low latency and reliable performance for real-time applications.

11 of 78

Application and REST Communication

At the top of the Local layer lies the Application or App, which is a Django-based web interface. It allows the user to monitor the system and control lighting behavior remotely through any web browser. Communication between the App and the backend services is handled using RESTful APIs, which ensure lightweight and efficient data transfer. The REST communication uses standard HTTP methods such as GET and PUT to send or receive information related to system state and mode configuration.

12 of 78

Database Management

The Database is a central component responsible for storing and managing system information. It maintains records of the operational mode (Auto or Manual) and the light’s ON or OFF state. Whenever a user makes a change through the web interface, the data is updated in the database. The Controller Service periodically retrieves data from the database to make informed decisions about system behavior. Thus, the database acts as the synchronization hub that connects the software layer to the physical IoT devices.

13 of 78

Controller Service Functionality

The Controller Service acts as the brain of the system, interpreting data and controlling the devices accordingly. It continuously monitors both user inputs and environmental sensor readings. In Auto mode, the controller uses light sensor data to determine whether to turn the light ON or OFF depending on the ambient brightness. In Manual mode, it simply follows the user’s command as received from the web interface. The Controller Service ensures that automation and manual control coexist without conflict, maintaining system consistency.

14 of 78

Resource and Device Layers

The Resource and Device layers represent the physical part of the system. The Resource layer provides a software abstraction that allows the controller to communicate with various hardware components in a standardized way. The Device layer includes tangible IoT elements such as sensors, relays, and lights. When a command is issued from the controller, the Resource layer converts it into electrical signals that the devices understand. This flow of commands and feedback completes the interaction loop between digital logic and physical hardware.

15 of 78

Monitoring Node Operations

The Monitoring Node serves as the analytical unit of the Local layer. It continuously observes system operations, records data, and performs performance analysis. It helps in detecting anomalies, logging sensor values, and ensuring overall system reliability. The data stored by the monitoring node can later be used to improve system performance, perform predictive analysis, or integrate with higher-level AI-based optimization algorithms.

16 of 78

Cloud Layer Role and Future Integration

The Cloud layer is intentionally depicted as an extension point in the architecture. Although the current implementation functions locally, the cloud can be used for advanced functionalities such as data analytics, remote monitoring, and centralized control. Integrating cloud services would allow users to access their home automation data from anywhere and apply machine learning for intelligent decision-making. This hybrid design ensures that the system remains scalable, flexible, and future-ready.

17 of 78

Summary of Deployment Architecture

In summary, the deployment design represents a well-structured integration of software and hardware components. The Local layer ensures autonomous, real-time control, while the Cloud layer offers long-term scalability. Data flows seamlessly from the user interface to the database, through the controller, and finally to the devices, with feedback maintained by the monitoring node. This layered and modular structure makes the system efficient, reliable, and adaptable to various smart home scenarios.

18 of 78

Figure 9.2 – Mode Service Specification

  • This figure details the Mode Service, a REST API that allows switching between Auto and Manual operational modes. It defines how users or controller services can modify and retrieve the mode value using HTTP requests.

  • (See Figure Below)

19 of 78

20 of 78

Introduction to Mode Service

Following the deployment design of the Smart Home Automation IoT System, Figure 9.2 explains the Mode Service specification. This REST-based service manages the system’s operational behavior by switching between Auto and Manual modes. It allows seamless interaction between the user interface, backend database, and IoT devices, ensuring synchronized control of lighting operations.

21 of 78

Structure of the Mode Service

At the center of the service specification lies the Mode Service component. It is defined as a RESTful web service that communicates through HTTP requests. This service provides an organized way to read and update the system’s mode configuration, maintaining consistent data exchange between the Django web app and controller logic.

22 of 78

Input Specification

The Input component, labeled ‘Set Mode: Auto/Manual’, represents user commands sent through the web interface. When a user changes the operational mode, an HTTP PUT request is generated. This request is sent to the Mode Service endpoint, where the database is updated with the new mode value. The ‘has Input’ relation indicates that the service actively receives mode-setting data from users or controllers.

23 of 78

Output Specification

The Output component, labeled ‘Current Mode: Auto/Manual’, represents the system’s feedback mechanism. When a GET request is received, the Mode Service fetches the current operational mode from the database and returns it to the user interface. This ensures transparency, allowing users to confirm whether the system is functioning in Auto or Manual mode.

24 of 78

Service Endpoint Definition

The Endpoint shown in the diagram defines the communication path for the Mode Service. It specifies the URL ‘/home/mode/’ and uses the HTTP protocol for communication. This endpoint acts as a bridge between the client-side web app and the backend service, enabling both local and remote access through Django’s REST framework.

25 of 78

Functional Role of the Mode Service

The Mode Service governs how the home automation system behaves under different conditions. In Auto mode, the controller autonomously manages light operation using sensor inputs. In Manual mode, user commands take priority, overriding automation. This service ensures dynamic adaptability, allowing users to maintain full control while enabling automation when required.

26 of 78

Integration and Summary

The Mode Service works alongside the State Service and Controller Service to provide a complete automation framework. While the Mode Service defines how the system should operate, the State Service manages what the system is currently doing. Both interact through the Controller Service, ensuring synchronized actions. Figure 9.2 thus demonstrates the modular and flexible design of the home automation IoT system’s service architecture.

27 of 78

Figure 9.3 – State Service Specification

  • This figure defines the State Service responsible for controlling the light’s ON/OFF condition. It specifies the REST API endpoints, HTTP methods, and data flow for managing the real-time state of the light through Django’s backend.

  • (See Figure Below)

28 of 78

29 of 78

Introduction to State Service Specification

Figure 9.3 illustrates the State Service, an integral RESTful component of the Smart Home Automation IoT System. While the Mode Service governs whether the system operates in Auto or Manual mode, the State Service directly manages the light’s ON/OFF operation. It ensures seamless synchronization between the web interface, backend database, and IoT devices by providing REST API endpoints for state management.

30 of 78

Purpose of the State Service

  • The State Service is designed to handle all operations related to controlling the light’s state. It processes both user-generated and automated requests, translating them into actionable commands for the hardware layer. Its main objective is to ensure that any request to turn the light ON or OFF is properly recorded, executed, and reflected across all system components.

31 of 78

Service Structure

  • At the core of the figure lies the Service block, labeled ‘Name: State, Type: REST’. This indicates that the service follows RESTful architectural principles, using HTTP methods such as GET and PUT for communication. This structure enables efficient, stateless interactions between the Django backend and the web interface or controller, allowing real-time responsiveness.

32 of 78

Input Specification

  • The Input block, labeled ‘State: On/Off’, defines the input parameters accepted by the service. When a user toggles the light via the web interface or when the controller detects the need for illumination, an HTTP PUT request is sent to the service. This request updates the light state in the database, enabling the system to maintain accurate and current state information.

33 of 78

Output Specification

  • The Output block, labeled ‘State: On/Off’, represents the feedback mechanism of the service. When the system or user sends a GET request, the service retrieves the current light state from the database and returns it. This ensures that the displayed status on the user interface matches the physical state of the light, maintaining real-time synchronization.

34 of 78

Service Endpoint Definition

  • The Endpoint block in the diagram defines how the service can be accessed. The endpoint URL is ‘/home/state/’, and communication occurs using the HTTP protocol. This endpoint provides a unified access point for the controller and user interface, allowing consistent control operations across different platforms. Using Django REST Framework, this endpoint maintains secure and structured data communication.

35 of 78

Functional Role in the Automation System

  • The State Service forms the control foundation of the lighting system. In Auto mode, the controller makes real-time decisions based on environmental sensor inputs and sends corresponding state-change requests. In Manual mode, the user directly interacts with the State Service through the web interface. This dual-functionality ensures both automation intelligence and user control coexist effectively.

36 of 78

Integration and Summary

  • The State Service works in conjunction with the Mode and Controller Services to form a cohesive automation framework. The Mode Service determines operational behavior, while the State Service manages light status changes. Both are orchestrated by the Controller Service, ensuring synchronization across software and hardware layers. Overall, Figure 9.3 demonstrates how RESTful design principles enable smooth communication and reliable operation within the smart home automation system.

37 of 78

Figure 9.4 – Web Application Interface

  • This screenshot shows the web interface through which users interact with the system. The interface includes switches for toggling Auto Mode and Light control, allowing both remote and local management of the system.

  • (See Figure Below)

38 of 78

39 of 78

Figure 9.5 – Hardware Schematic Diagram

  • This schematic illustrates the hardware setup, showing the interconnection of the Raspberry Pi controller, light sensor, and relay switch. It depicts how physical components are integrated with the digital logic of the Django system.

  • (See Figure Below)

40 of 78

41 of 78

Introduction to Figure 9.5 – Schematic Diagram

Figure 9.5 illustrates the schematic diagram of the Smart Home Automation IoT System, showing how the controller device, sensor, and actuator are interconnected. This figure presents the physical hardware implementation that supports the automation cycle of sensing, processing, and action within the smart lighting framework.

42 of 78

Hardware Overview

The system is built around a Raspberry Pi board, which serves as the primary processing unit. The Raspberry Pi manages sensor inputs, user commands, and actuator control signals through its GPIO pins. It communicates with the Django-based web application to synchronize lighting operations with RESTful services over a local or remote network connection.

43 of 78

Sensor Integration

The schematic includes a light-dependent resistor (LDR) sensor connected to the Raspberry Pi via an analog-to-digital converter (ADC). The LDR measures the ambient light intensity in the environment. In Auto Mode, when the light level falls below a certain threshold, the Raspberry Pi interprets this input and triggers the relay to turn ON the light. When sufficient light is detected, the system turns it OFF automatically.

44 of 78

Actuator and Relay Circuit

The actuator is represented by a relay module that acts as a switch between the Raspberry Pi and the lighting appliance. Since the Raspberry Pi operates at low voltage, the relay safely manages high-voltage circuits. The relay receives digital signals from the Raspberry Pi and toggles the light ON or OFF, enabling the controller to perform real-world actions based on logic or user input.

45 of 78

Breadboard Wiring and Circuit Design

The breadboard in the schematic diagram demonstrates how all components are physically connected without soldering. Power and ground lines from the Raspberry Pi supply voltage to the sensor and relay modules. Signal connections link the GPIO pins to the ADC and the relay inputs, allowing two-way communication between hardware and software layers. This modular setup enables easy reconfiguration and future expansion.

46 of 78

Operational Flow

  • The Raspberry Pi continuously reads sensor data and determines the required action based on the operational mode. In Auto Mode, the decision-making is sensor-driven, while in Manual Mode, it follows user commands sent from the web application. These commands are processed locally, and GPIO pins are updated to reflect the desired state of the lighting device.

47 of 78

Hardware–Software Integration

  • The schematic highlights how the physical and software components communicate through REST APIs. When users interact with the Django web dashboard, HTTP requests are sent to the Raspberry Pi, which executes the corresponding actions. This integration ensures that local hardware operations and remote web interactions remain synchronized, creating a cohesive and intelligent system.

48 of 78

Summary of the Schematic Diagram

  • Figure 9.5 depicts the practical realization of the smart lighting automation system. The Raspberry Pi acts as the brain, the LDR sensor provides environmental input, and the relay controls the lighting output. The modular design using a breadboard allows flexibility, scalability, and cost efficiency. This schematic serves as the bridge between theoretical design and real-world IoT implementation, completing the automation framework.

49 of 78

Figure 9.6 – Controller Service

  • This figure represents the Controller Service, the central logic engine of the automation system. It periodically checks the mode, reads sensor data, and updates the light state accordingly to maintain intelligent control.

  • (See Figure Below)

50 of 78

51 of 78

Introduction to Figure 9.6 – Controller Service

  • Figure 9.6 illustrates the Controller Service, which acts as the central decision-making unit of the Smart Home Automation IoT System. This service processes inputs from other modules, executes logic, and updates the lighting system in real-time. It works alongside the Mode and State services to ensure seamless operation between the web interface, database, and IoT hardware components.

52 of 78

Service Description

  • The Controller Service, labeled 'Name: Controller, Type: Native', represents a native process running on the Raspberry Pi. Unlike the REST-based Mode and State services, it operates locally to ensure low-latency decision-making. It is responsible for maintaining the automation loop—receiving data from sensors, applying logic, and controlling actuators without user intervention.

53 of 78

Input Specification

  • The Input block defines the parameters 'Mode: Auto/Manual' and 'State: On/Off'. These inputs determine how the system behaves at any given time. In Auto Mode, the Controller uses sensor data to make intelligent decisions. In Manual Mode, it follows user commands received via the web interface, ensuring flexibility between automation and direct control.

54 of 78

Schedule Specification

  • The Schedule block specifies the time interval at which the Controller Service operates. In this design, the interval is set to 'Every 5 seconds', meaning that the service executes its decision-making loop repeatedly at this rate. This regular execution schedule ensures that the system constantly adapts to environmental changes while balancing computational efficiency.

55 of 78

Output Specification

  • The Output block labeled 'State: On/Off' represents the result of the Controller's decision-making process. After evaluating the mode and environmental data, the service determines whether the light should be turned ON or OFF. This state update is then communicated to the actuator (relay) and synchronized with the database via the State Service.

56 of 78

Endpoint Specification

  • The Endpoint block specifies how the Controller interacts with other components through the '/home/' URL using the HTTP protocol. This connection allows it to exchange data with the Mode and State services. While primarily operating as a native process, this HTTP interface ensures interoperability and maintains real-time updates within the Django framework.

57 of 78

Functional Operation

  • The Controller Service continuously receives inputs, evaluates conditions, and produces outputs. For example, if the Mode is 'Auto' and the sensor detects low light, the Controller turns the light ON through the State Service. It repeats this evaluation every five seconds, ensuring real-time adaptability. In Manual Mode, it processes user-triggered actions instead of sensor-driven automation.

58 of 78

Integration and Summary

  • The Controller Service forms the core of the automation logic by integrating the Mode and State services into a unified system. It interprets the operational mode, evaluates system states, and issues control commands at scheduled intervals. By combining intelligent logic, REST-based communication, and periodic scheduling, the Controller Service enables reliable, autonomous, and efficient operation of the Smart Home Automation IoT framework.

59 of 78

Smart Lighting Home Automation — Code

Django REST APIs + Raspberry Pi Controller

60 of 78

models.py — Code

  • from django.db import models
  • class Home(models.Model):� mode = models.CharField(max_length=10)� state = models.CharField(max_length=10)
  • def __str__(self):� return f"Mode:{self.mode} State:{self.state}"

61 of 78

models.py

The Home model defines a minimal single-table representation used to coordinate the global operational mode and the instantaneous light state for the entire smart lighting system. The 'mode' attribute is a short character field intended to store values such as 'Auto' or 'Manual' which dictate whether the controller acts autonomously based on sensor inputs or defers to remote user commands. The 'state' attribute similarly holds textual markers such as 'On' or 'Off' to capture the present physical condition of the lighting actuator. Choosing a single row model simplifies synchronization across system actors the web front-end, the Raspberry Pi controller, and any monitoring nodes by providing a shared authoritative source. In deployment, ensure that exactly one Home instance exists; use get_or_create during initialization and include model constraints or explicit validation to restrict accepted values. This approach leverages Django's ORM for safe transactional updates, readable queries, and avoids direct SQL, thus reducing the risk of injection and improving maintainability.

62 of 78

serializers.py — Code

  • from rest_framework import serializers�from .models import Home
  • class HomeSerializer(serializers.ModelSerializer):� class Meta:� model = Home� fields = ['mode','state']

63 of 78

serializers.py

The HomeSerializer is a Django REST framework construct that provides bi-directional conversion between Django model instances and JSON payloads consumed by clients. By declaring a ModelSerializer tied to the Home model and explicitly enumerating the 'mode' and 'state' fields, the API benefits from automatic field generation, input validation, and a single place to apply transformation rules. When the endpoint returns data, this serializer produces JSON such as {'mode':'Auto','state':'Off'}; when receiving PUT requests, it parses the incoming JSON, validates types and required fields, and prepares a cleaned Python object suitable for assignment and persistence. Using serializers is superior to manual JSON handling because it centralizes validation logic, supports custom validators, and integrates smoothly with DRF's view classes and error reporting. For stricter behavior, add choice validators to enforce allowed values and descriptive error messages for invalid inputs.

64 of 78

views.py — Mode API (Code)

  • from rest_framework.decorators import api_view�from rest_framework.response import Response�from .models import Home�from .serializers import HomeSerializer
  • @api_view(['GET','PUT'])�def mode(request):� home, _ = Home.objects.get_or_create(pk=1, defaults={'mode':'Auto','state':'Off'})� if request.method == 'GET':� serializer = HomeSerializer(home)� return Response(serializer.data)� # PUT� serializer = HomeSerializer(home, data=request.data, partial=True)� serializer.is_valid(raise_exception=True)� serializer.save()� return Response({'message':'Mode updated', 'mode':serializer.data['mode']})

65 of 78

views.py — Mode API (Paragraph Explanation)

This function-based view implements a concise REST endpoint responsible for reading and modifying the operational mode of the system. On entry, the code uses get_or_create to guarantee the presence of a canonical Home row; this defensive pattern prevents AttributeError exceptions when the database is empty and establishes sensible defaults. For GET requests, the view serializes the Home instance into JSON using the HomeSerializer and returns the structured representation to requesting clients such as the web dashboard or IoT controller. For PUT requests, the endpoint constructs a serializer instance with the existing model and the incoming request data, enabling field-level validation and partial updates. Calling is_valid with raise_exception ensures that invalid payloads produce clear HTTP 400 responses with useful diagnostics rather than silent failures. Finally, save persists allowed changes atomically. This implementation balances robustness and clarity by centralizing validation in serializers and preserving simple HTTP semantics for consumers.

66 of 78

views.py — State API (Code)

  • from rest_framework.decorators import api_view�from rest_framework.response import Response�from .models import Home�from .serializers import HomeSerializer
  • @api_view(['GET','PUT'])�def state(request):� home, _ = Home.objects.get_or_create(pk=1, defaults={'mode':'Auto','state':'Off'})� if request.method == 'GET':� serializer = HomeSerializer(home)� return Response(serializer.data)� serializer = HomeSerializer(home, data=request.data, partial=True)� serializer.is_valid(raise_exception=True)� serializer.save()� return Response({'message':'State updated', 'state':serializer.data['state']})

67 of 78

views.py — State API

  • The State API mirrors the Mode API but focuses on the instantaneous actuator condition. It likewise ensures the canonical Home instance exists using get_or_create, returning the entire model's serialized state for clarity. On PUT requests the same validated serializer path is followed, permitting the client (either the front-end in Manual mode or the Raspberry Pi in Auto mode) to update the 'state' attribute. Keeping separate endpoints for mode and state clarifies responsibilities: the Mode API determines behavioral intent (automation versus manual control), while the State API represents the present action to be applied to the hardware. This separation simplifies access control (for example, granting write access to the operator UI on the State endpoint while restricting Mode changes) and reduces coupling, which eases testing and future extension.

68 of 78

urls.py — Code

  • from django.urls import path�from .views import mode, state
  • urlpatterns = [� path('home/mode/', mode, name='home-mode'),� path('home/state/', state, name='home-state'),�]

69 of 78

urls.py

The URL configuration maps clear, semantic HTTP endpoints to the view functions implementing the API. Using path strings such as 'home/mode/' and 'home/state/' produces human-readable routes which are easy to recall when wiring the front-end JavaScript or the Raspberry Pi controller. Naming routes (name='home-mode') allows reverse URL lookups within Django templates and improves testability. In larger systems, these patterns should be included under an API namespace and versioned (for example '/api/v1/home/mode/') to support backward-compatible changes. Additionally, route protection via DRF authentication classes and permission decorators should be applied at this level to prevent unauthorized writes when the service is exposed beyond a trusted local network.

70 of 78

frontend.js — AJAX PUT Mode (Code)

  • function setMode(modeValue) {� fetch('/home/mode/', {� method: 'PUT',� headers: { 'Content-Type': 'application/json' },� body: JSON.stringify({ mode: modeValue })� }).then(r => r.json()).then(data => console.log(data)).catch(e => console.error(e));�}

71 of 78

frontend.js

The JavaScript routine demonstrates a minimal interaction pattern from the browser to the REST endpoint. By performing a fetch PUT request with a JSON body containing the mode field, the front-end updates server-side state that in turn will be observed by the IoT controller. The function includes basic promise chaining to parse the JSON response and to log outcomes for debugging; in production replace console logs with user-facing notifications and error handling that updates UI state. Consider CSRF considerations for same-origin deployments: use DRF's token authentication or include CSRF headers when appropriate. Also, apply UI locking or optimistic updates to prevent duplicate requests and ensure the user receives immediate feedback while the network call completes.

72 of 78

controller.py — Raspberry Pi Loop (Code)

  • import time�import requests�from gpiozero import OutputDevice�from some_adc_library import ADC
  • relay = OutputDevice(17)�adc = ADC()�THRESHOLD = 300
  • while True:� try:� r = requests.get('http://<server>/home/mode/')� mode = r.json().get('mode')� if mode == 'Auto':� val = adc.read(channel=0)� if val < THRESHOLD:� requests.put('http://<server>/home/state/', json={'state':'On'})� relay.on()�

73 of 78

else:� requests.put('http://<server>/home/state/', json={'state':'Off'})� relay.off()� else:� s = requests.get('http://<server>/home/state/').json().get('state')� if s == 'On':� relay.on()� else:� relay.off()� except Exception as e:� # log and continue� print('Controller error', e)� time.sleep(5)

74 of 78

controller.py

The Raspberry Pi controller script is the operational bridge between cloud-hosted application state and the on-site hardware. Running as a continuously executing loop it periodically polls the Mode endpoint to discover whether it should act autonomously. In Auto mode the controller samples the analog LDR value via an ADC and compares it to a calibrated threshold; when the measured illumination falls below the threshold it signals the State endpoint and switches the relay on to energize the light. In Manual mode it instead fetches the authoritative 'state' from the server and drives the relay accordingly, allowing remote operator commands to take precedence. The code includes basic exception handling to ensure transient network or hardware issues do not halt execution. For reliability in production, add robust retry logic, exponential backoff, persisting local state to survive restarts, and consider replacing polling with a push-based protocol such as MQTT to reduce latency and network traffic.

75 of 78

adc_and_ldr — Code (Wiring/Read)

  • # wiring: LDR forms voltage divider read by MCP3008 ADC�# example read�value = adc.read(0) # returns 0-1023
  • if value < THRESHOLD:� # it's dark� pass

76 of 78

adc_and_ldr

Reading an LDR requires an analog-to-digital converter because Raspberry Pi's GPIO pins are digital only. The common pattern is to place the LDR in a voltage divider with a fixed resistor and connect the midpoint to an ADC such as the MCP3008, which communicates via SPI. The ADC returns a numeric range (for example 0-1023) proportional to the voltage and therefore to the ambient light intensity. The controller should compute a calibrated threshold empirically by sampling the sensor at representative light conditions and possibly applying smoothing via moving average to suppress noise and transient fluctuations from flicker or shadows. Storing threshold values in configuration rather than using hardcoded constants improves maintainability and allows per-deployment tuning. In environments where light gradients matter, consider using multiple sensors and simple aggregation to reduce false triggers.

77 of 78

relay_safety — Code (Notes)

  • # use a relay module rated for your load�# use opto-isolated module and flyback diode for mechanical relays�# always keep mains wiring isolated from low-voltage circuitry

78 of 78

relay_safety

Switching mains loads introduces real safety obligations. Always select a relay or contactor with voltage and current ratings exceeding anticipated loads and incorporate protective components such as snubber circuits, flyback diodes, and opto-isolation where appropriate. Use a transistor driver or a certified relay module to prevent direct current draw from GPIO pins; many relay boards include the necessary driver circuitry and optical isolation. Ensure that AC mains wiring is installed by a qualified electrician, that connections are insulated and strain-relieved, and that the low-voltage side is physically separated from mains conductors. Consider adding fuses, residual current devices (RCD), and surge protection for a production-grade installation. Document safety steps clearly in the project report and include prominent warnings in any distributed code or lab instructions.