bio photo

Email

##Lab: Serial Communication with Node

Modified to take in value from single sensor:

//ARDUINO SKETCH

void setup() {
  Serial.begin(9600);
  Serial.print("0");

}

void loop() {
  if (Serial.available() > 0) {
    char input = Serial.read();
    int sensor = analogRead(A0);
    Serial.println(sensor);
  };

}

//INDEX.JS file

var serialport = require('serialport'),
SerialPort = serialport.SerialPort,
portname = process.argv[2];


//setup port
var myPort = new SerialPort(portname, {
	baudRate: 9600,
	options: false,
	parser: serialport.parsers.readline("\n")
});

myPort.on('open', function(){
	console.log('port is open');
});

myPort.on('close', function(){
	console.log('port is closed');
});

myPort.on('error', function(){
	console.log('there is an error');
});

myPort.on('data', function(data){
	console.log(data);
	myPort.write('x');
});

I get a “port is open” but no values, I checked my connections and receive serial data in the Arduino IDE port (first a “0” and then when I send it a value). But in the console, node doesn’t work.

$ node index.js /dev/cu.usbmodem621
port is open

####Conclusion

Despite the failure, I feel better acquainted with node’s functioning especially its use of callback functions and use of JSON name pair values to configure the serial port.