简体   繁体   中英

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

I have been successful in getting serial data in P5.js sketch using this - GitHub - p5-serial/p5.serialport: Serial Port API and Server for p5.js library as either byte array or string values.

When I tried converting string to float type using float() – I get a lot of NaN values which shouldn't be coming since data is numerical.

Alternatively, I then tried getting data from serial port as byte array. I can't find a way to convert this array to my original float value in P5.js.

Any ideas on how to convert byte array to float or avoid getting NaN when converting string to float?

Appreciate your time and help. Thanks.

Codes I have tried for conversion:

  1. From String to float, I used

    let incomingData; let dataValue; incomingData = serial.readStringUntil('\n'); dataValue = float(incomingData); //standard method in P5.js -- returns NaN values

I also tried parseFloat() -- https://www.geeksforgeeks.org/javascript-parsefloat-function/

  dataValue = parseFloat(incomingData);
  //again returns maximum values as NaN
  1. From byte array to float

    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 未经转换的字符串数据数组

As seen in the last image, there were empty strings or null values coming. I just had to put a check for it before doing the conversion.

Thanks to all the commenters.

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

     }
   }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM