analogRead(D4) not working in saved program

Posted on
  • On an MDBT42, I'm using analogRead() in a function, called from a main function, called by onInit().
    The analogRead() works just once on the first run and the value is never updated.
    I know the pin voltage changes because it is correctly returned when I do a command line analogRead(D4) while the program is running.
    Any ideas why this might be? I am tending towards a problem with how I’m using onInit(), but even so I am a bit lost…

    Here is the code:

    function readBatt(pin) {
      v = analogRead(pin)*6.6;  // ADC * 3.3 * 2 (for Vbatt/2 divider)
      setLed();
    }
    
    function setLed() {
      if(v < 3) {
        clearInterval();
        setInterval("digitalPulse(D1, 0, [200,50,100,50]);", 10000);
      } else {
        clearInterval();
        setInterval("digitalPulse(D1, 0, [200,50]);", 10000);
      }
    }
    
    function onInit() {
      var v = 0;
      setInterval(function() {
        readBatt(D4);
      }, 10000);
    }
    

    What it does (meant to do) is flash the led twice at intervals if the voltage on D4 falls below 3, otherwise flash the led once at intervals. It's a low battery warning notification I want to add into other programs later. The led flashing functions perform as expected.
    The main loop (at onInit()) is meant to call the routine and update every 10s. The code is saved to flash from the webIDE.

    Thanks in advance for comments...

  • I think the issue is your use of clearInterval(); in setLed - this will clear ALL intervals, including the one calling readBatt. So in reality readBatt will only get called once.

    You probably want:

    var flashInterval;
    function setLed() {
      if (flashInterval) clearInterval(flashInterval);
      if(v < 3) {
        flashInterval = setInterval("digitalPulse(D1, 0, [200,50,100,50]);", 10000);
      } else {
        flashInterval = setInterval("digitalPulse(D1, 0, [200,50]);", 10000);
      }
    }
    
  • That has helped, thank you.
    The change by itself stopped everything from working, but thinking it through I increased the timer in onInit() to 30000ms. (The gotcha I had designed for myself there was that the led flash timer was set to 10 seconds, only to be restarted every 10 seconds, so it never flashed any leds!).
    Now I need to juggle the extra battery drain of flashing a warning led against letting the battery run down without warning.
    Thanks again @Gordon.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

analogRead(D4) not working in saved program

Posted by Avatar for docmathoc @docmathoc

Actions