unkounko

Dependencies:   mbed Servo

Revision:
0:562021ed1ba9
diff -r 000000000000 -r 562021ed1ba9 Communication/XBee/XBee.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Communication/XBee/XBee.cpp	Sat Jan 13 13:33:09 2018 +0000
@@ -0,0 +1,112 @@
+#include "XBee.h"
+
+#include <stdint.h>
+#include "mbed.h"
+
+namespace XBEE
+{
+    Ticker xbee_timer;
+    Serial xbee_uart(XBEE_TX, XBEE_RX);
+    DigitalOut XBee_LED(LED1);
+
+    void uartUpdate(void);
+    void lostCheck(void);
+
+    namespace
+    {
+        ControllerData ctrData;
+        ControllerData keepCtrData;
+        const uint8_t defaultData[4] = CTR_DEFAULT_DATA;
+		const char check[] = "DT=";
+		volatile char packet[24];
+
+        bool controllerLost = false;
+        uint8_t timerCount = 0;
+    }
+
+    void Controller::Initialize(void) {
+        xbee_timer.attach(lostCheck, 0.025);
+        xbee_uart.baud(4800);
+        xbee_uart.attach(uartUpdate, Serial::RxIrq);
+        DataReset();
+    }
+
+    ControllerData* Controller::GetData(void) {
+        __disable_irq();
+        for(uint8_t i = 0; i < CTR_DATA_LENGTH; i++) keepCtrData.buf[i] = ctrData.buf[i];
+        __enable_irq();
+        return &keepCtrData;
+    }
+
+    void Controller::DataReset(void) {
+        __disable_irq();
+		for(uint8_t i = 0; i < CTR_DATA_LENGTH; i++) ctrData.buf[i] = defaultData[i];
+        __enable_irq();
+    }
+
+    bool Controller::CheckControllerLost(void) {
+        return controllerLost;
+    }
+
+    void uartUpdate(void) {
+        static bool phase = false;
+        static uint8_t count = 0;
+
+        char data = xbee_uart.getc();
+
+		if(phase)
+		{		
+			packet[count] = data;
+			if(count < 2)
+			{
+				if(data != check[count])
+				{
+					phase = false;
+					controllerLost = true;
+                    XBee_LED = LED_OFF;
+				}
+			}
+			else if(count == 8)
+			{
+                if(data != '\r')
+                {
+                    phase = false;
+                    controllerLost = true;
+                    XBee_LED = LED_OFF;
+                }
+                else
+                {
+                    ctrData.buf[0] = packet[4];
+                    ctrData.buf[1] = packet[5];
+                    ctrData.buf[2] = packet[6];
+                    ctrData.buf[3] = packet[7];
+                    phase = false;
+                    timerCount = 0;
+                    controllerLost = false;
+                    XBee_LED = LED_ON;
+                }
+			}
+			count++;
+		}
+		else
+		{
+			if(data == '@')
+			{
+				count = 0;
+				phase = true;
+			}
+		}
+	}
+
+    void lostCheck(void) {
+        timerCount++;
+        if(timerCount == 2) XBee_LED = LED_OFF;
+        if(timerCount >= 20) {
+            controllerLost = true;
+            Controller::DataReset();
+            timerCount = 0;
+            XBee_LED = LED_OFF;
+        }
+    }
+}
+