如何使用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”
我有一个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脚本的,从那里可以捕获所需的数据。您只需要在此脚本中更改“端口”设置,就可以了。该脚本还将数据打印到屏幕上。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。