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.

87 lines
2.4 KiB

  1. /*
  2. Copyright 2017 Balz Guenat
  3. based on work by Jun Wako <wakojun@gmail.com>
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "actuation_point.h"
  16. #include "i2c.h"
  17. ///////////////////////////////////////////////////////////////////////////////
  18. //
  19. // AD5258 I2C digital potentiometer
  20. // http://www.analog.com/media/en/technical-documentation/data-sheets/AD5258.pdf
  21. //
  22. #define AD5258_ADDR 0b0011000
  23. #define AD5258_INST_RDAC 0x00
  24. #define AD5258_INST_EEPROM 0x20
  25. uint8_t read_rdac(void) {
  26. // read RDAC register
  27. i2c_start_write(AD5258_ADDR);
  28. i2c_master_write(AD5258_INST_RDAC);
  29. i2c_start_read(AD5258_ADDR);
  30. uint8_t ret = i2c_master_read(I2C_NACK);
  31. i2c_master_stop();
  32. return ret;
  33. };
  34. uint8_t read_eeprom(void) {
  35. i2c_start_write(AD5258_ADDR);
  36. i2c_master_write(AD5258_INST_EEPROM);
  37. i2c_start_read(AD5258_ADDR);
  38. uint8_t ret = i2c_master_read(I2C_NACK);
  39. i2c_master_stop();
  40. return ret;
  41. };
  42. void write_rdac(uint8_t rdac) {
  43. // write RDAC register:
  44. i2c_start_write(AD5258_ADDR);
  45. i2c_master_write(AD5258_INST_RDAC);
  46. i2c_master_write(rdac & 0x3F);
  47. i2c_master_stop();
  48. };
  49. void actuation_point_up(void) {
  50. // write RDAC register: lower value makes actuation point shallow
  51. uint8_t rdac = read_rdac();
  52. if (rdac == 0)
  53. write_rdac(0);
  54. else
  55. write_rdac(rdac-1);
  56. };
  57. void actuation_point_down(void) {
  58. // write RDAC register: higher value makes actuation point deep
  59. uint8_t rdac = read_rdac();
  60. if (rdac == 63)
  61. write_rdac(63);
  62. else
  63. write_rdac(rdac+1);
  64. };
  65. void adjust_actuation_point(int offset) {
  66. i2c_master_init();
  67. uint8_t rdac = read_eeprom() + offset;
  68. if (rdac > 63) { // protects from under and overflows
  69. if (offset > 0)
  70. write_rdac(63);
  71. else
  72. write_rdac(0);
  73. } else {
  74. write_rdac(rdac);
  75. }
  76. }