0

I have a circuit with a shift register which controls 8 LEDs: http://node-ardx.org/exercises/5. In code, I created a function cycle() cycle through each LED one at a time, but this occurs too quickly on the board. How can I add a delay inside the loop so that each LED stays on for 500ms?

Here's my code:

var five = require("johnny-five"), board, shiftRegister;

board = new five.Board();

board.on("ready", function() {
  shiftRegister = new five.ShiftRegister({
    pins: {
      data: 2,
      clock: 3,
      latch: 4
    }
  });

  var bytes = [
    00000001,
    00000010,
    00000100,
    00001000,
    00010000,
    00100000,
    01000000,
    10000000,
    00000000
  ];

  function cycle() {
      for ( var i = 0; i < bytes.length; i++ ) {
          console.log(bytes[i]);
          shiftRegister.send(bytes[i]);
      }
    }

  this.repl.inject({
    sr: shiftRegister
  });

  cycle();

});
1

The answer is already provided in the article.

  var i = 0; 
  function cycle() {
    console.log(bytes[i]);
    sr.send(bits[i]);
    i++;
    if( i<bytes.length )
      setTimeout(cycle, 300);
  }
  • I don't want the cycle function to repeat. I do want to delay just after sending the new byte to the register just after changing the LEDs. – KatieK Dec 11 '14 at 17:19
  • See edit above. It now only does one cycle. – Gerben Dec 11 '14 at 19:17
2

Insert a delay of 500ms?

function cycle() {
    for ( var i = 0; i < bytes.length; i++ ) {
        console.log(bytes[i]);
        sr.send(bits[i]);
        delay(500);
    }
  }
  • 1
    JavaScript doesn't have a function called "delay". – Ignacio Vazquez-Abrams Dec 11 '14 at 14:14
  • 1
    Good job that's not the language we're discussing then! – Mark Williams Dec 11 '14 at 14:17
  • Which variant of C or C++ is the "var" keyword supported in? – Ignacio Vazquez-Abrams Dec 11 '14 at 14:34
  • In that case you'll want this I imagine. – Mark Williams Dec 11 '14 at 15:00
  • This isn't working for me. When I run the changes above, the REPL reports delay is not defined. I'm running Johnny Five v0.8.32. Where is delay defined by Johnny Five? – KatieK Dec 12 '14 at 5:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.