Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Software-defined GPIOs / GPIO hooks#245

RenaKunisaki started this conversation inIdeas
Discussion options

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_gpioRead_mcp and get data from the I/O expansion. Thus we can use expansions, virtual GPIOs, remote connections, etc transparently with libraries that expect to use normal GPIOs.

Of course this example only demonstrates reading (and assumes Encoder's constructor doesn't touch its GPIOs, else we could usenew instead), but the same would apply to other operations.

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.

You must be logged in to vote

Replies: 0 comments

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Ideas
Labels
None yet
1 participant
@RenaKunisaki

[8]ページ先頭

©2009-2025 Movatter.jp