adxl345.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2021 IOsetting <iosetting(at)outlook.com>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "adxl345.h"
  15. uint8_t xbuf[3];
  16. uint8_t ADXL345_ReadByte(uint8_t addr)
  17. {
  18. ADXL345_CS = 0;
  19. xbuf[0] = addr | 0x80;
  20. xbuf[1] = 0xFF;
  21. SPI_TxRxBytes(xbuf, 2);
  22. ADXL345_CS = 1;
  23. return xbuf[1];
  24. }
  25. uint16_t ADXL345_ReadInt(uint8_t addr)
  26. {
  27. ADXL345_CS = 0;
  28. xbuf[0] = addr | 0xC0;
  29. xbuf[1] = 0xFF;
  30. xbuf[2] = 0xFF;
  31. SPI_TxRxBytes(xbuf, 3);
  32. ADXL345_CS = 1;
  33. return *((uint16_t *)&xbuf[1]);
  34. }
  35. void ADXL345_WriteByte(uint8_t addr, uint8_t dat)
  36. {
  37. ADXL345_CS = 0;
  38. xbuf[0] = addr;
  39. xbuf[1] = dat;
  40. SPI_TxRxBytes(xbuf, 2);
  41. ADXL345_CS = 1;
  42. }
  43. HAL_StatusTypeDef ADXL345_Init(
  44. ADXL345_DataRate_t dataRate,
  45. ADXL345_SPI_Wire_t spiWire,
  46. ADXL345_IntActive_t intLevel,
  47. ADXL345_DataResolve_t resolve,
  48. ADXL345_DataAlignment_t alignment,
  49. ADXL345_G_Range_t range)
  50. {
  51. if (ADXL345_ReadByte(ADXL345_REG_DEVID) == ADXL345_DEVICE_ID)
  52. {
  53. ADXL345_WriteByte(ADXL345_REG_BW_RATE, dataRate);
  54. ADXL345_WriteByte(ADXL345_REG_DATA_FORMAT,
  55. spiWire|intLevel|resolve|alignment|range);
  56. ADXL345_WriteByte(ADXL345_REG_POWER_CTL, 0x08); // BIT3=0/1:(测量模式/待机模式);BIT2=0/1:(工作/休眠);
  57. return HAL_OK;
  58. }
  59. else
  60. {
  61. return HAL_ERROR;
  62. }
  63. }
  64. void ADXL345_SetInterrupts(uint8_t interrupts)
  65. {
  66. ADXL345_WriteByte(ADXL345_REG_INT_ENABLE, interrupts);
  67. }
  68. void ADXL345_RemapInterrupts(uint8_t interrupts)
  69. {
  70. ADXL345_WriteByte(ADXL345_REG_INT_MAP, interrupts);
  71. }
  72. uint8_t ADXL345_IsInterrupt(uint8_t interrupt)
  73. {
  74. uint8_t int_src = ADXL345_ReadByte(ADXL345_REG_INT_SOURCE);
  75. return (int_src & interrupt);
  76. }
  77. void ADXL345_EnableTapDetectOnAxes(uint8_t axes)
  78. {
  79. ADXL345_WriteByte(ADXL345_REG_TAP_AXES, axes);
  80. }