Remote Switch

In this project, we will learn to use Cloud4RPi’s Switch to control the relay, thereby controlling the relay’s load-LED. You can also change the load of the relay to household appliances, but with safety in mind.

Experimental Procedures

Build the circuit.

../_images/relay1.png

Open the code.

cd ~/cloud4rpi-raspberrypi-python
sudo nano remote_switch.py

Find the line below and fill in the correct device token.

DEVICE_TOKEN = '__YOUR_DEVICE_TOKEN__'

Run the code.

sudo python3 remote_switch.py

Go to Cloud4RPi, add a new Control Panel named project2, and click Add Widget to add a Switch widget.

../_images/relay2.png

Once added, you can use the Switch widget to control the relay.

../_images/relay3.png

Code Explanation

RELAY_PIN = 18

Relay connected to GPIO18 of the T-expansion board.

GPIO.setmode(GPIO.BCM)
GPIO.setup(RELAY_PIN, GPIO.OUT)

Set to BCM nomenclature and set RELAY_PIN to output.

def relay_control(value=None):
    GPIO.output(RELAY_PIN, value)
    return GPIO.input(RELAY_PIN)

This function controls the relay according to the value and returns the current level of the relay.

Note

Since the relay works at high level, the relay closes when the switch state is True and opens when the switch state is False.

variables = {
    'LED On': {
        'type': 'bool',
        'value': False,
        'bind': relay_control
    },
}

By setting the value of the 'value' key, we can set the initial value of the Switch widget, then always read the value of the 'value' key and send the current level of RELAY_PIN (the value returned by the function relay_control()) to Cloud4RPi.