A simple library for controlling an MCP4241 digital potentiometer

Files at this revision

API Documentation at this revision

Comitter:
ollie8
Date:
Sat Feb 08 13:31:51 2014 +0000
Parent:
1:179b46a0165e
Commit message:
DigiPot can now be used in linear and log modes.

Changed in this revision

DigiPot.cpp Show annotated file Show diff for this revision Revisions of this file
DigiPot.h Show annotated file Show diff for this revision Revisions of this file
diff -r 179b46a0165e -r 54e9d9ddc350 DigiPot.cpp
--- a/DigiPot.cpp	Sat Jan 25 21:05:15 2014 +0000
+++ b/DigiPot.cpp	Sat Feb 08 13:31:51 2014 +0000
@@ -1,23 +1,47 @@
 #include "DigiPot.h"
-#include "math.h"
+#include <math.h>
 
 #define POT_0 0x00
 #define POT_1 0x10
+#define MAX 129.0
+#define MIN 0
+#define MAX_P 100
+#define BASE 10.0
+#define ROUND 0.5
 
-DigiPot::DigiPot(PinName miso, PinName mosi, PinName clk, PinName cs) {
+DigiPot::DigiPot(PinName miso, PinName mosi, PinName clk, PinName cs, Mode mode) {
     chsel = new DigitalOut(cs);
     spi = new SPI(mosi, miso, clk);
+    this->mode = mode;
     spi->format(8,0); 
     spi->frequency(1000000);
     level = 0x00;
+    percent = 0x00;
+    scale = log10(MAX);
 }
 
 void DigiPot::increment() {
-    setLevel(level++);
+    if (mode == LINEAR) {
+        if (level < MAX) {
+            setLevel(level++);    
+        }
+    } else {
+        if (percent < MAX_P) {
+            setLevel(round(pow(BASE, ((scale/MAX_P)*percent++))));
+        }        
+    }
 }
 
 void DigiPot::decrement() {
-    setLevel(level--);
+    if (mode == LINEAR) {
+        if (level > MIN) {
+            setLevel(level--);    
+        }
+    } else {
+        if (percent > MIN) {
+            setLevel(round(pow(BASE, ((scale/MAX_P)*percent--))));
+        }
+    }
 }
 
 void DigiPot::setLevel(unsigned char level) {
@@ -42,4 +66,8 @@
 
 unsigned char DigiPot::getLevel() {
     return level;
-}
\ No newline at end of file
+}
+
+unsigned char DigiPot::round(double value) {
+    return (unsigned char) floor(value+ROUND);    
+}
diff -r 179b46a0165e -r 54e9d9ddc350 DigiPot.h
--- a/DigiPot.h	Sat Jan 25 21:05:15 2014 +0000
+++ b/DigiPot.h	Sat Feb 08 13:31:51 2014 +0000
@@ -3,10 +3,14 @@
 
 #include <mbed.h>
 
+enum Mode {
+    LINEAR, LOGARITHMIC    
+};
+
 class DigiPot {
 
     public:    
-        DigiPot(PinName miso, PinName mosi, PinName clk, PinName cs);
+        DigiPot(PinName miso, PinName mosi, PinName clk, PinName cs, Mode mode);
         void increment();
         void decrement();
         void setLevel(unsigned char);
@@ -17,6 +21,10 @@
         SPI *spi;
         DigitalOut *chsel;
         unsigned char level;
+        unsigned char percent;
+        Mode mode;
+        double scale;
+        unsigned char round(double);
 };
 
 #endif
\ No newline at end of file