Merge remote-tracking branch 'upstream/edge' into upstream-master
[clinton/Smoothieware.git] / src / modules / utils / currentcontrol / mcp4451.h
1 #ifndef MCP4451_H
2 #define MCP4451_H
3
4 #include "libs/Kernel.h"
5 #include "I2C.h" // mbed.h lib
6 #include "libs/utils.h"
7 #include "DigipotBase.h"
8 #include <string>
9 #include <math.h>
10
11 class MCP4451 : public DigipotBase {
12 public:
13 MCP4451(){
14 // I2C com
15 this->i2c = new mbed::I2C(p9, p10);
16 this->i2c->frequency(20000);
17 for (int i = 0; i < 8; i++) currents[i] = -1;
18 }
19
20 ~MCP4451(){
21 delete this->i2c;
22 }
23
24 void set_current( int channel, float current )
25 {
26 if(current < 0) {
27 currents[channel]= -1;
28 return;
29 }
30 current = min( (float) max( current, 0.0f ), this->max_current );
31 currents[channel] = current;
32 char addr = 0x58;
33 while(channel > 3){
34 addr += 0x02;
35 channel -= 4;
36 }
37
38 // Initial setup
39 this->i2c_send( addr, 0x40, 0xff );
40 this->i2c_send( addr, 0xA0, 0xff );
41
42 // Set actual wiper value
43 char addresses[4] = { 0x00, 0x10, 0x60, 0x70 };
44 this->i2c_send( addr, addresses[channel], this->current_to_wiper(current) );
45 }
46
47 float get_current(int channel)
48 {
49 return currents[channel];
50 }
51
52 private:
53
54 void i2c_send( char first, char second, char third ){
55 this->i2c->start();
56 this->i2c->write(first);
57 this->i2c->write(second);
58 this->i2c->write(third);
59 this->i2c->stop();
60 }
61
62 char current_to_wiper( float current ){
63 return char(ceilf(float((this->factor*current))));
64 }
65
66 mbed::I2C* i2c;
67 float currents[8];
68 };
69
70
71 #endif