Fork of Smoothie to port to mbed non-LPC targets.

Dependencies:   mbed

Fork of Smoothie by Stéphane Cachat

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers mcp4451.h Source File

mcp4451.h

00001 #ifndef MCP4451_H
00002 #define MCP4451_H
00003 
00004 #include "libs/Kernel.h"
00005 #include "I2C.h" // mbed.h lib
00006 #include "libs/utils.h"
00007 #include "DigipotBase.h"
00008 #include <string>
00009 #include <math.h>
00010 
00011 class MCP4451 : public DigipotBase {
00012     public:
00013         MCP4451(){
00014             // I2C com
00015             this->i2c = new mbed::I2C(p9, p10);
00016             this->i2c->frequency(20000);
00017             for (int i = 0; i < 8; i++)
00018                 currents[i] = 0.0;
00019         }
00020 
00021         ~MCP4451(){
00022             delete this->i2c;
00023         }
00024 
00025         void set_current( int channel, float current )
00026         {
00027             current = min( (float) max( current, 0.0f ), this->max_current );
00028             currents[channel] = current;
00029             char addr = 0x58;
00030             while(channel > 3){
00031                 addr += 0x02;
00032                 channel -= 4;
00033             }
00034 
00035             // Initial setup
00036             this->i2c_send( addr, 0x40, 0xff );
00037             this->i2c_send( addr, 0xA0, 0xff );
00038 
00039             // Set actual wiper value
00040             char addresses[4] = { 0x00, 0x10, 0x60, 0x70 };
00041             this->i2c_send( addr, addresses[channel], this->current_to_wiper(current) );
00042         }
00043 
00044         float get_current(int channel)
00045         {
00046             return currents[channel];
00047         }
00048 
00049     private:
00050 
00051         void i2c_send( char first, char second, char third ){
00052             this->i2c->start();
00053             this->i2c->write(first);
00054             this->i2c->write(second);
00055             this->i2c->write(third);
00056             this->i2c->stop();
00057         }
00058 
00059         char current_to_wiper( float current ){
00060             return char(ceil(float((this->factor*current))));
00061         }
00062 
00063         mbed::I2C* i2c;
00064         float currents[8];
00065 };
00066 
00067 
00068 #endif