philips hue api raspberry pi python

Control Philips Hue Lights with Raspberry Pi: Ultimate Guide

The Raspberry Pi is a great tool for many home projects, and one project I tested early on in my Raspberry Pi journey was controlling the lights in my home. Want to try it? Here’s how.

Most smart lights (like Philips Hue) come with a master device that is accessible through an API (the bridge). The API can be used with Python, allowing a Raspberry Pi to be the brain of the home system, managing the lights with more advanced scenarios than the default.

Sure, you can do most things from your phone like a random user, but today we will challenge you a bit to do it with code instead :-).

If you’re looking to quickly progress on Raspberry Pi, you can check out my e-book here. It’s a 30-day challenge where you learn one new thing every day until you become a Raspberry Pi expert. The first third of the book teaches you the basics, but the following chapters include projects you can try on your own.

Want the best experience? Become a premium member for ad-free browsing, access exclusive content, and ask questions in our private forums. Your membership helps support the site!

Introducing Philips Hue

Philips is a well-known Dutch company that is a leader in many areas, including home appliances, technology, and healthcare products.

It’s a company driven by innovation. It was the first to sell audio cassettes, CD and Blu-ray.
They are pioneers in other products, such as the Ambilight technology on TV (that you can simulate using Hyperion on Raspberry Pi).

But the main products that interest us today are the smart lights they created in the Philips Hue collection.

The Philips Hue collection

The Philips Hue collection includes all Philips smart lights.
The concept includes bulbs, a bridge, and an app to manage the lights.

Philips hue collection
  • The bridge is the router between lights and your smartphone app.
    It needs access to your network (RJ45), and if possible to an Internet connection.
    The configuration is easy if you use a DHCP server on your network.
  • Lights connect the bridge automatically in wireless.
    As soon as you switch them on, they are available on the app. No configuration is needed.
  • And the Hue app is available on your smartphone to manage all of this.
    You can switch lights on and off, change colors, and create routines.

What they’re not selling in the commercial ads is the API. There is a great API on the bridge that you can use to do whatever you want. And that’s what I’m going to show you in this post.

Minimum requirements

If you don’t have a Philips Hue pack at home yet, or colored bulbs, several models and packs are available on the market. From the basic on/off white light to bulbs where you can change the color.

Here are some packs I recommend:

My brother gave me the first two packs for my birthday years ago, and I’ve been using them ever since. It’s a bit expensive (if not gifted!), but worth it. All the lights are still working after 10 years of use, and I’m happy with them.

All the packages are compatible with Alexa and some include an Echo Dot.
For starter kits, you can choose how many bulbs you want.

Step 1: Raspberry Pi & lights setup

Before writing your first line of code, you must prepare some things.
Let’s make sure everything is ready.

Raspberry installation

We’ll be controlling everything from a Raspberry Pi running Raspberry Pi OS and writing our scripts in Python. So you need to make sure you’ve followed all of these steps:

  • Grab any Raspberry Pi model (latest recommendations here).
    It’s a very lightweight project, so even an old model or a Pi Zero will do (I use one myself).
  • Install Raspberry Pi OS.
    You can choose any version, I’ll do the tutorial with the Lite version.
  • Connect to the network (or configure the Wi-Fi) and ensure you have Internet access.
  • Enable SSH so you can follow the next instructions on your computer and copy/paste the commands (SSH guide here if needed).
  • Update your system:
    sudo apt update
    sudo apt upgrade
  • Choose a code editor.
    On the Desktop version, you already have Thonny and Geany installed.
    On the Lite version, nano or vim will be enough.
    You can also create scripts on your computer and transfer them to the Raspberry Pi afterwards (with WinSCP for example).
  • Make sure PIP is installed:
    sudo apt install python3-pip

That’s all you need for the moment.

Are you a bit lost in the Linux command line? Check this article first for the most important commands to remember and a free downloadable cheat sheet so you can have the commands at your fingertips.

Hue bridge

On the Philips Hue side, the first step is to find the Hue bridge IP address (the little router that comes with your pack).

If you have access to your Internet router or DHCP server interface, you may find it listed on it.

