Software SPI allows non-standard SPI pins to be used for interfacing with SPI devices

Fork of SWSPI by Dave Van Wagner

Revision:
2:eafe3ec5fbf8
Parent:
1:9e0c0217646d
Child:
3:8c19911bdb58
--- a/SWSPI.cpp	Fri May 08 08:05:29 2015 +0000
+++ b/SWSPI.cpp	Fri May 08 08:23:58 2015 +0000
@@ -23,43 +23,42 @@
 #include <mbed.h>
 #include "SWSPI.h"
 
-SWSPI::SWSPI(PinName mosi_pin, PinName miso_pin, PinName sclk_pin) : miso(NULL)
+SWSPI::SWSPI(PinName mosi_pin, PinName miso_pin, PinName sclk_pin)
+    : mosi(mosi_pin),
+      miso(NULL),
+      sclk(sclk_pin)
 {
-    mosi = new DigitalOut(mosi_pin);
     if (miso_pin!= NC)
         miso = new DigitalIn(miso_pin);
-    sclk = new DigitalOut(sclk_pin);
     format(8);
     frequency();
 }
 
 SWSPI::~SWSPI()
 {
-    delete mosi;
     delete miso;
-    delete sclk;
 }
 
 void SWSPI::format(int bits, int mode)
 {
     this->bits = bits;
-    this->mode = mode;
     polarity = (mode >> 1) & 1;
     phase = mode & 1;
-    sclk->write(polarity);
+    sclk.write(polarity);
 }
 
 void SWSPI::frequency(int hz)
 {
-    this->freq = hz;
+    // TODO: need wait_ns taking int
+    this->delay_s = 0.5f/hz;
 }
 
 int SWSPI::write(int value)
 {
     int read = 0;
-    for (int bit = bits-1; bit >= 0; --bit)
+    for (unsigned bit = 1 << (bits-1); bit; bit >>= 1)
     {
-        mosi->write(((value >> bit) & 0x01) != 0);
+        mosi.write((value & bit) != 0);
 
         if (phase == 0)
         {
@@ -67,9 +66,9 @@
                 read |= (1 << bit);
         }
 
-        sclk->write(!polarity);
+        sclk.write(!polarity);
 
-        wait(1.0/freq/2);
+        wait(delay_s);
 
         if (phase == 1)
         {
@@ -77,11 +76,10 @@
                 read |= (1 << bit);
         }
 
-        sclk->write(polarity);
+        sclk.write(polarity);
 
-        wait(1.0/freq/2);
+        wait(delay_s);
     }
     
     return read;
 }
-