Avatar for allObjects


Member since Jul 2014 • Last active Sep 2017

Very excited about Espruino! JS is just a great, universal language that - for me - implements - thank's @Gordon on an ARM3/4/... MC and with a Web IDE - all essential programming concepts there are and makes them easy to use, including the hardware access. My relationship with The Flintstones is about the same as Espruino and Arduino..., or JS and C... not that C-like things are not of use or needed anymore, but I can get most of them close enough with compiled JS.

Most recent activity

  • in Projects
    Avatar for allObjects

    In deed... listening to you is about re-listening to myself... With a similar background and with the options of shimming/polyfilling/frameworking specific platforms to a common platform, things just work portably perfect. 'Unfortunately' with the resource constraints and a non-ES(X) JavaScript interpreter/vm, things aren't as forthcoming. I recall my first request to have a module to be able to deliver 'class'/constructor and at the same time mentioning browser-side require.js/AMD - because that was the 'thing' I was used to. In the meantime I know that require() looks the same, delivers (almost) the same but works a bit different...

    Espruino JavaScript puts as a bit back into the time where it really really mattered in what Browser Web pages with JavaScript had to run in... to not have a run in... ;-). I feel it is amazing how far Espruino came from when I experienced it the first time - and that was already way beyond version 1v00. Just to mention a small detail: Promises. I started out with just callbacks.

    Just recently I contemplated to extend require(). With different styles of Web communications and Promises available, AMD is done... and Espruino becomes an IoT/Hardware/Controlling-'Browser' in an M2M environment vs. the original - known for quite some time now - UI/Rendering-Browser in a U2M/C2M environment.

    Espruino's frugalness in just everything - power, (eep)rom and ram, and even size (w/ Espruino Pico and now Puck) - except performance and ease-of-use made me reconcile with being put a bit back in time. If mentioned resourcefulness does not matter, no need for Espruino, any other environment of dog bones and xyz berries and ... what ever single board computer you find on the market - in numbers like ants in a hill - would do (btw: rasp means obsolete... because raspberries had to be consumed right away after picking because they mush and rot/ferment quickly... may be that's why the French originally made wine of them).

    Have no answers to your questions(*), because "Was der Bauer nicht kennt, (fr)isst er nicht!" - What the farmer does not know he does not eat!... but I'm willing to learn and become an educated, gourmet farmer... ;)

    (*) except for the last one: may be because reality - hardware with sensors to the real world - is involved, which is not that easy to (unit/integration-test-)emulate as what we call real databases (and other emulatable) system, even though I did that serveral time already when (cross) developing (in the Browser only) logic that uses sensor and display and motion sub-systems. The Sensors, Displays and Motions were DOM nodes. Another reason is: doing IoT on MC level, the targeted environment is pretty given and not much changing. The software is dedicated and not intended general and universal, because latter virtues are just not affordable by the available memory resources. Extensibility has to be 'thought in' in a different way.

  • in Pico / Wifi / Original Espruino
    Avatar for allObjects

    @KevinJ, you are right that in the docs the simple example code doe somewhat solicit a practice that then fails on larger applications. Initially though, I'm sure @Gordon had in mind it would work all the way thru, because last but not least, he went thru all the hoops to save the system's state down to the configuration and active timeouts, intervals, and watches. As said, with small things and simple one-time initializations this works all just fine... Complicating the examples is not the answer, but doing nothing either. May be adding a page with multiple things that need initialization and initializations with dependencies and adding a link in the simple examples to that page would be nice. All Espruino sub projects - including the documentation - is on github... you can clone it, make additions and enhancements and ask for merge requests.

    May be you came across the conversation about simple explanation how to save code that espruino run on start?, where pist #8 and #18 contribaute 2 times 2 cents about code life cycle in Espruino environment.

    Espruino programming concept is quite different from Arduino... even though deep under the hood both work with events, but only Espruino brings it 'easy' (easier?) to understand into the application realm.

    Coming from Browser / JavaScript programming with interfacing with DOM and XHTML Request and Sockets, Espruiono is not much different. It is just not common place to have such a high-level and easy-going language available to deal with micro controller hardware.

  • in Projects
    Avatar for allObjects

    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.

  • in ESP8266
    Avatar for allObjects

    @PeterS, you get the syntax error info also on the right hand side - in the editor pane. I guess you noticed that by now. Sorry that we did not think of the issue entering the example in the console (right hand side). What you also may have found out is that you can enter everything on the left side, it is just not as convenient. For given DHTH22 sensor example, you would have to enter on the left side following code before you enter the example code (with lines 3..40 being the non-minified, source code of the DHTD22 module from http://www.espruino.com/modules/DHT22.js­) :

    function DHT22(pin) {
      this.pin = pin;
    DHT22.prototype.read = function (cb, n) {
      if (!n) n=10;
      var d = ""; 
      var ht = this;
      pinMode(ht.pin); // set pin state to automatic
      digitalWrite(ht.pin, 0);
      this.watch = setWatch(function(t) {
      }, ht.pin, {edge:'falling',repeat:true} );
      setTimeout(function() {pinMode(ht.pin,'input_pullup');},1);
      setTimeout(function() {
        delete ht.watch;
        var cks = 
        if (cks&&((cks&0xFF)==parseInt(d.substr(34,­8),2))) {
            raw : d,
            rh : parseInt(d.substr(2,16),2)*0.1,
            temp : parseInt(d.substr(19,15),2)*0.2*(0.5-d[1­8])
        } else {
          if (n>1) setTimeout(function() {ht.read(cb,--n);},500);
          else cb({err:true, checksumError:cks>0, raw:d, temp:-1, rh:-1});
      }, 50);
    exports.connect = function(pin) {
        return new DHT22(pin);

    ...because something like this happens when you upload your code on the right hand side with the Upload to Board button:

    The upload looks *FIRST* through your code (with regular expression) to find all require.("...") patterns. For each "...." module reference, the code is pulling from internet or local modules folder and 'shoved the down the throat' of Espruino over the same channel as when you enter stuff on the left side. As *SECOND AND LAST*, the actual application code is uploaded - again - over the same channel.

    You just cannot obviously see that because before sending any code, the uploader turns echo in console of and turns it on again after completion of upload. But when you use the Up Arrow key in the console (left hand side) after an upload just happened, you see the last complete JavaScript expression/line that was uploaded... which proves, that the uploader just did what I described above.

    (You may have read post #8 and post #18 of the conversation about simple explanation how to save code that espruino run on start? which explains these things in more detail. - Luckily, the complexity of sequencing of nonblocking/asynchronous thins or callback-hell where Espruino moves on in the code before things are done is made easy: [Promise]()s is available on Espruino and makes writing event driven applications with Espruino even more a breeze.)

    To complete the exercise of this post - proof that we can enter all in the left side and succeed - we paste now the example in the left hand side (for convenience the example code is repeated here):

    var ow = new OneWire(A1);
    var sensor = require("DS18B20").connect(ow);
    setInterval(function() {
      sensor.getTemp(function (temp) {
        console.log("Temp is "+temp+"°C"); 
    }, 1000);

    There is no real mystery, just pur(e)3.co.uk smartness... 'pure smartness' - I just made that up. No clue where pur in http://pur3.co.uk stands for... may be IT IS pure - with the E facing backwards as some do when obfuscating their password or user id... Cats puRR, may be in 3(D)...)... only @Gordon may shed some light on pur3... if he thinks we can handle it... sorry: ...if I can handle it... ;-)

  • in ESP8266
    Avatar for allObjects

    ...yep, np what so ever. Monitored temperature in my upstairs office - more like a sauna - over the CA heat wave recent weeks...

    ...and I did not need to store the module local.

    @Alexander's struggle got me going and made my get a sensor and run the examples, even added a display and a Web server connecting to my home wireless so I had access to the sensor information from anywhere in the house with my phone over Wifi.

  • in Projects
    Avatar for allObjects

    ...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.

  • in Projects
    Avatar for allObjects

    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...

  • in Pico / Wifi / Original Espruino
    Avatar for allObjects

    @user81574, I suggest you move on with PaddeK's code. Again, thanks @PaddeK for sharing. It does not need much to get it to completion for enroll and the other functions you would like to have at your (coding-)finger-tips. (Sticking on my path would over several serious transformation steps - such as adding the parser and promise - lead to a solution too... but I like to use invented wheels... in favor of saving the - unrecoverable - resource called Time for getting after the not yet invented ones...).

    For example, for the enroll function, just add the application callback into the method signature (line 11):

    ...function(id, callback) {

    and use it (in lines 21 and 22):

            let errorHandler = (err) => { ledOff(); reject(err);
                        callback(err, { _: me, id: id }); },
                successHandler = () => { console.log('enroll success'); resolve();
                        callback(undefined, { _: me, id: id })};

    If you want to have your callback execution to happen in its own Espruino JavaScript single-thread 'task', pack the callback invocation in setTimeout(...:

            let errorHandler = (err) => { ledOff(); reject(err);
                        setTimeout(callback, 100, err, { _: me, id: id }); },
                successHandler = () => { console.log('enroll success'); resolve();
                        setTimeout(callback, 100, undefined, { _: me, id: id })};

    This will allow other pending - and may be more pressing - 'tasks' to get a chance to do their thing. Applied throughout the whole application makes your application behave like a TSO - (processor) time sharing option - environment for each of the tasks, where you run less into timely-ness contentions (buffer overflow, stacking up to many and/or 'losing' events,...) - from the single core /360 times...

    For adding more to the module, such as getting the extra information on open, add a method .open(... following the same pattern as .enroll(... with callback, and adjust the successHandler accordingly.

    To make operations very robust, always begin with an open( and end with a close (to be added in both successHandlerand errorHandler. I do not know the finger print reader's sequencing control, but having a clear begin and end always helps - like demarcation of a transaction: begin and end with commit or rollback (a-la successHandler and errorHandler, respectively).

    Putting all in one single module is no difficult either. Just add the code into the first piece of code from @PaddeK.

    This conversation was great pleasure for me and makes me conclude: Old dog, new tricks? ...still works.

  • in Pico / Wifi / Original Espruino
    Avatar for allObjects

    Promise really shines in this setup of sequencing. I'm glad it became available. I have only one little concern that the nesting may push the limit of memory usage. Of course, implementation of how data is handled can greatly mitigate that.

  • in Pico / Wifi / Original Espruino
    Avatar for allObjects


    ...oh these late nights, early early mornings lend many hands for a nice tee and coffee and nasty spills there of...

    But foremost: @PaddeK, thanks for sharing!

    Looked through the code and - even though not the way I'm used to - I like it and learned a lot from it... including a bug: I treated the checksum as 8 bit instead of 16... ouch. Using a buffer and put 8 and 16 bit views over it is a cool thing... One could even use a clipping one that makes the &0xFF obsolete...

    @PaddeK, do you have some usage information?

    From your comment and code I assume you got pretty far with implementing. Yes, images is not the coolest to do... If you would have some SRAM / FRAM / MRAM (able up to 40 MHz clock rate - enough to keep up with measly serial 9600, even with byte-wise addressing versus self-incrementing address) and stream response into those, on serial data receipt and process it form there... Regular information as blocks, and images streamed. Serial (flash) EPROM would work as well used as a Ring buffer, fast enough, cheap, and barely wearing down with the amount of data when going for a large one... The EPROM could then also be used as the 'local Database' in addition to communicating it over Wifi to a networked server (that's what I guess @user81574 has eventually in mind... ( Btw, do you know the size of a so-called profile? Because that is what I guess has to work as minimum to be really useful).

    @user81574, I would give it a try with @PaddeK's code when given some usage samples.