首页 > 解决方案 > 将字节数组或字符串值转换为 P5.js 中的浮点数(基于 JavaScript)

问题描述

我已经成功地使用这个 - GitHub - p5-serial/p5.serialport:P5.js 库的串行端口 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
    

arduino中的原始数据 P5.js 中的字符串数据 转换为浮点数后的 NaN 转换值数组 - 很多 NaN 未经转换的字符串数据数组

标签: javascriptp5.jsdata-conversion

解决方案


如上一张图片所示,出现了空字符串或空值。在进行转换之前,我只需要对其进行检查。

感谢所有评论者。

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

     }
   }
  }

推荐阅读