If not, you can run a scan on your network.
On Windows, I generally use Advanced IP Scanner for this.
But as the Raspberry Pi is ready and connected to the same network, we can use it to find the bridge:

  • Install nmap with apt:
    sudo apt install nmap
  • Run this command:
    nmap -sP 192.168.1.0/24
    Adjust the network to your environment.
  • You’ll get a list of all devices on the network.
    Find the Hue bridge inside, for example:
    find the hue bridge ip
  • That’s it, you found the bridge IP address (192.168.1.10 in my case).

Note this IP address, we’ll use it later.

Configure lights

This is not really related to our project, but before you go any further, make sure all your lights (bulbs or strips) are plugged in and recognized by the bridge and smartphone app, with a name set for each one.

Follow the instructions from Philips. We won’t be playing with the API for the setup, it’s much easier to do everything from your smartphone and only use the API once everything is working properly without it.

Install the Python library

In Python, a library is a collection of functions that make something easier to code.
Instead of writing all the code ourselves, we’ll use an existing library: phue
.

I’ll give you library links for other languages at the end of the article. Python is the default language for Raspberry Pi, and the library works perfectly well, so there’s no need to look for something more complicated (unless you’re an expert in another language or have other constraints).

Grab my Python cheat sheet!
If like me, you always mix the languages syntax, download my cheat sheet for Python here!
Download now

Warning: Since the Bookworm version of Raspberry Pi OS, it’s almost mandatory to use a virtual environment before installing Python libraries. Click on the link to understand what it is and how to use it.

Once the environment is created and activated, you can install the Python library with:
pip install phue
Pip is a magical command for your Python projects, learn more about it here if you’re new to this.

That’s it, we’re ready to move to coding.

Step 2: How to use the Philips Hue API

On your Hue bridge, there is an API available.
The base URL is http://<IP>/api/v1.

I’ll show you the basic requests you can make, how it works, and we’ll create the first scripts.

API introduction

If you are new to programming, API stands for “Application Programming Interface”.
Its main purpose is to allow devices or software programs to talk to each other. It’s a translation tool between your code and the other device’s capabilities.

In our case, the idea is to have the Raspberry Pi talk to the Hue bridge.
The bridge has a list of functions available through the API. Python will make HTTP requests to this API, so we can interact with the Hue lights (turn them off for example).

This API is usually protected with a username that we need to create before making any calls
(You may have seen the “unauthorized user” error when trying to access the base API URL).

API tester overview

To test the API without coding, Philips gives us a tool to create requests in a form.
This form is available at http://<IP>/debug/clip.html.

In this form, you’ll find three parts:

  • URL: The URL you want to call.
    We’ll see later that each function has a different URL.
  • Method: GET, PUT, POST or DELETE.
    These are different actions you can make with your request.
    For example, GET is to see the configuration while PUT is to change something.
  • Message Body: For some specific functions, you may need to add more details to explain what you want to change in the Hue configuration (e.g., which light you want to interact with).

Then you have the “Command Response” below. While sending requests, you’ll see the bridge’s answer in this field. This will help you debug your requests.

Now that you understand what it is, let’s start by creating your username.

Create user

In most requests, we need authentication to allow access to the Hue bridge configuration.
To create your authentication token, fill the form like this:

  • URL: /api
  • Message Body:
    {"devicetype":"TestApp#RaspberryPi"}

    Put what you want for the device type (app name or device as you wish).

  • Then press the bridge button.
  • In the following 30s, hit the POST button to run the query.

This form should look like this:

how to create the Hue username

In the “Command response” field, you can see the username generated by the Hue bridge.
Note it, we’ll use it in all the next calls.

List lights

Before changing the configuration in a specific room, we need to get the list of all lights installed.

Get the list of all the lights

To get a list with all lights available, fill out the form with this:

  • URL: /api/<username>/lights.
    Replace <username> with the one you got in the previous step (long random string).
  • Then press “GET” to get the answer.

The answer is in JSON format, which isn’t easy for a human to read (more about this here).

You should see one paragraph per light.
Each paragraph starts with a number (1, 2, 3, etc.) and contains all information about the corresponding light.

Take a few minutes to find which number corresponds to which light.
For example: 1=>Bedroom, 2=> LED strip, etc.
Later we’ll use only the ID, so you need to grab this information.

Get the status of one light only

You can also get information for only one light.
Just add the light ID at the end of the URL, like this:

  • URL: /api/<username>/lights/1
  • Method GET.

This will ensure that Light 1 is the one you think it is.

