五力全開 / Mbed 2 deprecated Nucleo_printf

Dependencies:   mbed

Revision:
1:f6e87237daaa
Parent:
0:d88d3f466e6a
--- a/main.cpp	Sat May 28 03:34:49 2016 +0000
+++ b/main.cpp	Sat May 28 09:28:59 2016 +0000
@@ -7,19 +7,37 @@
 
 Serial pc(SERIAL_TX, SERIAL_RX);
  
-DigitalOut myled(LED1);
 Serial bluetooth(D10, D2); // tx,rx
+ 
+// Circular buffers for serial TX and RX data - used by interrupt routines
+const int buffer_size = 100;
+// might need to increase buffer size for high baud rates
+uint8_t rx_buffer[buffer_size+1];
+// Circular buffer pointers
+// volatile makes read-modify-write atomic 
+volatile int rx_in=0;
+volatile int rx_out=0;
 
-int ReceiveCount = 0;
-char BluetoothDataReceived[21];
+void Rx_interrupt();
+bool availableRxFIFO();
+uint8_t readRxFIFO();
+
 int main() {
-  int i = 1;
   pc.printf("Hello World !\n");
   
   bluetooth.baud(9600);
+  // Setup a serial interrupt function to receive data
+  bluetooth.attach(&Rx_interrupt, Serial::RxIrq);
   
   while(1) { 
+  if(availableRxFIFO())
+  {
+    uint8_t temp = readRxFIFO();   
+    pc.printf("  count: %d\n",temp);
+  }
+  wait(0.1);
   
+      /*
       if(bluetooth.readable())
       {
         unsigned char temp = bluetooth.getc() - 158;
@@ -31,18 +49,37 @@
       //pc.printf("This program runs since %d seconds.\n", i++);
       myled = !myled;
       //bluetooth.printf("\n Hi");
-      
-      /*
-    if(bluetooth.readable() >= 21)
-    {
-        //unsigned char temp = bluetooth.getc();
-        for(int i=0;i<21;i++)
-        {
-            BluetoothDataReceived[i] = bluetooth.getc();
-            pc.printf("%c",BluetoothDataReceived[i]);
-        }
-    }
-    */
+      */
   }
 }
- 
\ No newline at end of file
+
+bool availableRxFIFO()
+{
+    if(rx_out != rx_in) 
+    {return 1;}
+    else
+    {return 0;}
+}
+ 
+uint8_t readRxFIFO()
+{
+    if(rx_out != rx_in) {
+        uint8_t Output = rx_buffer[rx_out];
+        rx_out = (rx_out + 1) % buffer_size;
+        return Output;
+    }
+    return 0;
+}
+ 
+// Interupt Routine to read in data from serial port
+void Rx_interrupt() {
+// Loop just in case more than one character is in UART's receive FIFO buffer
+// Stop if buffer full
+    while ((bluetooth.readable()) && (((rx_in + 1) % buffer_size) != rx_out)) {
+        rx_buffer[rx_in] = bluetooth.getc();
+// Uncomment to Echo to USB serial to watch data flow
+//        pc.putc(rx_buffer[rx_in]);
+        rx_in = (rx_in + 1) % buffer_size;
+    }
+    return;
+}
\ No newline at end of file