• You don't need state machines for this simple case.

    @Robin: Refering to post #1 and #4, to replace WHILE and FOR with setInterval/setTimeout/clearInterval, use this code when the button is pressed (first setWatch function, line 1) instead of WHILE:

    yolo = setInterval(function() {  //the watch displays the hour
          display(1, hourFirstDigit);
          display(2, hourSecondDigit);    }, 50); //with 50ms if may flicker
    

    When the button is released (second setWatch function , line 11) call clearInterval(yolo) and allClear(). Then show the minutes again with yolo = setInterval(), and use setTimeout to clear that interval after 300ms with clearInterval(yolo) again insted of FOR.

    If the displays flickers at 50ms reduce the interval to maybe 25 or 20ms.

  • Note: Although we don't have the 'actual' seven segment wiring diagram, I'm inferring each segment is connected to a physical pin.

    IMO @maze1980, it doesn't make sense (to me anyway) to continue to hammer on the outputs using digitalWrite() every 50msec, as just a one time write should be sufficient, unless of course the digits are in the state of changing.



    For the next step of code optimization, @barry_b_benson it would be far more efficient to replace all those function calls with a simple array containing the 'on' state of each segment.

    https://www.quackit.com/javascript/tutor­ial/two_dimensional_arrays.cfm

    Although I tend to stay away from global arrays, in this case using your existing module, would be an easy addition.

    Something like:   Untested

    var arySegments = new Array(10);
    
    // { A B C D E F G }  where G is middle segment - L91 inside link of post #1
    // This works nice here with digits as element zero of arySegments[0] is zero
    // See usage inside function display() below
    
    // For Zero
    var aryDigitZero = { 1, 1, 1, 1, 1, 1, 0 };
      . . . 
    var aryDigitNine = { 1, 1, 1, 0, 0, 1, 1 };
    
    // Load the master array with each segment lit definition
    arySegments.push( aryDigitZero );
      . . . 
    arySegments.push( aryDigitNine );
    
    
    function display( value ) {
      
      for ( var idx = 0; idx < aryDigitZero.length;  idx++ ) {
        digitalWrite( arySegments[value], arySegments[value][idx] );
      }
    }
    
    
    // Usage to turn on a single digit
    
    display( 8 );
    
    



    Different example initializing two dimension arrays:

    https://www.espruino.com/Morphing+Clock

About

Avatar for Robin @Robin started