Switch a light off and on

Switch a light off

To switch a light off, use these parameters in the form:

  • URL: /api/<username>/lights/2/state
  • Message Body:
    {"on":false}
  • Then click PUT.

You should see the light switching off without using the smartphone app.

Switch a light on

Then to put it back on, use the same parameters.
And change false to true in the message body.

Sandbox finished, let’s move to coding.

Step 3: Write your first scripts

In this section, I’ll show you some basic scripts, to use the API in Python, using the phue library we installed earlier.

Switching the light on and off

Switch the light off

I give you the script directly and explain after:

  • Open your Python editor (Thonny or nano).
    nano switch.py
  • Paste this code inside:
    #!/usr/bin/python
    from phue import Bridge
    import logging

    logging.basicConfig()
    b = Bridge('192.168.1.10')

    #Uncomment this line to register the app (see below)
    #b.connect()

    #Change the light state
    b.set_light(1, 'on', False)


    Replace 192.168.1.10 with your bridge’s IP address you previously noted.
    In the set_light function replace the first parameter with your light ID.
  • Save and run it.
    In Thonny, click “Run” in the top menu.
    Or in a terminal, use:
    python switch.py

The first time you’ll get an error because the script needs to create its username (like we did in the API tester).
For this, you need to:

  • Comment out the b.connect() line.
  • Press the bridge button.
  • Run the script.
  • Comment the line.
  • Run the script again.

The corresponding light should switch off.
You only need to do this the first time, for all the following scripts, the user name already exists and the b.connect() line isn’t needed.

Switch the light on

To not stay in the dark longer, we will turn on the light again :).
Basically, you only have to change one thing: change false to true in the set_lights function.

Here is the script you can use:

#!/usr/bin/python

from phue import Bridge
import logging
logging.basicConfig()

b = Bridge('192.168.1.10')

b.set_light(1, 'on', True)

Don’t forget to replace the bridge IP address.

Change the light color

If you have a color-capable lamp (not all Hue lights are compatible), there are a few more things you can try.

Philips Hue uses two values to define the color: x and y.
You may have seen these values in the API tester.

Basically, x and y are numbers between 0 and 1, and changing their values will change the light color. You can find information here on the official website to convert RGB colors to XY colors.

For our test, we’ll just take random values and see what happens.

Grab my Python cheat sheet!
If like me, you always mix the languages syntax, download my cheat sheet for Python here!
Download now

Here is the code you can use to change the light color:

#!/usr/bin/python

from phue import Bridge
import logging
import random
logging.basicConfig()

b = Bridge('192.168.1.10')

b.set_light(1, 'xy', [random.random(),random.random()])

It’s the same code as before, but instead of changing the “on” setting, we play with the “xy” values.
The random function returns a number between 0 and 1, perfect in this case.

You use the same “set_light” function to change other parameters you’ve seen in the API tester, like the brightness or the saturation.

But now that you understand the basics, we’ll move to more complex scenarios.

Scenarios & routines

In this section, I’ll give you an idea of what you can build with this API, Python, and your Raspberry.

There is no limit to what you can do! Just find an idea and try to code it.

Light schedule

We can build a timed schedule for the light.
For example, switch them on before you return home or wake up.

In the smartphone app, this is available in the “Routines” tab.
But we’ll build it in Python.

See current routines

The base API URL for routines is: /api/<username>/schedules.
You can call this URL with the GET method to see your existing routines in the API tester.

You’ll get a JSON with all the routines and each configuration you made.

You can also see them in a more intuitive way on your phone.
It might be the easiest way to check whether the routines created via your script are correct or not.

Create a routine

To create a routine, you need to POST data to the same URL.
Here is one example:

#!/usr/bin/python

from phue import Bridge
import logging
logging.basicConfig()

b = Bridge('192.168.1.10')

data = {'on': True, 'transitiontime': 600}
b.create_schedule('Wake up', '2019-05-01T07:00:00', 1, data, 'Wake Me Up' )

In this script, we ask the API to create a routine called “Wake Up”.
This routine will switch on the light with ID 1 at the specified date.

You should now see this routine on your smartphone (Routines > From other applications).
Or you can check again with the API tester.

There is no point in doing this if you have the app on your smartphone.
But you can include this piece of code in a larger program.

