• Hi,

    Finally I have bought some hardware to my espruino boards and I have a question:

    I started with code from distance sensing robot:

    var TRIG = A0; // ultrasonic trigger
    var ECHO = A1; // ultrasonic echo signal
    var MOTORS = [A3,A2,B10,B11]; // pins for the motors
    
    var t1 = 0;
    var dist = 0;
    var inManouver = false;
    
    // Get the distance from the sensor
    setWatch(function(e) { t1=e.time; }, ECHO, { repeat:true, edge:'rising'  });
    setWatch(function(e) { var dt=e.time-t1; dist = (dt*1000000)/57.0; },  ECHO, { repeat:true, edge:'falling' });
    // 20 times a second, trigger the distance sensor
    setInterval("digitalPulse(TRIG,1, 10/1000.0)",50);
    

    i'm trying to make for e.g.

    Led1 on if distance sensing between 10 and 20 cm
    Led2 on if 20 and 50 cm
    Led3 ......

    tried with switch (case) and multiplue ifs always fail, what is the best way to achive this functionality?

    I have also some general question about some book / tutorial on Java for total newbie before making some serious code.

    Thanks in advance for help.

    BR
    Max

  • My thought would be

    setWatch(function(e) { var dt=e.time-t1; dist = dt*1000000/57.0; updateLed();},  ECHO, { repeat:true, edge:'falling' });
    
    
    function updateLed() {
    
    if (dist<10)  { //those are cm right? I've never used my HC-SR04's...
    digitalWrite(LED1,1);
    digitalWrite(LED2,0);
    digitalWrite(LED3,0);
    } else if (dist<20) {
    digitalWrite(LED1,0);
    digitalWrite(LED2,1);
    digitalWrite(LED3,0);
    } else {
    digitalWrite(LED1,0);
    digitalWrite(LED2,0);
    digitalWrite(LED3,1);
    }
    }
    

    Maybe cleaner:

    var ledpins=[LED1,LED2,LED3]; //declare with the globals
    
    //instead of the three digital writes, you can do:
    digitalWrite(ledpins,[1,0,0]); 
    
    

    (code is untested)
    Edit: Code block that already, damnit!

    (that's assuming you've checked that the dist values you're getting are sensible)

About

Avatar for DrAzzy @DrAzzy started