title: How to time interval between event in lua
body: <p>I am writing a simple script in lua. If the LED is on, it will increment the counter by 1. If the led is off for more than 1 seconds, it reset the counter. </p>
  
  <p>So how exactly do we time event like that in lua ?</p>
  
  <p>This is what i have and been testing multiple ways so far. </p>
  
  <pre><code>function ReadADC1()
      local adc_voltage_value = 0
      adc_voltage_value = tonumber(adc.readadc()) * 2 -- 0.10 --get dec number out of this -- need to know where package adc come from
      --convert to voltage
      adc_voltage_value = adc_voltage_value *0.000537109375 --get V
      adc_voltage_value = math.floor(adc_voltage_value *1000 +0.5) --since number is base off resolution
  
      --print (adc_voltage_value)
      return adc_voltage_value
  
  end
  -- end of readADC1() TESTED
  
  function interval()
  local counter1 =0 
  ledValue = ReadADC1()
  if (ledValue &gt;= OnThreshHold) then
      ledStatus = 1
      t1=os.time()
  else
      ledStatus = 0
      t2 = os.time()
  end
  
  --counter1 =0
  for i=1,20 do
  if (ledStatus == 1) then -- if led is off for more than 1 second, reset counter = 0
  counter1 = counter1 + 1
  elseif ((ledStatus ==0 and ((os.difftime(os.time(),t2)/100000) &gt; 1000))) then -- increment counter when led is on
  counter1 = 0
  
  end
  end
  print (counter1)
  </code></pre>
  
  <p>end
  I know for sure the logic for interval is wrong since os.time return a huge number (i assume it in psecond instead of second).</p>
  
  <p>Any suggest or solution is welcome. I tried vmstarttimer and vmstoptimmer before this but not sure how it work.</p>
  
  <p>EDIT:</p>
  
  <pre><code>function counter()
  
      local ledValue = ReadADC1()
          local t1 = os.clock()   
          while true do
              local t2 = os.clock()
              local dt = t2 - t1
              t1 = t2
  
              if ((ledValue &lt; OnThreshHold) and (dt &lt; 1)) then -- if led is off for less than 1 second
                  ledCounter = ledCounter + 1
              elseif ((ledValue &lt; OnThreshHold) and (dt &gt; 1)) then-- if led is off for more than 1 second
                  ledCounter = 0;
              else
                  ledCounter = ledCounter
              end
              print (ledCounter)
          end
  
  end
  </code></pre>
  
  <p>Ultimately, it will be return ledCounter instead of print counter since I will plug the value of counter to another function that will print a message correspond to the number of counter </p>