onInit and reset

Posted on
  • Is there a way other than power cycle to send a command to restart and run onInit? reset() seems to keep it from running.

    Bill

  • Try load() - that loads code out of flash and runs it... reset() clears everything out of memory, so there won't be an onInit() for it to call!

  • I have spent a lot of time on code that when loaded from the IDE works great. When I do a save and power cycle, it never seems to run the same. I have done a dump() and the code looks like it is missing whole sections. Doing this on a STM32Fdiscovery.

    Code from IDE:

    function delay(count) {
      for(x=0; x < count; x++)
        ;
    }
    delay(1000);
    print("test");
    
    Response from dump()
    function delay(count) {
      for(x=0; x < count; x++)
           ;
    }
    var x = 1000;
    digitalWrite(A0,0);
    =undefined
    

    BTW, this digitalWrite(A0,0); never goes away.

  • That's expected.

    When you send that code from the IDE, some of the commands are running immediately.

    delay(1000) gets called, which sets x = 1000 by the end of the loop, and you print "test".

    Then you save the state after that - that saves the state at the time you do save(), so it saves a function called delay and the variable x with value 1000.

    To make that work the way it looks like you want it to, you need to put code you want to run at startup into the onInit() function, which is called on startup - ie:

    function delay() {
    for(x=0; x < count; x++)
    ;
    }
    function onInit() {
    delay(1000);
    console.log("test");
    }
    

    Basically, all the code needs to be in onInit() or within other functions. Even require("module.js").connect()'s should be done inside onInit(), since some of them need to run code to initialize the external hardware.

    When you do save(); it will save the current state, and then reset the Espruino, loading the saved code, and running onInit().

    Note that that's a lousy way to get a delay - because you have no idea how long that loop will take to execute 1000 times. When I need a delay, I do:

    function delay(a) {
    var et=getTime()+a/1000;
    while (getTime() < et) { 
    ;
    }
    }
    

    Also, for for loops, you probably want to do for (var x=....), not for (x=....), unless you're intending for x to be a global variable.

    Not sure about the digitalWrite(A0,0) - I suspect it's something board specific?

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

onInit and reset

Posted by Avatar for tobor @tobor

Actions