The Unconventional Guide to Nodejs for Arduino

This article is continuation of previous article named Arduino And Python but using NodeJs.Follow steps 1 and 2 of that article to load standard firmata code to arduino. I am going to use arduino-firmata.js, a NodeJs module for this article.You can find source code for the library here.
Lets get started.
You need to have NodeJs installed in your machine,if you don't have done yet check this for installation.
Now open up your terminal, follow the steps below,
1.$ cd ~/Desktop
2.$ mkdir arduino_nodejs
3.$ cd arduino_nodejs
4.$ npm init #to make nodejs project, continue pressing enter keep all settings default
5.$ npm install arduino-firmata --save
6.$ sudo rm -r node_modules/serialport #you need to delete as it uses latest serial port but arduino-firmata.js is not updated accordingly
7.$ npm install serialport@3.x #it is the correct version for this library
8.$ node
Now we are all set,
> var ArduinoFirmata = require('arduino-firmata'); //importing library
> var arduino = new ArduinoFirmata(); //making arduino object
> arduino.connect('/dev/cu.usbmodem1421'); //argumant passed here may be different for your machine,check tools tab of your arduino IDE
> arduino.digitalWrite(10, true); // writing high to pin 10 of arduino
> arduino.digitalWrite(13, false); // writing low to pin 10 of arduino
For reading digital pin,
> arduino.pinMode(7, ArduinoFirmata.INPUT); //making pin 7 of arduino input
> console.log( arduino.digitalRead(7) ); //reading pin 7 and displaying it to console
For reading analog pin,
> var analog_value = arduino.analogRead(0); //reading from channel 0 of analog port of arduino > console.log(analog_value); //displaying read analog value(0~1023)
And that's it.Further documentation can be found here.
Enjoy coding arduino in NodeJs.Keep following the site.Another article named Arduino and Bash is coming soon.

No comments:

Post a Comment