AmbiLamp: Lamp Code
LED Script

The second script we want to write is for controlling the LED. Last lesson, we sent information from the hardware, to the database. Now we want to go the other direction - sending information from the web app (which communicates through the database) to the hardware.

We are still working on the Pi! Make sure you are ssh'd in - this stuff won't work on your laptop.

Create a new file with this starter skeleton.

import requests

# import the RGB and Color libraries

# the address we will make the request to

# construct the RGB LED and Color object

while True:

# make a get request to retrieve the current settings, and extract the JSON from it

# set the color to the lightColor field of the settings object

# set the RGB's color

Challenge: Control LED

Fill in the skeleton. It's a pretty simple script - refer back to the test scripts provided in the libraries folder and the documentation we provided to figure out how to control the LED. It needs to

Get the settings
Set the color to the lightColor field from the current settings
Set the LED to that color

Test that your script works by visiting your web app's home page and changing the color with our color form. You could also change the color with Postman, or even by making a put request to the settings document from the script, but that's less fun - the point is to control the LED from the web app, so do it that way!

The lightColor field you receive from the API is a string. Look at our documentation for the Color library - is there a function that will let you set the color using the string from the settings response?

You may notice some delay between changing the color on the website and seeing it actuate on the lamp. This is because the get request has to establish a connection each time it is called, and that can be slow.

You should now be able to read from your sensors, and see the readings on the web app, as well as control the LED from the web app!