vpaeder / pymcp2221

A python driver for the Microchip MCP2221/MCP2221A USB 2.0 to I2C/UART protocol converters
https://pypi.org/project/pymcp2221
MIT License
5 stars 2 forks source link

Question how fast can I read GPIO Input pin #3

Closed crbyxwpzfl closed 1 year ago

crbyxwpzfl commented 1 year ago

Hi, this is a general question so please close this if this is unrelated to your driver.

tl;dr

I timed mcp.gpio_read_value(1) and found it to be around 0.002s This seems slow to me compared to a microcontroller or raspberry pi. Is it possible to read the value of the pin quicker? Again I am very grateful for any tips or Info.

full story

I just tried to run a ultrasonic-distance-sensor (HC-SR04) with the mcp2221. I expected the same code form my raspberry to work with the mcp2221.

while True:
    mcp.gpio1_value = True
    time.sleep(0.00001) #  from spec sheet trigger pin high for 0.01ms to init pulse
    mcp.gpio1_value = False

    while mcp.gpio_read_value(0) == False : 
        StartTime = time.time() #  time when pulse is out
        print("GPIO0 False")

    while mcp.gpio_read_value(0) == True : 
        StopTime = time.time() #  time when echo returns
        print("GPIO0 True")

    TimeElapsed = StopTime - StartTime #  time till echo
    distance = (TimeElapsed * 34300) / 2 #  distance is half the roundtrip of the travel time of sound-pulse * speed of sound
    print(distance)

    time.sleep(1) 

But the script gave very wired readings.

Since the Sensor Requires quite fast GPIO operations I timed mcp.gpio_read_value(1) via

while True:
    print()
    Start = time.time()
    print(f"pin1 is {mcp.gpio_read_value(1)} ") 
    Stop = time.time()
    print("time to read pin")
    print(Stop - Start)

this gave this output

pin1 is False 
time to read pin
0.001984119415283203

pin1 is False 
time to read pin
0.0020868778228759766

pin1 is False 
time to read pin
0.0019788742065429688

pin1 is False 
time to read pin
0.0021982192993164062

pin1 is False 
time to read pin
0.003014802932739258

pin1 is False 
time to read pin
0.0029480457305908203

pin1 is False 
time to read pin
0.00273895263671875

pin1 is False 
time to read pin
0.0019137859344482422
...

Perhaps this is the reason why the sensor script does not work spec sheet of HC-SR04

vpaeder commented 1 year ago

You can try the raw command directly like that:

cmd = bytearray(64)
cmd[0] = 0x51
while True:
  mcp.dev.write(cmd)
  value = mcp.dev.read(64)

Since it communicates through HID in 64 byte chunks I assume it won't become lightning-fast though. Also when I read the datasheet you linked to I see that you need to measure pulse widths. If you want precise timings you should rather stick a microcontroller in between the MCP and your chip.

crbyxwpzfl commented 1 year ago

okok I will try the raw command method. Otherwise I try an other sensor which has I2C or use a microcontroller in between like you suggested. Thank you very much!