B4R Code Snippet Switch a relay (to On/NC) when it gets dark via an LDR and PIR

SubName: Use this routine to switch a relay.
Description: You can use this basic code to control for example an outdoor high powered light, in my case running at 240V. The PIR (Passive Infrared Sensor) constantly senses movement which is no good during daytime. This board layout and code will only switch power to the relay (thus to a light) once the outside light level drops below a set level (it's getting darker), in my case below 1000. Please note that your resistance level reading may differ to mine.

Note: Yes I could have connected the PIR directly to pin 13, but I personally opted not to do that.

B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'Public variables can be accessed from all modules.

    Public Serial1 As Serial
    Public PIR_D2, Relay_D3, LED_D13, LDR_A0 As Pin
    Public TmrLightLevel As Timer
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    Log("AppStart")

    LDR_A0.Initialize(LDR_A0.A0, LDR_A0.AnalogRead) 'Light Dependent Resistor
    LDR_A0.Mode = 0

    PIR_D2.Initialize(2, PIR_D2.MODE_INPUT_PULLUP) 'Passive Infrared Sensor Pin
    PIR_D2.AddListener("PIRMovementDetected_StateChanged")

    Relay_D3.Initialize(3, Relay_D3.MODE_OUTPUT) 'Relay Trigger Pin
    Relay_D3.DigitalWrite(True)

    LED_D13.Initialize(13, LED_D13.MODE_OUTPUT) 'Built-in LED on pin 13

    TmrLightLevel.Initialize("LightLevel_Tick", 100) 'Temp timer just for viewing current light level
    TmrLightLevel.Enabled = True
End Sub

Sub PIRMovementDetected_StateChanged (State As Boolean)
    If LDR_A0.AnalogRead <= 1000 Then  'LDR Level getting darker, this is just a test level
        Select State
            Case True
                LED_D13.DigitalWrite(True)
                Relay_D3.DigitalWrite(False)
                Log("Movement detected")
            Case False
                LED_D13.DigitalWrite(False)
                Relay_D3.DigitalWrite(True)
                Log("Nothing detected")
        End Select
    End If
End Sub

Sub LightLevel_Tick
    Log(LDR_A0.AnalogRead) 'Test timer just to see the current light level
End Sub

Tags: Relay, PIR, LDR, Arduino, Light, Resistor

PIR LDR Relay_bb.png
 
Last edited:
Top