Leonardo switchbox, polling vs Interupts

There is an issue with shifting <<16 a 16bit integer.

It needs to be cast to a uint32_t before shifting.

Since these are return values from functions, I don't know the best syntax to use.

You can try this to see if it works
int32_t pins = (uint32_t)mcp1.readGPIOAB() << 16 | mcp2.readGPIOAB();

This should work if the cast of the function return does not.

uint16_t pins1 = mcp1.readGPIOAB();
uint16_t pins2 = mcp2.readGPIOAB();

uint32_t pins = (uint32_t)pins1 << 16 | pins2;
1 Like

Sorry @downloadkid I wasn't able to test the code and I missed something important that @cattledog pointed out.

Try this line:

uint32_t pins = mcp1.readGPIOAB() << 16UL | mcp2.readGPIOAB();

@PaulRB and @cattledog thank you again.

cattledog your suggestion worked but I needed to change the order of the mcp boards as it started reading mcp2 before mcp1.

int32_t pins = (uint32_t)mcp2.readGPIOAB() << 16 | mcp1.readGPIOAB() ;

PaulRB i did try your suggestion but didn't seem to work, similar as before , one board or the other.

Either way, wow, thank you both for your patience and help. Are you both happy for me to close this off and mark as solved - there is so much info and education in this post, I'm sure it will be a useful reference to many people. that's on you guys!!

I didn't test it myself and was unsure if it would work. I guess shifting a 16-bit value by a 32-bit value doesn't work like addition or multiplication because the result isn't 32 bits.

If you have any other questions about how I shortened the code, please ask on this forum topic. I want you to be capable of doing similar in future.

That's because with the shifting of mcp1 to the highest order bits, mcp2 values were in the lower order bits.

The reading routine with the for loop starts with bit 0 which would have been mcp2 bits.

for (uint8_t p = 0; p < numToggles; p++) {
      if (bitRead(pins, p) != bitRead(prevPins, p)) {
        Joystick.setButton(firstToggle + p, !bitRead(pins, p));
      }

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.