2

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"

Anton Broos
  • 37
  • 1
  • 5

1 Answers1

0

I have a Raspberry Pi3, and I'm doing a similar thing using python. I'm going to assume that you can run python with your current setup, but I'll share my script with you.

import serial
import time
import csv
import traceback
import datetime
import requests

port = '/dev/serial/by-id/usb-Prolific_Technology_Inc._USB-Serial_Controller_D-if00-port0'
#port = '/dev/ttyUSB0'
baud = 9600

ser = serial.Serial(port, baud, timeout=1)
ser.flushInput()

print(ser.name)

oldline = []
a = 0
while (a == 0):
    try:
        line = ser.readline()                 # read bytes until line-ending
        line = line.decode('UTF-8','ignore')  # convert to string
        #line = line.rstrip('\r\n')            # remove line-ending characters

        split_line = line.splitlines()

        if oldline != split_line:      
            with open("test_data.csv","a") as f:
                for item in split_line:
                    print (item)
                    x = datetime.datetime.now()

                    # You can write to a text/CSV file.
                    #writer = csv.writer(f,delimiter=",")
                    #writer.writerow([x.strftime("%c"), item])

                    # #You can also send the data to a website/database for processing elsewhere
                    payload = {'pager_message': item}
                    r = requests.post("https://yoursever.com/file_to_post_to.php", data=payload)

                    #Show what the server responded with
                    print(r.text)

        oldline = split_line


    except Exception:
        traceback.print_exc()
        print("exiting")
        #print("Keyboard Interrupt")
        break

With it, you'll notice that it actually POSTS to a php script, which from there, you will be able to capture the data you need. You'll just need to change the "port" settings in this script and you should be right to go. This script also prints out the data to screen.

The script is currently hosted here: https://github.com/vrdriver/Serial-PI-thon

vr_driver
  • 1,867
  • 28
  • 39