From 90d5c5e9a29b81389de3dc5046bc7f8260c70a17 Mon Sep 17 00:00:00 2001
From: Luca Erbetta <luca.erbetta@skywarder.eu>
Date: Sat, 7 Mar 2020 16:47:33 +0100
Subject: [PATCH] [BusTemplate] Wait for TXE before doing something on the bus

---
 src/shared/drivers/BusTemplate.h | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/src/shared/drivers/BusTemplate.h b/src/shared/drivers/BusTemplate.h
index 0652a840b..0a9ebfbc6 100644
--- a/src/shared/drivers/BusTemplate.h
+++ b/src/shared/drivers/BusTemplate.h
@@ -110,6 +110,9 @@ private:
 
     inline void _write(uint8_t byte) const
     {
+        // Wait until the peripheral is ready to transmit
+        while ((getSPIAddr(N)->SR & SPI_SR_TXE) == 0)
+            ;
         getSPIAddr(N)->DR = byte;
         while ((getSPIAddr(N)->SR & SPI_SR_RXNE) == 0)
             ;
@@ -127,6 +130,9 @@ private:
 
     inline uint8_t _read() const
     {
+        // Wait until the peripheral is ready to transmit
+        while ((getSPIAddr(N)->SR & SPI_SR_TXE) == 0)
+            ;
         getSPIAddr(N)->DR = 0;
         while ((getSPIAddr(N)->SR & SPI_SR_RXNE) == 0)
             ;
@@ -157,6 +163,9 @@ private:
      */
     inline uint8_t _transfer(uint8_t* byte)
     {
+        // Wait until the peripheral is ready to transmit
+        while ((getSPIAddr(N)->SR & SPI_SR_TXE) == 0)
+            ;
         getSPIAddr(N)->DR = *byte;
         while ((getSPIAddr(N)->SR & SPI_SR_RXNE) == 0)
             ;
-- 
GitLab