Search code examples
javascriptc++arduinocross-language

Interface javascript with arduino


I'm an arduino noob and I'm trying to interface some javascript with arduino. For now all I'm trying to do is move a servomotor in a direction if a js variable is under a certain value and moving it the other way if it's above that value. I don't have a clue about how i should tackle this, so I'd appreciate any help. I do have the servomotor moving part and the javascript part, I just don't know how to put them together.


Solution

  • For now all I'm trying to do is move a servomotor in a direction if a js variable is under a certain value and moving it the other way if it's above that value.

    Here's how you can accomplish this with Johnny-Five:

    1. Make sure you have node and npm installed
    2. With the Arduino IDE, upload StandardFirmata (File -> Examples -> Firmata -> StandardFirmata) to the Arduino, close the IDE
    3. npm install johnny-five
    4. create a new JS file, save the following in it:
    var five = require("johnny-five");
    var board = new five.Board();
    
    board.on("ready", function() {
    
      var servo = new five.Servo(11);
    
      this.repl.inject({
        move: function(value) {
          var angle = 0;
          if (value > 0) {
            angle = 180;
          }
          servo.to(angle);
        }
      });
    });
    
    1. With the USB cable plugged in to the board and computer, run the above program in your terminal. Once it's running, call move(n) where n is any number. Numbers greater than 0 will move the servo to 180°; numbers less than or equal to 0 will move the servo to 0°.