[英]Converting byte array or String value to float in P5.js (javascript based)
我已经成功地使用这个在 P5.js 草图中获取串行数据- GitHub - p5-serial/p5.serialport: Serial Port API and Server for p5.js library 作为字节数组或字符串值。
当我尝试使用 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
如上图所示,出现了空字符串或 null 值。 在进行转换之前,我只需要对其进行检查。
感谢所有评论者。
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.