DAQ Arduino with NodeJS serialport

In this tutorial, I will make a Data Acquisition (DAQ) procedure between PC and Arduino. PC (with NodeJS) will send command to Arduino via serialport, then Arduino will send response to PC so that PC can plot the data.

At code line of Arduino, I make the main loop do nothing by using serialEvent to listen command. If command is “gene”, Arduino will send 2 parameters tempe_data and humid_data with JSON format. The reason to random generate 2 parameters is I am too lazy to connect the DHT22.

test_serialport_b.ino


/*
 * Date: Mon, 12/06/2017
 * Desc: Arduino and NodeJS serialport
 * Info: Random generator temperature and humidity
 * to simulate DHT22, JSON format
 * only response data when receive request
 */
// used for generating data
double tempe_data;
double humid_data;
// used for serial buffering
#define TERM_CHAR '\n'
#define BUF_LEN 16
int i = 0;
char incomingChar; 
char buf[BUF_LEN];
// used pinLED for test mode
int pinLED = 13;

void setup() {
 delay(1000);
 // Initialize serial port
 Serial.begin(9600);
 //Serial.begin(115200);

// Initialize random generator
 randomSeed(analogRead(3)*1234);

// Initialize pinLED for test mode
 pinMode(pinLED, OUTPUT);
 digitalWrite(pinLED, LOW);
}

void loop() {
 // do nothing
}

double generate_data(long offset, long min_range, long max_range){
 // data = offset + rand, for example if range = [0,4] offset will be 2, rand will be 2
 long randParam = random(min_range*100, max_range*100);
 double data = (double)offset + (double)randParam/100;
 return data;
}

// generate random temperature and humidity
// send with JSON format
void procedure(){
 // generate
 tempe_data = generate_data(2, -2, 2);
 humid_data = generate_data(3, -3, 3);
 // send
 Serial.print(F("{\"CH1\": "));
 Serial.print(tempe_data);
 // create a fake CH2 to test JSON
 Serial.print(F(", \"CH2\": "));
 Serial.print(humid_data);
 Serial.println(F("}"));
}

void serialEvent() {
 // when characters arrive over the serial port...
 if (Serial.available()) {
 // wait a bit for the entire message to arrive
 delay(100);
 // clean buffer and index
 memset(buf,'\0',BUF_LEN); 
 i = 0; 
 // read all the available characters
 while (Serial.available() > 0) {
 incomingChar = (char) Serial.read();
 if(incomingChar != TERM_CHAR && i != BUF_LEN) 
 buf[i++] = incomingChar;
 else
 break;
 delay(1); // wait for another byte 
 }
 // Activate function on right code
 if(String(buf) == "10"){
 digitalWrite(pinLED, HIGH);
 } else if(String(buf) == "20"){
 digitalWrite(pinLED, LOW);
 } else if(String(buf) == "gene"){
 procedure();
 } else{
 // to be continued
 } 
 }
}

If you ask what is the role of pinLED and command "10" and "20", it is for testing. What is the character 'F' in Serial.print(F("{\"CH1\": "))? It is saving buffering bytes for transmitting serial data. What is the flaw of the code? It still does not make Arduino sleep and wake up.

About NodeJS role, I use express, socket.io and ejs to make a web server. I use serialport to receive and transmit data. I use chart.js to plot the data. What is the flaw of the code? The DAQ only happens in my PC, it cannot be accessed by another PC or my smartphone. Here comes the code

index.js


var express = require("express");
var app = express();
app.use(express.static("public"));
app.set("view engine", "ejs");
app.set("views", "./views");

var server = require("http").Server(app);
var io = require("socket.io")(server);
server.listen(3000);

// Using serialport to communicate with COM3
var serialport = require("serialport");
var mySerial = new serialport("COM3", {
 baudrate: 9600,
 parser: serialport.parsers.readline("\n")
});

mySerial.on("open", function(){
 console.log("COM3 is opened.");
});
// close serialport
mySerial.on("close", function(){
 console.log("COM3 is closed.");
});
// listening data on CH1
mySerial.on("data", function(JSON_data){
 // var CH1_data = JSON.parse(JSON_data).CH1;
 // var CH2_data = JSON.parse(JSON_data).CH2;
 // console.log(CH1_data + "----" + CH2_data);
 // sending COM data to client
 // io.sockets.emit("com-data",CH1_data);
 io.sockets.emit("com-data",JSON_data);
});

// Host server// SocketIO listening for connection and disconnection
io.on("connection", function(socket){
 console.log("Connecting client id: " + socket.id);
 socket.on("disconnect", function(){
 console.log("Client id: " + socket.id + " has disconnected");
 });
});

// Service for loading
app.get("/", function(req, res){
 res.render("trangchu");
});

// Testing serialport transmit every 2 seconds
var auto_counter = 0;
setInterval(function(){
 console.log(auto_counter);
 //mySerial.write(String(auto_counter));
 mySerial.write("gene");
 mySerial.write("\n"); // Eliminate
 auto_counter++;
 if(auto_counter == 21){
 auto_counter = 0;
 }
},2000);

trangchu.ejs


<html>
<head>
<title>COM data</title>

http://jquery.js
http://socket.io/socket.io.js
http://js/Chart.js
http://js/Chart.min.js

</head>

<body>
COM3. This is my localhost 192.168.1.101:3000

<h2 id="noidung"></h2>
 
</body> //Chart.defaults.global.responsive = true; //var ctx = document.getElementById("myChart"); var ctx = document.getElementById("myChart"); var counter; var myLineChart; createGraph() //--- declare function function createGraph(){ counter = 0; myLineChart = new Chart(ctx, { type: 'line', data: { labels: [], datasets: [{ label: ['Temperature'], data: [], backgroundColor: [ 'rgba(255, 99, 132, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)' ], borderWidth: 1 }, { label: ['Humidity'], data: [], backgroundColor: [ 'rgba(54, 162, 235, 0.2)' ], borderColor: [ 'rgba(54, 162, 235, 1)' ], borderWidth: 1 }] }, options: { animation: { duration: 0, // general animation time }, scales: { yAxes: [{ ticks: { max: 6, beginAtZero:true }, stacked: false }] }, elements: { line: { tension: 0, // disables bezier curves } } } }); } // goi dien len server var socket = io("http://localhost:3000"); // client listening socket.on("com-data", function(data){ // $("#noidung").html(data); // console.log(counter + "-----" + data); var obj = JSON.parse(data); $("#noidung").html(obj.CH1 + " ----- " + obj.CH2); console.log(counter + "-----" + obj.CH1); counter++; myLineChart.data.labels.push(counter); myLineChart.data.datasets[0].data.push(obj.CH1); myLineChart.data.datasets[1].data.push(obj.CH2); myLineChart.update(); if(counter > 10){ myLineChart.destroy(); //counter = 0; createGraph(); } // if(counter = 20){ // counter = 0; // myLineChart.destroy(); // } else{ // counter++; // myLineChart.data.labels.push(counter); // myLineChart.data.datasets[0].data.push(data); // myLineChart.update(); // } }); $(document).ready(function(){ }); </html>

To use chart.js, in the folder public there will be a folder called js containing Chart.js and Chart.min.js (Chart will capital C). Note that I used COM3

Connect Arduino with loaded program and node index.js, you will see the result:

DAQ_nodejs

There is still some residual in my code. OK my bad. I am too lazy to delete the residual.

The biggest question in my head now is how to publish it globally so that everyone can see the chart of random generated parameters? I think about mongoDB and Heroku may work.

See you.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s