If you have a schedule with different wake-up times that changes every week, it will be hard to create this schedule with your phone.

In your Python code, you can import a CSV file with the wake-up time for each day, or even connect to a web page to update the wake-up time for tomorrow. You make the code one time and don’t have to do anything after that.

Just an idea … let’s move to the next one :).

Playing with colors

We saw before how to set the light color if your bulb can manage this.
With the power of Python, you can create animation that isn’t available in the smartphone app. For example, we could change the color automatically and gradually every minute.

I will start with something easy but not the prettiest.
And then we’ll see a more complex code to change the color step by step.

First try

In a previous paragraph, I wrote that the color of the Hue bulbs is defined by two values: x and y. To change the color gradually, you can increase this value bit-by-bit. For example, starting at 0/0 and increasing one value by 0.01 every minute.

Let’s try:

#!/usr/bin/python

from phue import Bridge
from time import sleep
import logging
logging.basicConfig()

b = Bridge('192.168.1.10')

x=0
y=0

while True:
   x = x+0.01
   if x>1 :
     x=0

   print(x)
   b.set_light(3, 'xy', [x,y])
   sleep(1)
  • I import sleep from the time library to wait one second between each change (you can set another wait time, but for the try one second is ok).
  • Then I define my two values: x and y, initialized at 0.
  • To make the light change color forever, I need to create an infinite loop (while True).
  • I increment the x value from 0.01 each second and make sure that it stays between 0 and 1.
  • I display the value in the output to monitor if everything goes well.
  • Finally, I set the light to the current x and y values (set_light), and wait one second (sleep).

Run the script and see what happens. You should see your bulb or strip start with a blue light, then change from purple to pink, and finally going red.

Try to change the y value to see which colors you get, or even change the two values at the same time.

The result is cool but not perfect. We don’t go through all possible colors and at the end of the loop, we switch from red to blue without transitioning. Can we create a better script? Yes absolutely.

First improvement

To avoid switching from red to blue without transition, you need to have your value going from 0 to 1, and then from 1 to 0.

To do this, for each iteration, you need to know if the direction is an increment or decrement.
And change the direction when you reach the limits (0 or 1).

Here is how I made this code:

#!/usr/bin/python

from phue import Bridge
from time import sleep
import logging
logging.basicConfig()

b = Bridge('192.168.1.10')

x=0
y=0

direction="inc"

while True:
        if direction=="inc":
                x = x+0.01
                if x>=1 :
                        direction="dec"
        else:
                x = x-0.01
                if x<=0:
                        x=0
                        direction="inc"
        print(x)
        b.set_light(3, 'xy', [x,y])
        sleep(1)

Now, if you run the script, the color will go from blue to red as before, and then from red to blue gradually.

It’s better but we still don’t have all the colors. To improve this, you need to understand what are these x and y values, and how they work.

Can you do better?

Here is the representation of x and y values with the corresponding light color (source: Wikipedia).

As you can see, it won’t be easy to move through all possible colors.
My only idea was to use an array with some points defined manually in your favorite color.
And then to set these colors step-by-step.

