Tetsuya Yamamoto / Mbed 2 deprecated MD-Tutorial

Dependencies:   mbed

Revision:
2:becb78cfc927
Parent:
1:0ef4f75d84b5
Child:
3:0920442e3f03
--- a/main.cpp	Fri Oct 30 10:54:39 2020 +0000
+++ b/main.cpp	Mon Nov 02 11:42:17 2020 +0000
@@ -23,16 +23,25 @@
 PwmOut pwmR(PWM_R);
 //  DIR
 DigitalOut dirR(DIR_R);
-//  resistor
-//AnalogIn in(D3);
+
+//  serial
+Serial serial(D5,D4);
+
 //  joystick analogin
-AnalogIn joyX(A0);
-AnalogIn joyY(A1);
+//AnalogIn joyX(A0);
+//AnalogIn joyY(A1);
+//  stick value
+float x = 0.5F;
+float y = 0.5F;
+
 
 //  current power
 double currentPowerL = 0;
 double currentPowerR = 0;
 
+//  attach function
+void control_rx();
+
 int main()
 {
     //printf("start program... \n\r");
@@ -45,14 +54,17 @@
     //  power setting
     float maxPower = 0.9F;
     
+    //  serial attach
+    serial.attach(control_rx,Serial::RxIrq);
+    
     //printf("finish start up! \n\r");
 
     while(1){
         //  prepare power value
         float powerL,powerR;
         
-        float x = joyX.read();  //  go ahead & back
-        float y = joyY.read();  //  left & right
+        //float x = joyX.read();  //  go ahead & back
+        //float y = joyY.read();  //  left & right
         //  value format
         if(x > 1) x = 1.0;
         if(x < 0) x = 0.0;
@@ -153,3 +165,34 @@
     }
 }
 
+void control_rx(){
+    int head = 0;
+    char bytesX[4];
+    char bytesY[4];
+    
+    while(serial.readable()){
+        char c = serial.getc();
+        
+        if(c == 0x3a){
+            head = 0;
+            continue;
+        }
+        if(head < 3){
+            bytesX[head] = c;
+        }else{
+            bytesY[head - 3] = c;
+        }
+        if(head == 6){
+            //  printf
+            int32_t intX = (bytesX[0] << 24) + (bytesX[1] << 16) + (bytesX[2] << 8) + bytesX[3];
+            int32_t intY = (bytesY[0] << 24) + (bytesY[1] << 16) + (bytesY[2] << 8) + bytesY[3];            
+            //  cast float to double
+            float formatX = (float) intX;
+            float formatY = (float) intY;
+            //  save
+            x = formatX;
+            y = formatY;
+        }
+        head++;
+    }
+}