javascript - 将字节数组或字符串值转换为 P5.js 中的浮点数(基于 JavaScript)
问题描述
我已经成功地使用这个 - GitHub - p5-serial/p5.serialport:P5.js 库的串行端口 API 和服务器作为字节数组或字符串值在 P5.js 草图中获取串行数据。
当我尝试使用 float() 将字符串转换为浮点类型时——我得到了很多不应该出现的 NaN 值,因为数据是数字的。
或者,然后我尝试从串行端口获取数据作为字节数组。我找不到将这个数组转换为我在 P5.js 中的原始浮点值的方法。
关于如何将字节数组转换为浮点数或避免在将字符串转换为浮点数时获得 NaN 的任何想法?
感谢您的时间和帮助。谢谢。
我尝试转换的代码:
从String到float,我用过
let incomingData; let dataValue; incomingData = serial.readStringUntil('\n'); dataValue = float(incomingData); //standard method in P5.js -- returns NaN values
我也试过 parseFloat() - https://www.geeksforgeeks.org/javascript-parsefloat-function/
dataValue = parseFloat(incomingData);
//again returns maximum values as NaN
从字节数组到浮点数
let incomingBytes = []; let dataValue; incomingBytes = serial.readBytesUntil('\n'); dataValue = dataView.getFloat64(bytebuffer); // This javascript method is not supported by P5.js it seems
解决方案
如上一张图片所示,出现了空字符串或空值。在进行转换之前,我只需要对其进行检查。
感谢所有评论者。
let incomingData; //incoming serial value is stored in this variable
let temparray = [1000]; //temporary array used in updating final array
let plot_from_here = [1000]; //final array of values to plot
function setup(){}
function draw(){}
function serialEvent() {
if(serial.available()>0){
incomingData = serial.readStringUntil('\n'); //read string until next line
if(incomingData != ""){
incomingData = trim(incomingData); //trim white spaces
arrayCopy(temparray,0, temparray,1,999); //Copy value from index 0 to index 1
temparray[0]= float(incomingData); //Update index 0 of temparray for the incoming value -- the value is converted to float from string type
plot_from_here = temparray; //update values in final array
print(plot_from_here);
}
}
}
推荐阅读
- javascript - for循环中的随机延迟setTimeout
- autodesk-forge - 有没有办法在查看器中使用 BoxSelection 扩展启用部分选择
- java - 您可以垂直打印生成的随机数(10 个整数)一维数组吗?
- python - Pytest 测试套件在 GitHub Actions 上随机出现错误,无需更改
- python - 从 csv 文件动态创建数据框
- javascript - 如何根据两个过滤器过滤对象数组?
- java - 在 Java 中使用字符串创建一个简单的计算器
- python - 刮了
- 通过 Python 的 BeautifulSoup 在网站中的产品详细信息,但无法将其导出到 csv
- java - Checkstyle 错误:de-lomboked code 超过 7 个参数(找到 20 个)
- jsf - 根据 ui:repeat 列表中特定复选框元素的值禁用 inputTextarea 元素?