pat9125.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "pat9125.h"
  2. #include "swspi.h"
  3. #ifdef SWSPI_RPI
  4. // #include <bcm2835.h>
  5. #define DELAY(delay) usleep(delay)
  6. #endif //SWSPI_RPI
  7. #ifdef SWSPI_AVR
  8. #include "Arduino.h"
  9. #define DELAY(delay) delayMicroseconds(delay)
  10. #endif //SWSPI_AVR
  11. unsigned char ucPID1 = 0;
  12. unsigned char ucPID2 = 0;
  13. int pat9125_x = 0;
  14. int pat9125_y = 0;
  15. int pat9125_b = 0;
  16. int pat9125_init(unsigned char xres, unsigned char yres)
  17. {
  18. swspi_init();
  19. ucPID1 = pat9125_rd_reg(PAT9125_PID1);
  20. ucPID2 = pat9125_rd_reg(PAT9125_PID2);
  21. if ((ucPID1 != 0x31) || (ucPID2 != 0x91))
  22. {
  23. return 0;
  24. }
  25. pat9125_wr_reg(PAT9125_RES_X, xres);
  26. pat9125_wr_reg(PAT9125_RES_Y, yres);
  27. return 1;
  28. }
  29. int pat9125_update()
  30. {
  31. if ((ucPID1 == 0x31) && (ucPID2 == 0x91))
  32. {
  33. unsigned char ucMotion = pat9125_rd_reg(PAT9125_MOTION);
  34. pat9125_b = pat9125_rd_reg(PAT9125_FRAME);
  35. if (ucMotion & 0x80)
  36. {
  37. unsigned char ucXL = pat9125_rd_reg(PAT9125_DELTA_XL);
  38. unsigned char ucYL = pat9125_rd_reg(PAT9125_DELTA_YL);
  39. unsigned char ucXYH = pat9125_rd_reg(PAT9125_DELTA_XYH);
  40. int iDX = ucXL | ((ucXYH << 4) & 0xf00);
  41. int iDY = ucYL | ((ucXYH << 8) & 0xf00);
  42. if (iDX & 0x800) iDX -= 4096;
  43. if (iDY & 0x800) iDY -= 4096;
  44. pat9125_x += iDX;
  45. pat9125_y += iDY;
  46. return 1;
  47. }
  48. }
  49. return 0;
  50. }
  51. unsigned char pat9125_rd_reg(unsigned char addr)
  52. {
  53. swspi_start();
  54. DELAY(100);
  55. swspi_tx(addr & 0x7f);
  56. DELAY(100);
  57. unsigned char data = swspi_rx();
  58. swspi_stop();
  59. DELAY(100);
  60. return data;
  61. }
  62. void pat9125_wr_reg(unsigned char addr, unsigned char data)
  63. {
  64. swspi_start();
  65. DELAY(100);
  66. swspi_tx(addr | 0x80);
  67. DELAY(100);
  68. swspi_tx(data);
  69. swspi_stop();
  70. DELAY(100);
  71. }