title: How to to register the time when the system outputs 1?
body: <p>This code registers incoming data from serial USB port distance tracker and converts the data stream to <code>1</code> or <code>0</code> (if they pass a certain threshold) and adds a Unix timestamp</p>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>import serial
  import datetime
  import time
  
  distance = 5
  
  # Open serial usb port
  ser = serial.Serial('/dev/tty.usbserial', 115200, timeout=0.05)
  
  # converts data to 1/0 
  def convertData(data):
      data = data.decode("utf-8")
      data = data.replace('$BM,','') 
  
      try:
          data = float(data)
          if data &lt;= distance:
          data = 1
          else:
              data = 0
      except ValueError:
          pass
      return data
  
  
  while True:
      data = ser.read(9999999)
      measureunix = float(time.time())
      specData = convertData(data)
      print ('Distance:', specData,'Timestamp(Unix):', measureunix)   
  </code></pre>
  
  <p><strong>Output in terminal:</strong></p>
  
  <pre class="lang-none prettyprint-override"><code>Distance: 1 Timestamp(Unix): 1495381131.521877
  Distance: 1 Timestamp(Unix): 1495381131.572295
  Distance: 1 Timestamp(Unix): 1495381131.626737
  Distance: 1 Timestamp(Unix): 1495381131.677538
  Distance: 1 Timestamp(Unix): 1495381131.73111
  Distance: 1 Timestamp(Unix): 1495381131.786401
  Distance: 1 Timestamp(Unix): 1495381131.839391
  Distance: 0 Timestamp(Unix): 1495381131.889872
  Distance: 0 Timestamp(Unix): 1495381131.940595
  Distance: 0 Timestamp(Unix): 1495381131.991894
  Distance: 0 Timestamp(Unix): 1495381132.043311
  Distance: 0 Timestamp(Unix): 1495381132.097168
  Distance: 0 Timestamp(Unix): 1495381132.149091
  Distance: 0 Timestamp(Unix): 1495381132.200407
  Distance: 0 Timestamp(Unix): 1495381132.25372
  Distance: 0 Timestamp(Unix): 1495381132.306592
  </code></pre>
  
  <p><strong>Problem:</strong></p>
  
  <p>As for the next step- I'm not sure how to do this, but I want to setup a counter that starts counting when the output is (1), continues that until there are two successive(0), then stops counting and prints out the time spent counting <code>(time_of_last(1)-time_of_first(1))</code> divided by the number of <code>(1)</code>'s and waits until the next <code>(1)</code> and starts it again.</p>
  
  <p><strong>Background:</strong> </p>
  
  <p>I'm am trying to build a system that uses distance tracking laser to measure speed of rotating disc (disc has holes with a set diameter). So the laser would register spinning and it would be possible to understand the angular velocity and angle of the rotating disc</p>
  
  <p>Perhaps there is a better way to do any of this, I'm not sure.</p>