How can I read the serial data from an arduino connected to a COM port on my server(an old laptop running kali linux) using php, so that I can display the data on a webpage?
I've read other questions about the same problem, all of them are either super complicated or require php-serial https://github.com/Xowap/PHP-Serial (this returns only a bunch of errors i can't seem to fix). I actually did managed to read the serialport with C# in just a few lines of code (in visual studio, see below). How can it be that much harder in php?
C#
using System;
using System.IO.Ports;
namespace UNOtoDB
{
class Program
{
static SerialPort S;
static void Main(string[] args)
{
S = new SerialPort();
S.PortName = "COM4";
S.BaudRate = 9600;
S.ReadTimeout = 2000;
S.Open();
while (true) {
Console.WriteLine(S.ReadLine());
}
}
}
}
Arduino
int Mapped;
int res;
void setup() {
pinMode(A0, INPUT);
Serial.begin(9600);
}
void loop() {
res = analogRead(A0);
Mapped = map(res, 0, 1023, 0, 47); //using a 47Kohm potentiometer
Serial.println(Mapped);
delay(100);
}
Solution (using Node.js)
var serialport = require('serialport');
var Readline = serialport.parsers.Readline;
var parser = new Readline();
var path = '/dev/ttyACM0' ;
var myPort = new serialport(path ,{
baudRate: 9600,
});
myPort.pipe(parser);
parser.on('data', readSerialData);
function readSerialData(data) {
console.log(data);
sleep(1000);
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
make sure you use parser.on() otherwise the data logged will sometimes split on its characters or digits. for example "31" will sometimes become "3" and "1"