[英]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.