1

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.

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.

Here’s the polling loop from what I’m currently doing. It “works”, but the CPU usage is far too high. I’m running this on a process that shares the “position” variable with other processes on a memory-mapped file.

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)

Can anybody recommend a more efficient way to do this? Should I avoid python and use something faster? If so what?