如何使用 php 从连接到我的服务器(运行 kali linux 的旧笔记本电脑)上的 COM 端口的 arduino 读取串行数据,以便我可以在网页上显示数据?
我读过有关同一问题的其他问题,所有这些问题要么超级复杂,要么需要 php-serialhttps://github.com/Xowap/PHP-Serial https://github.com/Xowap/PHP-Serial(这仅返回一堆我似乎无法修复的错误)。实际上,我确实设法用 C# 只需几行代码就可以读取串行端口(在 Visual Studio 中,见下文)。 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);
}
解决方案(使用 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;
}
}
}
确保使用 parser.on() 否则记录的数据有时会在字符或数字上分割。例如“31”有时会变成“3”和“1”