Parsing Data Streaming dari Arduino ke NodeJS Server

Kode Arduino :

// Potmeter vars
const int analogInPin = A0;
int sensorValue = 0; // value read from the potmeter
int prevValue = 0; // previous value from the potmeter
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);

}

// the loop routine runs over and over again forever:
void loop() {
// Potmeter
sensorValue = analogRead(analogInPin);
// read the analog in value:
if(prevValue != sensorValue){
Serial.print("B"); // begin character
Serial.print(sensorValue*5);
Serial.print(",");
Serial.print(sensorValue);
Serial.println("E"); // end character
prevValue = sensorValue;
}
delay(50); // give the Arduino some breathing room.
}

Kode Server NodeJS (server.js)


var serialport = require("serialport");
var SerialPort = serialport.SerialPort;

var receivedData ;
var sendData;
var serialPort = new SerialPort("COM6", { // Menggunakan COM 6
baudrate: 9600,
parser: serialport.parsers.readline("\n")
});

serialPort.on("open", function () { // Komunikasi serial dibuka
console.log('open');

serialPort.on('data', function(data) { //Menerima dan Mengirim data ke Arduino


receivedData += data.toString();
//console.log(receivedData);

if (receivedData .indexOf('E') >= 0 && receivedData .indexOf('B') >= 0) {
sendData = receivedData .substring(receivedData .indexOf('B') + 1, receivedData .indexOf('E'));
receivedData="";
k=sendData.split(",");
var a=k[0];
var b=k[1];
console.log("nilai A ="+a);
console.log("nilai B ="+b);

}
});
});

 

 

phonegap16

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *