Added mutex for multiple SPI devices on the same SPI bus

Fork of cc3000_hostdriver_mbedsocket by Martin Kojtal

Revision:
47:cc9a2501e29f
Parent:
45:50ab13d8f2dc
diff -r ca8c234997c0 -r cc9a2501e29f cc3000_spi.cpp
--- a/cc3000_spi.cpp	Sun Nov 10 21:41:44 2013 +0100
+++ b/cc3000_spi.cpp	Thu Oct 16 13:39:08 2014 +0000
@@ -43,8 +43,8 @@
 
 namespace mbed_cc3000 {
 
-cc3000_spi::cc3000_spi(PinName cc3000_irq, PinName cc3000_en, PinName cc3000_cs, SPI cc3000_spi, cc3000_event &event, cc3000_simple_link &simple_link)
-  : _wlan_irq(cc3000_irq), _wlan_en(cc3000_en), _wlan_cs(cc3000_cs), _wlan_spi(cc3000_spi), _event(event), _simple_link(simple_link) {
+cc3000_spi::cc3000_spi(PinName cc3000_irq, PinName cc3000_en, PinName cc3000_cs, SPI cc3000_spi, Mutex & mutex, cc3000_event &event, cc3000_simple_link &simple_link)
+  : _wlan_irq(cc3000_irq), _wlan_en(cc3000_en), _wlan_cs(cc3000_cs), _wlan_spi(cc3000_spi), _mutex(mutex),  _event(event), _simple_link(simple_link) {
 
     _wlan_spi.format(8,1);
     _wlan_spi.frequency(12000000);
@@ -90,6 +90,7 @@
 }
 
 uint32_t cc3000_spi::first_write(uint8_t *buffer, uint16_t length) {
+    _mutex.lock();
     _wlan_cs = 0;
     wait_us(50);
 
@@ -99,7 +100,8 @@
     write_synchronous(buffer + 4, length - 4);
     _spi_info.spi_state = eSPI_STATE_IDLE;
     _wlan_cs = 1;
-
+    _mutex.unlock();
+    
     return 0;
 }
 
@@ -144,6 +146,7 @@
         _spi_info.tx_packet_length = length;
 
         // Assert the CS line and wait until the IRQ line is active, then initialize the write operation
+        _mutex.lock();
         _wlan_cs = 0;
 
         wlan_irq_enable();
@@ -224,6 +227,7 @@
         } else if (_spi_info.spi_state == eSPI_STATE_IDLE) {
             _spi_info.spi_state = eSPI_STATE_READ_IRQ;
             /* IRQ line goes low - acknowledge it */
+             _mutex.lock();
              _wlan_cs = 0;
             read_synchronous(_simple_link.get_received_buffer(), 10);
             _spi_info.spi_state = eSPI_STATE_READ_EOT;
@@ -234,6 +238,7 @@
                 // Trigger Rx processing
                 wlan_irq_disable();
                 _wlan_cs = 1;
+                _mutex.unlock();
                 // The magic number resides at the end of the TX/RX buffer (1 byte after the allocated size)
                 // If the magic number is overwitten - buffer overrun occurred - we will be stuck here forever!
                 uint8_t *received_buffer = _simple_link.get_received_buffer();
@@ -248,6 +253,7 @@
             write_synchronous(_simple_link.get_transmit_buffer(), _spi_info.tx_packet_length);
             _spi_info.spi_state = eSPI_STATE_IDLE;
             _wlan_cs = 1;
+            _mutex.unlock();
         }
     }
 }