将字节数组或字符串值转换为 P5.js 中的浮点数(基于 javascript)

Converting byte array or String value to float in P5.js (javascript based)

我已经成功地在 P5.js sketch 中使用这个获取串口数据 - GitHub - p5-serial/p5.serialport: Serial Port API 和 p5.js 库的服务器作为字节数组或字符串值。

当我尝试使用 float() 将字符串转换为浮点类型时 – 我得到了很多不应该出现的 NaN 值,因为数据是数字。

或者,我然后尝试从串行端口获取数据作为字节数组。 我找不到将此数组转换为我在 P5.js 中的原始浮点值的方法。

关于如何将字节数组转换为浮点数或在将字符串转换为浮点数时避免获得 NaN 的任何想法?

感谢您的宝贵时间和帮助。谢谢。

我尝试转换的代码:

  1. 从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
  1. 从字节数组到浮点数

    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);

     }
   }
  }