keybrd library is an open source library for creating custom-keyboard firmware.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

PortRead_MCP23S17.cpp 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include "PortRead_MCP23S17.h"
  2. /*
  3. PortRead_MCP23S17::begin() is not needed because port direction is already configured to input by default.
  4. SPI bus is configured in PortWrite_MCP23S17::begin().
  5. */
  6. void PortRead_MCP23S17::begin(const uint8_t strobeOn)
  7. {
  8. uint8_t pullUp; //bitwise, 1 means internal pull-up resistor enabled
  9. if (strobeOn == LOW) //if active low
  10. {
  11. pullUp = readPins;
  12. }
  13. else
  14. {
  15. pullUp = 0;
  16. }
  17. pinMode(SS, OUTPUT); //configure controller's Slave Select pin to output
  18. digitalWrite(SS, HIGH); //disable Slave Select
  19. SPI.begin();
  20. SPI.beginTransaction(SPISettings (SPI_CLOCK_DIV8, MSBFIRST, SPI_MODE0)); //control SPI bus todo is slow clock needed?
  21. digitalWrite(SS, LOW); //enable Slave Select
  22. SPI.transfer(port.ADDR << 1); //write command
  23. SPI.transfer(port.num); //configure IODIR
  24. SPI.transfer(readPins); //0=output (for LED), 1=input (for read)
  25. digitalWrite(SS, LOW); //enable Slave Select
  26. digitalWrite(SS, HIGH); //disable Slave Select
  27. SPI.transfer(port.ADDR << 1); //write command
  28. SPI.transfer(port.num + 0x0C); //configure GPPU
  29. SPI.transfer(pullUp); //0=pull-up disabled (for LED), 1=pull-up enabled (for read)
  30. digitalWrite(SS, HIGH); //disable Slave Select
  31. //SPI.endTransaction() is not called to release the SPI bus
  32. // because keyboard only has one SPI device.
  33. }
  34. /*
  35. read() returns portState.
  36. */
  37. uint8_t PortRead_MCP23S17::read()
  38. {
  39. uint8_t portState; //bit wise
  40. digitalWrite(SS, LOW); //enable Slave Select
  41. SPI.transfer(port.ADDR << 1 | 1); //read command
  42. SPI.transfer(port.num + 0x12); //GPIO register address to read data from
  43. portState = SPI.transfer(0); //save the data (0 is dummy data to send)
  44. digitalWrite(SS, HIGH); //disable Slave Select
  45. return portState;
  46. }