Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. const SerialPort = require('serialport');
  2. const Readline = require('@serialport/parser-readline')
  3.  
  4. // Set the com port to use
  5. const ARDUINO_COM_PORT = "COM3";
  6.  
  7. // Setup the serial port (port will auto open)
  8. const arduinoSerialPort = new SerialPort(ARDUINO_COM_PORT, { baudRate: 9600 });
  9. const arduinoParser = arduinoSerialPort.pipe(new Readline({ delimiter: '\r\n', encoding: 'utf8' }))
  10.  
  11. // Tells you when the port is open
  12. arduinoSerialPort.on('open', function() {
  13. console.log('Serial Port ' + ARDUINO_COM_PORT + ' is opened.');
  14. });
  15.  
  16. // Tells you when data arrives from the parser (so a line at a time)
  17. arduinoParser.on('data', function(data) {
  18. // Assume we sent data as a comma seperated string
  19. // like this, so that data == "123,456,789"
  20.  
  21. // Split the numbers based on a comma delimeter into an array
  22. const values = data.split(',');
  23.  
  24. // Make sure we have the number of values we expect
  25. if (values.length === 3)
  26. {
  27. // Get data
  28. const sensorA = values[0];
  29. const sensorB = values[1];
  30. const sensorC = values[2];
  31.  
  32. // Do something...
  33. console.log(`A: ${sensorA}, B: ${sensorB}, C: ${sensorC}`);
  34. }
  35. else
  36. {
  37. // Not the right number of values - panic!
  38. console.warn("Panic!")
  39. }
  40. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement