• Right, just so it's out the way... I've only just pick up JS w/ Espruino and I'm kind of struggling with a simple piece of code:

    const gnd = digitalWrite(B3, 0);
    const pwr = digitalWrite(B4, 1);
    const cw = 1;
    const ccw = 0;
    const dataCW = [];
    const dataCCW = [];
    const dataLength = 36;
    
    
    const getData = (dir, t) => {
    	const solarIn = () => analogRead(A5);
    	const dataRead = () => ((solarIn() * 65536) * 5.0) / 65536;
    	const dataPush = (data) => {
    		data.push(dataRead());
    	};
    
    	const peekVal = () => {
    		if(dir === 1) {
    			for(let i = 0; i < dataLength; i++) {
    				setTimeout(() => {
    					dataPush(dataCW);
    					if(dataCW.length === dataLength) {
    						let peekValCW = Math.max.apply(null, dataCW);
    						let peekValPosCW = () => dataCW.indexOf(peekValCW);
    						return peekValPosCW();
    					}
    				}, i * (t / dataLength));
    			}
    		}
    		else if(dir === 0) {
    			for(let i = 0; i < dataLength; i++) {
    				setTimeout(() => {
    					dataPush(dataCCW);
    					if(dataCCW.length === dataLength) {
    						let peekValCCW = Math.max.apply(null, dataCCW);
    						let peekValPosCCW = () => dataCCW.indexOf(peekValCCW);
    						return peekValPosCCW();
    					}
    				}, i * (t / dataLength));
    			}
    		}
    	};
    	return peekVal();
    };
    
    
    getData(cw, 1000);
    
    

    All I'm trying to do atm is to read a value from a POT(mimicking a future sensor) which then gets stored in an array depending on the two inputs which then would get the position in that array of the greatest value stored... now, all I want is to be able to "see"(print) that value-position, then store it under another const/ let and do something with it...
    In Python this would be something simple like:

     //to see/ print the data for visualisation purposes only:
    print(getData(cw, 1000)) 
    //to store it under another variable:
    var  =  getData(cw, 1000)
    
    

    Now the printing issue is kind of solved in the sense that I can just print the return of that conditional:

    //line 25 or 37
    print(peekValPosCW());
    
    

    But if I'm doing it from where I'm calling the function it's giving me "undefined"... now I get the fact that it's printing undefined because it calls for the print much faster than it takes the function to complete and output something out(at least I'm pretty sure that's what's going on)... but just as a test I've tried using a setTimeout on the print of about 3sec and I'm still getting undefined back which only confused me even more...

  • @Robin Thanks for getting back with all the resources... I'll have a look asap; in the meantime I've managed to get closer to what I wanted using callbacks.
    And yes, new to JS as well... seems to be quite different when compared to Python or C/ C++.

About

Avatar for Robin @Robin started