Display output from two pucks in one browser window

Posted on
  • Hello, I'm new to pucks. Received two of them for a little project with RC racing cars. We want to put one puck in each car and a magnetic strip at the finish line to count the laps. The hardware setting works and within the web IDE the code for counting the laps works as well. Now I'm looking for a way to have both pucks outputs combined. Seems that one browser window could work. But with the details I'm lost. Please can somebody give me some hints on how to connect a chrome browser window to the two pucks and how to display the puck output in a browser window? Thank you!

  • That sounds like a really neat idea!

    The normal Puck.write/etc is meant for a single connection, but Puck.connect returns a new 'connection' variable for each active device and will work just fine with multiple Pucks (I think the limit depends on the Bluetooth device in your PC, but it should be 5 or more).

    Here's some code which'll connect to multiple Pucks - just click each button and connect in turn, and then when a button is pressed on each it'll get reported.

      <script src="https://www.puck-js.com/puck.js"></­script>
      <button class="connect_button" btn="A">Connect A</button>
      <button class="connect_button" btn="B">Connect B</button>
      <button class="connect_button" btn="C">Connect C</button>
      <pre id="log"></pre>
      <script type="text/javascript">
        function log(txt) {
          document.getElementById("log").innerHTML­ += txt+"\n";
        // Called when we get a line of data 
        function onLine(btn,v) {
          if (v.indexOf("Pressed")>=0)
           log("Button "+btn+" pressed!");
        // When clicked, connect or disconnect
        var connection;    
        var buttons = document.getElementsByClassName("connect­_button");
        for (var i=0;i<buttons.length;i++) {
          buttons[i].addEventListener("click", function() {
            var btn = this;
            var btnid = this.getAttribute("btn");
            Puck.connect(function(connection) {
              if (!connection) {
                alert("Couldn't connect!");
              log("Connected to "+btnid);
              // Handle the data we get back, and call 'onLine'
              // whenever we get a complete line
              var buf = "";
              connection.on("data", function(d) {
                buf += d;
                var i = buf.indexOf("\n");
                while (i>=0) {
                  onLine(btnid, buf.substr(0,i));
                  buf = buf.substr(i+1);
                  i = buf.indexOf("\n");
              // First, reset Puck.js
              connection.write("reset();\n", function() {
                // Wait for it to reset itself
                setTimeout(function() {
                  // Now tell it to print text whenever the button is pressed
                  connection.write('\x10setWatch(function(­) {console.log("Pressed");}, BTN, { edge: "rising", debounce: 50, repeat: true });\n',
                   function() { console.log("Ready..."); });
                 }, 1500);

    The majority of what's in there is resetting/loading code onto the Pucks and then reading one line of data at a time - the actual connection code is pretty simple.

  • Very nice, I will try that when my Puck JS arrives - Cheers Jonathan

  • Will something like this code work for what I am wishing to do does anyone know.? All I want is that when my 8 Pucks arrive that a light comes on in one puck, a person touches the Puck that the light came on, it goes out when touched, then a another Pucks light comes on and the person touches that Puck to switch the light off, etc etc, all Puck lights coming on at different times and all random. But not controlled via a web site. If anyone has any video of the Pucks doing this I would love to see it. Hope this makes sense.

  • Your scenario is:

    1. 8 pucks P# - # = 1..8 - plus a hub - H
    2. all expected pucks come online with the hub
    3. Hub randomly picks a puck, for example P3
    4. Hub tells picked Puck P3 to turn the light on
    5. Puck P3 turns light on
    6. Puck P3 gets hit (P3's momentary switch is pressed)
    7. Puck P3 turns light off
    8. Puck P3 notifies Hub about event (P3 Light on-time)
    9. Hub randomly picks another puck, for example...
      ...move on with step 3... and this will go on and on until some other condition/event is met/happens.

    Above sequence assumes Hub is involved in every on-off cycle... this allows different patterns of selection:

    1. completely random - step 2 happens independent of what happened in previous steps 2.
    2. conditioned random - second step 2 picks one of the 7 not yet lightened pucks, step 3 of the 6, etc. which gives lets the hitter - if the hitter has knows what has gone on for the last hits since begin - anticipate what's next with increasing probability up to 1: the last one after 7 have been lit and hit.

    Another option is that each puck knows the other 7 in the gang and picks randomly which puck's turn it will be to lit, hit, and turn off.

    further variations are a variable delay time until next puck is lit....

    ...and how (variable) long a puck will be lit... and and how long after the light turns off the puck is still sensitive to a hit...

    ...and also if a puck is hit when is is not or had just turned off the light but was not sensitive anymore to hits

    All these variations allow to draw various conclusions...

    From what I understand is that it is not only about being able lit, being hit, and turn off, but also forward information about the events to a central recording place which does stats/graphs.

    PS: if you have just 8 pucks, they would need to know about each other's id upfront, so they can create the proper advertising and scanning.

  • You are the Man and have got it in one first time. That is what I am trying to do 100%.

    Its to help my kids and hopefully kids all over the world who are Football Players, or play any sport, to improve their reaction and speed etc. You can buy commercial ones but they want $8K!! for 8 lights! and I know I can make the same for max $500, maybe less.

    Its just the coding I get stuck with as I am hardware not software sorry to say. Below is a bit more information on my project which may explain it a bit better. This was my original question, but I think you have answered it all for me. How much will you charge to do the code for me? - Cheers Jonathan

    1) The Puck JS I understand has a switch built into its case that can switch LEDs on etc. Can I hard wire/replace the built in switch with a stronger switch, the switch I will use will be a High Grade Military switch as it needs to be very strong to withstand hard hits to it (Both by hand and foot). The switch I will use will be a momentary switch, i.e push to activate. Is it easier enough to wire the Military switch wires onto the Puck JS either to replace the built in switch or run in parallel etc?

    Answer Please:

    2) The Puck JS has built in LED's but they will not be big enough or bright enough for our product. I intend to make a round PCB board with either 8 or 12 large BRIGHT LED's on it and that the Military switch will sit in the middle of. I understand I will need an external power supply etc to control the other 8/12 LED's and this is OK, but can I take the data signal that the Puck JS uses for its own internal LED and use that to control my large external LED's when my switch has been pressed?

    Answer Please:

    3) I understand the Puck JS, and as per the video I saw, can be set up as a slave and master system, where by when one of the switches in the Puck JS is connected (touched) and thus turning off the LED in that Puck JS, that another Puck JS a few feet away will be activated and its LED comes on, and so on and so on.

    If so what is the maximum control range from Puck to Puck. 5 foot/20 foot?

    Answer Please:

    How many Puck JS can be talking to each other via the master Puck JS. Maximum I need is 12 but could work with 8. I am not very good with coding, so any advise help anyone could give on how to make the Puck JS talk to each other would be very much appreciated.

    Answer Please:

    How hard would it be to make an APP (Blue Tooth?) that can also be used to decide which of the 8 or 12 Puck JS LED's come on and when? So that people who use it can set their own training session, i.e if your left arm has been broken and you have to do exercise to make your left arm stronger you can make the LEFT sided Puck JS LED's come on more and not just random.

    Answer Please:

    Is there a way to give feedback and data to people as to how much they improve in terms of speed/reaction time etc and have this sent via BLE to a mobile via an App?

    Answer Please:

    1 Attachment

    • Example.jpg
  • 1) switch is not the switch you want to use... you can use it for testing... but for real, you would just some kind of touch/hit sensor/switch that is read by a pin. Btw, whether it is called Btn or pinX, the code is the same.
    2) the internal 4 leds (r,g,b,infrared) are not for bright ligth, more a control. Therefore you just connect a pin to a N FET and switch with that a LED bank or a 1..3W LED that gives more light. To drive that bright light you need anyway some more power capacity than what the puck has built in.

    3) Line of sight and no obstructions, BLE makes it to 100+ meters... so no worry for run that in a room... may be not across a soccer/Football field, but for sure in a gym it is good enough.]
    4) the concept is that all pucks in a set are known to a hub - an extra device that understands BLE.

    5) Depending the concept, you are not really limited to the number of pucks... but an overcrowding in the RF space

    6) Writing the cod for a puck is not that difficult. A bit more work is needed for the hub, last but not least you want the hub to be able to program/select profiles of activation patterns, and make it select. I would not combine that with the puck. Most likely, this should be a device that can do Wifi and BLE - like a bridge (a puck though connected to the pc can do as well). A wifi enabled and connected device can even send the data to a google spreadsheet document, from which all kinds of reports and graphs can be produced with plain spreadsheet formulas/programming.

    The outline for the pucks an hub application is something like that:

    One way is:
    The pucks all start out in advertising mode, in which they advertise their ID and that they are ready for connect. The hub then sends the light on command (delay to turn on the light, how long the light and how long to sense a hit). The puck executes the commands and reports back the hit time. The hub waits for that response, closes the connection, stores this information, and then moves on the the next randomly (or profile defined) puck's advertisement, and so on.

    ...more at later time.

  • Amazing how you work all this out, just amazing. The Google Spreadsheet is a great idea, never though of that.

    Yes I want the hub to be able to program/select profiles of activation patterns etc so are you saying its better not to use the Puck and use a different device for the hub?, what sort of Bridge/Hub do you suggest and can I buy one already made or do I need to have one designed?

    I agree a sensors better than a switch, I am just not sure which is the best one and if they will activate fast enough when the hand/foot triggers them, any suggestion which is the best sensor to use?

    Yes 100% correct what you have written below:

    The pucks all start out in advertising mode, in which they advertise their ID and that they are ready for connect. The hub then sends the light on command (delay to turn on the light, how long the light and how long to sense a hit). The puck executes the commands and reports back the hit time. The hub waits for that response, closes the connection, stores this information, and then moves on the the next randomly (or profile defined) puck's advertisement, and so on.

    I got the idea from the below link, but they want crazy money and no parent/child can afford the money they want, so I decided I would have a go and make a cheap version that anyone can buy or make and enjoy using to get fit. - Thanks again for feedback Jonathan

  • A brief note for sensor: puck has already built in magneto sensor. Having a moving part in your device with a magnet could be used to get that going... see attached cross cut. There is also a third Puck Placement option C: next to the Power Pack. Orientation and Placement and Relative Movement of Magnet in respect to Puck would have to be figured out experimentally.

    Making it water tight for up to ... meters include even more application fields. Spring has then to be from stainless steel and button needs holes to accommodate displacement on pressing replacement on releasing.

    'Communication' under water may have to be done differently... I'm pretty sure that water cuts back tremendously on range of BLE. But making some range test experiments would pretty quickly answer that (very low frequency / very long wave RF is probably not easy to achieve, since it would ask for very long antennas... may be a ferrite stick / bar /...? ...but that would be a totally different communication setup). So, if there is no RF communication at all, this are alternatives to check out:

    a) a time delayed programmed program is loaded before the devices get thrown into the water.
    b) communication could happen by pulse modulation of the lights emitting the information usually sent over BLE
    c) if the regular light does not make it, IR could make it with additional IR diodes and sensors (puck has already built in IR LED and Light sensitive LED, but they are most likely not be of use and adding light conducting channels into the device from multiple pint in the device's surface may not be feasible or work either.
    d) use sound - sea creatures like whales and dolphins do that all the time - using piezo / surface speakers and sensors.... different frequencies and modulation techniques would have to be evaluated...

    Anyway... enough of the dreaming... sw is on my brain burner...

    1 Attachment

    • touchDevice.png
  • Thanks again great feedback, great drawing, what software do you use to make that?

    Yes the magneto sensor in the Puck maybe the best way to go for the sensor etc, I never thought of that, good idea.

    I have ordered my 8 Pucks to at least start my idea. Any idea how I start on the sketch/program now to start them at least talking to each other? And is there a ready made hub you would suggest I buy/use as the main controller? Thanks once again.

  • ...let yourself inspire by this conversation about Multi-puck Game Howto?.

    Btw, you can cross-develop your application in a Browser and plain text editor... until your pucks arrive... Your browser understands JavaScript and you can model (simulate/emulate/fake(news)) your components nicely as object with same protocol, but different implementation for the aspects that are different (button and light are DOM nodes that can have events attached and change their state by css. I would do that anyway... and did it already for several projects. Constant upload takes its time and debugging is much harder than in a browser. Upload times with puck are even more time consuming because it's OTA / BLE. (Chrome) Browser has an excellent debugger.

  • Great thanks I am looking at the link you sent now, very interesting. I will have a go doing what you suggested, send me some links of projects you have done if you don't mind, I would love to see them to also get ideas etc - Cheers

  • I was reading up what happened with Puck.js since I received mines as Kickstarter reward. At that time I did some basic stuff, but since then I was busy with other (and other Espruino) things.

    Reading through what BLE offers for multi-connection and conversation and the timing that is involved with it, I have to revise the communication concept. Main reason is that connecting and disconnecting is not fast enough (1..2 seconds) to actually do what you @Jonathan_Mallinson want to do. I assume things can happen very very fast - on land, in water it would be a bit slower and the slow way would work.

    In general, Bluetooth has a limitation of a Master/Central device having max. 7 connections to Slave/Peripheral devices. I though read somewhere that the BLE Espruino implementation would allow more - it is just a question of memory... But I guess 7 works for you too. Therefore, lets look in a first step into what can be done with 7, and may be later how this number can be increased.

    As base to start with is this documentation about Controlling Other Pucks.

    What we see in the example is that the master/central puck

    1. looks for the slave/peripheral puck with a particular id (advertisement) with NRF.requestDevice(...). This may take up a few seconds, because there may be a lot of BLE devices out there that advertise...
    2. establishes a ble_simple_uart connection (simple universal asynchronous receive and transmit communication over BLE). This takes some time too.
    3. sends the command for the slave/peripheral puck as function call in JavaScript source code
    4. disconnects from slave/peripheral puck (takes also some time...).

    So there is not much new or different from what I initially started with: the peripheral pucks are in advertising mode advertising their (customized) id. But the major difference is caused by the fact that a puck can be in either advertisement mode or connected mode, and switching between that take the time you cannot afford.

    The first example in referenced documentation is also not better in performance, since the connection is established for each command and torn down afterwards. But this is not the last thing... The whole process can be made much faster - for a price which we explain and deal with later on.

    The second example establishes the connection once - in a slightly different way with device.gatt.connect() and keeps the connection... Some application code has now to be built around the code of the second example that:

    • is aware of the '7 other guys' that 'are in the game'
    • runs activity programs
    • commands the other guys to light up
    • listen for the other guys for their hits
    • collect performance data from the other guys
    • be able to communicate with 'the outside' (for all kinds of things via BLE AND button)
      • switch between modes of connect to outside (admin) and connect to guys ('play'/activity)
      • start / stop activity programs
      • select loaded programs
      • load identity
      • load 'other guys' ids
    • report (low) power status (for some house keeping)
    • be able to be waken up / pulled back when gone lost

    The 'other guys' will also need some software smartness:

    • be aware of the 'master(s)' that can - are allowed - to ask for a connection
    • be able to connect
    • listen to the commands with parameters
    • handle the lights
    • handle the button (hits)
    • be able to communicate with 'the outside' (in a different way and for a different purpose than the master)
    • be able to communicate with 'the outside' (for all kinds of things via BLE AND button)
      • switch between modes of connect to outside (admin) and connect to guys ('play'/activity)
      • load identity
      • load master's id (masters' ids)
    • report (low) power status (for some house keeping)
    • be able to be waken up / pulled back when gone lost

    Before doing a deep dive in the application we have now - as promised - to deal with the reason why we have to build it that way and what the corollary cost of it is:

    The *LE in BLE does literally WALK THE TALK OF LOW ENERGY. And the proof of that is that Puck can advertise for months and months and months and... even years while living just of a CR2032 button cell/battery of average 200mAh. How can it do that? Advertising costs about 20uA that is averaging to 4uA with suitable duty cycle and transmit power level of advertising - just one (1) uA more than doing really really nothing (see section Power Consumption at espruino.com/puck.js). Math then tells us that 200mA / 4uA = 50'000 h (hours) = 5.7 years. And with a (space) quality battery - that would be even longer... just limited by shelf life / self-discharge of the the battery (Smoke/COx detectors do such things up to 10 years on a fat battery). Of course, life is not just advertising, and 'decent' transmit power level as used for the longevity test may not be good enough.

    As seen in Power Consumption section of espruino.com/puck.js, being connected, uses about 200uA - 50 times more than just advertising - gives us still 1000 hrs (40+ days) - and with JavaScript running 4mA - 10'000 times more than advertising - gives us still 50 hours. Now 50 hours is not really the number, since JavaScript in Espruino runs only when there is something to do... because Espruino is Event Driven.

    Said so we are totally on the safe side for the intended application... and even more so, because for running lights, we have to have anyway an extra power pack that has to source peaks up to 500mA (25LEDs 20mA each). Some Alkaline AA (800mAH) 'can' do that, Ni-HM (~2500AH) do even better, and best do LiPOs... LiPO do the best not necessarily from a capacity point of view, but because they can supply highest current draw vs. capacity compared to any other readily available technology. Furthermore, with Alkalines 3 cells are required to run some type of LEDs, and even then the voltage falls below the required voltage way before the cells' capacity is exhausted (old NiCads fair even better in that respect). With LiPOs only one cell is required. To drive a puck though, a voltage regulator is required because a fully charged LiPO yields up to 4.2 Volts and will kill the puck. For driving the LEDs with equal - or ambient adjusted - brightness, evenly simple circuitry is required - current limiting resistor(s) - and the rest PWM can do. If individual LED control is required - for example to communicate with numbers of lit LCDs, a little bit more hardware is required.

    If going down the path of individually controlled LEDs, additional information can be communicated to the hitter by running LEDs - clock and counter clock wise, jumping LEDs, different speed of running and jumping to indicate time frame, etc. (different speed of behavior would be useful for, for example, to light multiple devices and communicate hit priority/on time/etc... which could even vary... there is no limit to what can be thought of to increase appeal and excitement of the game and avoid 'predictability'... left and right to indicate to hit or not hit, or hit first all running one direction and then the other... a careful analysis system has though then to be developed...)

    With the power pack that is required for running the lights, we can very very easily also run the Pico... the additional power draw by puck will barely barely noticeable. The button cell can be replaced by a dummy that is powered thru wire by the power pack - or even much easier - directly through pins we have anyway to connect. Puck could be not in its regular case, but rather plugged in... It still could stay in its case but pins or connector with at least three (3) connections have to be available: GND, 3.3V, light control (output)).

    Being done with the options and power consumption rap sheet, we can say that sustaining connection for fast communication is not an issue (minor point to discuss is: how can we reasonably protect 'the other guys' from 'denial-of-service' attacks before they are asked for connection form master...)

    And the icing(s) on the cake:

    1. master can also be used like 'the other guys'
    2. all can be programmed the same way, which has multiple advantages:
      1. if master goes bust, one of the guys can take over
      2. a team of 8 can be split into two with two masters and 2-to-4 and 3-to-3 'other guys' in the teams.
      3. more icing(s) later...

    Let's get coding...

    PS: this is my fifteenhundredandfirst post... started out a bit more than 3 years ago - June/July 2014- with Espruino version 1v64 on The Original Espruino Board.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview

Display output from two pucks in one browser window

Posted by Avatar for user80956 @user80956