如何使用php从连接到服务器(运行kali linux的旧笔记本电脑)的COM端口的arduino中读取串行数据,以便可以在网页上显示数据?
我已经阅读了有关同一问题的其他问题,所有这些问题要么都非常复杂,要么需要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”
答案 0 :(得分:0)
我有一个Raspberry Pi3,并且我正在使用python做类似的事情。我假设您可以使用当前设置运行python,但我将与您共享脚本。
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
有了它,您会注意到它实际上是发布到一个php脚本的,从那里可以捕获所需的数据。您只需要在此脚本中更改“端口”设置,就可以了。该脚本还将数据打印到屏幕上。
该脚本当前托管在这里:https://github.com/vrdriver/Serial-PI-thon