obniz developer team
Published

Change the color of a full-color LED with HTML color picker

Easily change the color of a full-color LED using an HTML color picker displayed in a web browser.

BeginnerFull instructions provided1 hour545

Things used in this project

Hardware components

obniz
Cambrian Robotics obniz
×1
RGB Diffused Common Cathode
RGB Diffused Common Cathode
×1

Story

Read more

Code

Untitled file

HTML
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="https://obniz.io/js/jquery-3.2.1.min.js"></script>
    <script
      src="https://unpkg.com/obniz@3.x/obniz.js"
      crossorigin="anonymous"
    ></script>
  </head>
  <body>
    <div id="obniz-debug"></div>
    <h2>Color Picker with LED</h2>
    <input type="color" value="#333300" id="colorPicker" />

    <script>
      var obniz = new Obniz("OBNIZ_ID_HERE");
      obniz.onconnect = async function() {
        var led = obniz.wired("WS2811", { din: 3, vcc: 2, gnd: 1 });
        led.rgb(0x33, 0x33, 0);
      
        $("#colorPicker").on("change", function(val) {
          let colorString = $("#colorPicker").val();
      
          let rgb = colorString2hex(colorString);
          led.rgb(rgb[0], rgb[1], rgb[2]);
        });
      };
      
      function colorString2hex(hex) {
        if (hex.slice(0, 1) == "#") hex = hex.slice(1);
        if (hex.length == 3)
          hex =
            hex.slice(0, 1) +
            hex.slice(0, 1) +
            hex.slice(1, 2) +
            hex.slice(1, 2) +
            hex.slice(2, 3) +
            hex.slice(2, 3);
      
        return [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4, 6)].map(function(str) {
          return parseInt(str, 16);
        });
      }
    </script>
  </body>
</html>

Credits

obniz developer team
80 projects • 37 followers
Development board "obniz" is controlled via the internet.

Comments