Half Duplex Version of SWSPI

Fork of SWSPI by Dave Van Wagner

Revision:
3:d3be72ac889e
Parent:
2:70039cc8ba02
--- a/SWSPI_HD.cpp	Tue Jun 19 10:49:39 2018 +0000
+++ b/SWSPI_HD.cpp	Tue Jun 19 11:19:34 2018 +0000
@@ -23,10 +23,11 @@
 #include <mbed.h>
 #include "SWSPI_HD.h"
 
-SWSPI_HD::SWSPI_HD(PinName dio_pin, PinName sclk_pin)
+SWSPI_HD::SWSPI_HD(PinName dio_pin, PinName sclk_pin, PinName cs_pin)
 {
     dio = new DigitalInOut(dio_pin);
     sclk = new DigitalOut(sclk_pin);
+    cs = new DigitalOut(cs_pin,true);
     format(8);
     frequency();
 }
@@ -35,6 +36,7 @@
 {
     delete dio;
     delete sclk;
+    delete cs;
 }
 
 void SWSPI_HD::format(int bits, int mode)
@@ -54,19 +56,20 @@
 int SWSPI_HD::write(int value)
 {
     int read = 0;
-
+    //ensure clock is in right phase to start and disable slave device
+    cs->write(true);
+    sclk->write(!polarity);
+    
     //Write Out
     dio->output();// set as an OUTPUT
-    
+    cs->write(false);//select slave device (active low)
     for (int bit = bits-1; bit >= 0; --bit)
     {
-        dio->output();// set as an OUTPUT
-        
         dio->write(((value >> bit) & 0x01) != 0);
-
+        wait(1.0/freq/2);
         sclk->write(!polarity);
-
         wait(1.0/freq/2);
+        sclk->write(polarity);
     }
     
     //Read In
@@ -79,6 +82,11 @@
             if (dio->read())   // was miso
                 read |= (1 << bit);
         }
+        
+        sclk->write(!polarity);
+
+        wait(1.0/freq/2);
+        
         if (phase == 1)
         {
             if (dio->read())   // was miso
@@ -89,6 +97,7 @@
 
         wait(1.0/freq/2);
     }
+    cs->write(true);
     return read;
 }