title: Python Hall Sensor Monitor - Too High CPU Usage
body: <p>I'm doing a project where I need to monitor several hall sensors for a position encoding. The logic is pretty simple, but the digital signal is fast: it may have up to 350 position changes per second.</p>
  <p>I was hoping I could simply write a hall sensor monitor program watching the GPIOs but it appears that these programs consume quite a bit of CPU if I monitor at the necessary frequency. I had hoped suspending the CPU between every poll would help, but it doesn't seem to make much difference.</p>
  <p>Here's the polling loop from what I'm currently doing. It &quot;works&quot;, but the CPU usage is far too high. I'm running this on a process that shares the &quot;position&quot; variable with other processes on a memory-mapped file.</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>REFRESH_RATE = .0005
  
  while True:
      new_p1_state = GPIO.input(hall_p1)
      new_p2_state = GPIO.input(hall_p2)
  
      if new_p1_state != p1_state or new_p2_state != p2_state:
          if p1_state == GPIO.HIGH:
              if new_p2_state == GPIO.HIGH:
                  position -= 1
              else:
                  position += 1
          else:
              if new_p2_state == GPIO.LOW:
                  position -= 1
              else:
                  position += 1
  
          p1_state = new_p1_state
          p2_state = new_p2_state
  
      time.sleep(REFRESH_RATE)</code></pre>
  </div>
  </div>
  </p>
  <p>Can anybody recommend a more efficient way to do this? Should I avoid python and use something faster? If so what?</p>