Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork130
Software-defined GPIOs / GPIO hooks#245
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
Consider something like: #defineNUM_SW_GPIOS 50 //arbitrary number#defineNUM_GPIOS (NUM_HW_GPIOS + NUM_SW_GPIOS)typedefint (*swGpioReadFunc_t)(intpin);swGpioReadFunc_treadFunc[NUM_GPIOS];int_readHwGpio(intpin) {//whatever hardware-specific code here}int_readDummyGpio(intpin) {return0;}void_initGpios() {//would be called at some point during bootfor(inti=0;i<NUM_GPIOS;i++) {if(i<NUM_HW_GPIOS)readFunc[i]=_readHwGpio;elsereadFunc[i]=_readDummyGpio; }}intgpioRead(intpin) {returnreadFunc[pin](pin);}swGpioReadFunc_tgpioSetReadFunc(intpin,swGpioReadFunc_tfunc) {swGpioReadFunc_told=readFunc[pin];readFunc[pin]=func;returnold;} Now, suppose you're using a library that handles some device for you such as a rotary encoder. It expects to be told which pins the encoder is connected to: EncodermyEncoder(PIN_ENCODER1,PIN_ENCODER2); But due to space constraints, you don't want to connect the encoder to a GPIO. Instead, you want to use an I/O expander such as the MCP23017. That means you need to modify the Encoder library. But with this change, you don't! #definePIN_MCP_BASE 40 //pin 0 of MCP23017 is virtual GPIO40MCP23017mcp(PIN_MCP_BASE,whatever);#definePIN_ENCODER1 (PIN_MCP_BASE+0)#definePIN_ENCODER2 (PIN_MCP_BASE+1)EncodermyEncoder(PIN_ENCODER1,PIN_ENCODER2);int_gpioRead_mcp(intpin) {//assume this reads one bit; inefficient for simplicity's sake for demoreturnmcp.read(pin-PIN_MCP_BASE);}voidsetup() {gpioSetReadFunc(PIN_MCP_BASE,_gpioRead_mcp);gpioSetReadFunc(PIN_MCP_BASE+1,_gpioRead_mcp);//...repeat for however many pins you want to use} Now when the unmodified Encoder library attempts to read GPIOs 40 and 41, it will actually call Of course this example only demonstrates reading (and assumes Encoder's constructor doesn't touch its GPIOs, else we could use As a bonus, it would even be possible to hook the real hardware GPIOs, eg for debugging when something is accessing them, inverting their output, remapping them, etc. |
BetaWas this translation helpful?Give feedback.