digipot_mcp4451.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include "Configuration.h"
  2. #ifdef DIGIPOT_I2C
  3. #include "Stream.h"
  4. #include "utility/twi.h"
  5. #include "Wire.h"
  6. // Settings for the I2C based DIGIPOT (MCP4451) on Azteeg X3 Pro
  7. #if MB(5DPRINT)
  8. #define DIGIPOT_I2C_FACTOR 117.96
  9. #define DIGIPOT_I2C_MAX_CURRENT 1.736
  10. #else
  11. #define DIGIPOT_I2C_FACTOR 106.7
  12. #define DIGIPOT_I2C_MAX_CURRENT 2.5
  13. #endif
  14. static byte current_to_wiper( float current ){
  15. return byte(ceil(float((DIGIPOT_I2C_FACTOR*current))));
  16. }
  17. static void i2c_send(byte addr, byte a, byte b)
  18. {
  19. Wire.beginTransmission(addr);
  20. Wire.write(a);
  21. Wire.write(b);
  22. Wire.endTransmission();
  23. }
  24. // This is for the MCP4451 I2C based digipot
  25. void digipot_i2c_set_current( int channel, float current )
  26. {
  27. current = min( (float) max( current, 0.0f ), DIGIPOT_I2C_MAX_CURRENT);
  28. // these addresses are specific to Azteeg X3 Pro, can be set to others,
  29. // In this case first digipot is at address A0=0, A1= 0, second one is at A0=0, A1= 1
  30. byte addr= 0x2C; // channel 0-3
  31. if(channel >= 4) {
  32. addr= 0x2E; // channel 4-7
  33. channel-= 4;
  34. }
  35. // Initial setup
  36. i2c_send( addr, 0x40, 0xff );
  37. i2c_send( addr, 0xA0, 0xff );
  38. // Set actual wiper value
  39. byte addresses[4] = { 0x00, 0x10, 0x60, 0x70 };
  40. i2c_send( addr, addresses[channel], current_to_wiper(current) );
  41. }
  42. void digipot_i2c_init()
  43. {
  44. const float digipot_motor_current[] = DIGIPOT_I2C_MOTOR_CURRENTS;
  45. Wire.begin();
  46. // setup initial currents as defined in Configuration_adv.h
  47. for(int i=0;i<=sizeof(digipot_motor_current)/sizeof(float);i++) {
  48. digipot_i2c_set_current(i, digipot_motor_current[i]);
  49. }
  50. }
  51. #endif