1

What I'm trying todo: I'm trying to have an arduino send data over serial to a node server. The node server then parses that data as JSON, and uses it to display info (say a temperature, or time, button press, etc.) I have all of this working, however not perfectly. The data seems to be coming in after huge delays rather than every second. It also seems to be random, as I'll get roughly three objects one time, then maybe ten the next. The arduino is set to send it's data every two seconds, and its been tested. Meaning the information displayed practically in real time when I tested it in the console. (see serial-test.js) I believe it has something to do with the JSON parser and server running on the same script. I tried to use a promise but I doubt that would fix it. I'm new-ish so apologies for any mistakes.

PS: express had to be required twice, not sure why, I can see it's app and express but when I adjusted everything to just one require, it all broke so I left it.

PPS: Just tried parsing the data clientside, it did not appear to solve the issue.

I'm using node SerialPort to get the data from the arduino; node HTTP, node Express, and node Socket.io for the server.

Arduino Code: (Arduino nano/ ATMega328p old bootloader)

boolean blah = true;
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
  thatFunction();
}

void thatFunction(){
  if(blah){
    Serial.println("{\"state\": \"GOOD\", \"name\": \"thing1\"}");
    blah = false;
  } else {
    Serial.println("{\"state\": \"BAD\", \"name\": \"thing2\"}");
    blah = true;
  }
}

Server JS (Serverside?)

const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
const port = new SerialPort('COM4', { baudRate: 9600 });
const debugMode = false;

let str;
let parser = new Readline();
port.pipe(parser);

// Server 
const express = require('express')
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

// Needed to fix the index.html not finding the CSS file.
// Files must be in the folder 'public'
app.use(express.static('public'));

app.get('/', function(req, res){
  res.sendFile(__dirname + '/public/');
});

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

http.listen(8000, function(){
  console.log('listening on *:8000');
});


// Parser is too slow!?? Maybe it can't work along side the server..
// Parsed Serial Data being 'emitted' to the socket.io server. main.js listens for those emits, and displays the info.
parser.on('data', function (data) {
  str = JSON.parse(data); //Then parse it
  console.log(str);
  io.emit('parsed-data', str);
});

Main JS (Clientside?)

let dataDisplay = document.getElementById("woop");
let socket = io();

socket.on('connect', function () {
  socket.on('parsed-data', function (json) {
    console.log(json);
    dataDisplay.innerText = json.state;
  });
});

Index

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Serial Port Data Viewer</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="./styles/main.css" />
</head>
<body>
  <h1 id="woop"></h1>

  <script src="/socket.io/socket.io.js"></script>
  <script src="./javascript/main.js"></script>
</body>
</html>

Serial-test

// Node serial port listener
const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
const debugMode = true;
const port = new SerialPort('COM4', { baudRate: 9600 });
let parser = new Readline();
let str;
port.pipe(parser);

SerialPort.list((err, ports) => {
  console.log(ports);
})

parser.on('data', function (data) {
  str = JSON.parse(data); 

  if (debugMode) {
    console.log('Data:', data);
    if (str.state == "GOOD") {
      console.log(str.name);
      // process.stdout.write("\u001b[2J\u001b[0;0H");
      console.log("\x1b[32m%s\x1b[0m", str.state);
    } else if (str.state == "BAD") {
      console.log(str.name);
      // process.stdout.write("\u001b[2J\u001b[0;0H");
      console.log("\x1b[31m%s\x1b[0m", str.state);
    }
  }
});

Not too sure where else to look at this point, and I feel like I've exhausted every possible google search I can think of. I appreciate any help I can get!

Sources I've checked for info:

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
fr-Dmli
  • 183
  • 1
  • 1
  • 10

0 Answers0