I had another idea: convert hexadecimal colors code (#123456) to the corresponding XYZ value.
And there is a Python library to do this.

To install it, use this command:
pip install rgbxy
Make sure to be inside the virtual environment before running this command.

And then you can use functions like converter.hex_to_xy(‘12345‘) to get the xy value from the hex value. You’ll find all the functions here.

But I can’t find how to cycle through all the colors gradually.
So it doesn’t help me.

Use an external API

The last scenario I want to introduce is using an external API.
For example, you can get sunrise and sunset times from an API, and plan to turn off the lights when the day comes up.

That’s something I cover in detail in my Python book (“Master Python on Raspberry Pi“).

If you want an anecdote, I remember I created a script to set a specific color depending on the number of players on my Minecraft server in real-time. For example, white if empty, green up to 10, orange up to 20, and red over 30 players. It’s an idea that you can adapt to your specific point of interest.

It’s funny and easy to make!

Download Your Essential Linux Commands Guide!
It's a free PDF guide containing every Raspberry Pi Linux command you should know!
Download now

Programming with other languages

If you prefer to code with other languages, I want to give you the main libraries I found for the main languages:

On a Raspberry Pi, Python or PHP should be enough for a standalone script.
But it depends where you want to include it, or if you use another API.

And if you are not ready yet to jump into the programming complexity, installing Home Assistant on your Raspberry Pi might be a first step to try to automate everything in your home.

Download Your Essential Linux Commands Guide!
It's a free PDF guide containing every Raspberry Pi Linux command you should know!
Download now

🛠 This tutorial doesn't work anymore? Report the issue here, so that I can update it!

If you are looking for exclusive tutorials, I post a new course each month, available for premium members only. Join the community to get access to all of them right now!

Conclusion

That’s it! You now know how to control your lights from a Raspberry Pi, thanks to the Philips Hue system. It’s difficult to start, but when you understand the basics, you can build what you want in a couple of minutes.

If you need more information, check the Philips Hue Developer website to learn other tips.

Let me know what you build with your Raspberry Pi and Philips Hue.

Whenever you’re ready, here are other ways I can help you:

The RaspberryTips Community: If you want to hang out with me and other Raspberry Pi fans, you can join the community. I share exclusive tutorials and behind-the-scenes content there. Premium members can also visit the website without ads.

Master your Raspberry Pi in 30 days: If you are looking for the best tips to become an expert on Raspberry Pi, this book is for you. Learn useful Linux skills and practice multiple projects with step-by-step guides.

The Raspberry Pi Bootcamp: Understand everything about the Raspberry Pi, stop searching for help all the time, and finally enjoy completing your projects.

Master Python on Raspberry Pi: Create, understand, and improve any Python script for your Raspberry Pi. Learn the essentials step-by-step without losing time understanding useless concepts.

You can also find all my recommendations for tools and hardware on this page.

How would you rate this article?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Spread the word!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar Posts

17 Comments

  1. Hello, this looks like a terrific article. Unfortunately without a publication date attached to it, it’s nearly useless to me. Without having some idea how current the information is, I’m not willing to go through the entire tutorial. It would be great if you could put a publication date at the beginning of the posting. Thanks, and keep up the good work!

    1. Hi Steve,
      This post is about one year old
      It should still work, there is almost nothing depending on the system in this tutorial

  2. Hi Patrick,
    I’m not a programmer but for me this looks good 🙂 .

    I’m trying now to build a website where I can control my lights from. somethig Very easy – a butten on a apache website which when I press the light goes on and when I press it again the light goes off. Can I do it with this script in python?
    Cheers
    Pawel

    1. I don’t have much experience in Python, but it should be possible

      In my case, I have done this in PHP in the past
      But I don’t have the code anymore
      You can find many library on GitHub if you want to try in PHP

      1. Too bad that You don’t have the code anymore. I will try to find Your PHP code and give it a shot. If I will not succeed by myself can I contact You directly? On GitHub is no forum where I can ask 🙁

  3. not working for me, when i first go in debug mode i can see the url changed to :/api/1234

    when i try both /app and /api/1234 i get error 404

  4. im getting this error

    from phue import Bridge
    ModuleNotFoundError: No module named ‘phue’

    1. Hello,

      Did you install the library?
      sudo pip install phue

      And thanks for /app, I will change this

      1. Thonny uses Python 3, you installed it for Python 2. Try using pip3 instead of pip.

  5. When trying to get the list of lights i use the URL:
    /api/7iU1zmt9-mHWtwZ3rW6ZIgz1nRAlEDFvonCRxcmx/lights

    And it returns “Your file not found”

    Any suggestions on how to fix this?

    Thank you in advance for your help.

  6. When trying to get the list of lights i use the URL:
    /api/7iU1zmt9-mHWtwZ3rW6ZIgz1nRAlEDFvonCRxcmx/lights

    And it returns “Your file not found”

    Any suggestions on how to fix this?

    Thank you in advance for your help

    1. Figured it out from another article it needed to have the bridge IP before, so:
      /api/7<username/lights

  7. Hi,

    When i try to use the “put” command to change the state of the bulb to “false” i receive the following message:

    [
    {
    “error”: {
    “type”: 4,
    “address”: “/lights”,
    “description”: “method, PUT, not available for resource, /lights”
    }
    }
    ]

    Do you know how i can resolve this?

    Thanks in advance for your help.

  8. Hi guys,
    I am setting up ambi light with WS2812 LED strip. I was wondering if i can use my philips hue lights with the WS2812 together for more effect.
    Thank you

Comments are closed.