Example program of decoding the DF Robotics xbee joystick serial output

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers mbed_DFRobot_joystick_parse.cpp Source File

mbed_DFRobot_joystick_parse.cpp

00001 // Example of parsing the serial string from the DF Robot Joystick with the mbed
00002 #include "mbed.h"
00003 
00004 DigitalOut myled(LED1);
00005 Serial pc(USBTX, USBRX);    //tx, rx via USB connection
00006 Serial xbee(p13, p14);    //tx, rx via Xbee socket
00007     
00008 int main() {
00009     char joystr[100];   //used to store the whole joystick string
00010     int buttonsAll;     //16bit representation of all buttons
00011     int button[16];     //individual button states (normally high)
00012     int js_lr_L;        //Left Joystick Left/Right movement
00013     int js_ud_L;        //Left Joystick Up/Down movement
00014     int js_lr_R;        //Right Joystick Left/Right movement
00015     int js_ud_R;        //Right Joystick Up/Down movement
00016     int chksum;         //checksum for error correction
00017             
00018     pc.baud(921600);    //crank up the PC baudrate (USB) to avoid latency between data acquisition
00019     xbee.baud(9600);
00020     
00021     pc.printf("\r\n\r\n%s\r\n", __FILE__);
00022         
00023     while(1) {                
00024         while(xbee.readable())      //clear out the remaining characters in the buffer
00025             char c = xbee.getc();
00026             
00027         //read the serial string from the xbee (starts with '$', ends with \r\n            
00028         xbee.scanf("$%s\r\n", &joystr);    
00029             
00030  //       pc.printf("%s\r\n", joystr);     //used for debugging
00031   
00032         if(!strncmp(joystr, "JOYSTK", 6)){
00033             if (sscanf(joystr, "JOYSTK,%X,%d,%d,%d,%d*%X", &buttonsAll, &js_lr_L, &js_ud_L, &js_lr_R, &js_ud_R, &chksum) >= 1) {
00034      
00035                  // iterate through buttonsAll (each bit) to assign value MSB first
00036                 for(int i=15;i>=0;i--){
00037                     if(buttonsAll & (1 << i))
00038                         button[i] = 1;
00039                     else
00040                         button[i] = 0;
00041                     pc.printf("%1d ", button[i]);
00042                 }
00043                 
00044                 //pc.printf("%7 %5d %5d %5d %5d 0x%02X\r\n", buttonsAll, js_lr_L, js_ud_L, js_lr_R, js_ud_R, chksum);
00045                 pc.printf("%5d %5d %5d %5d\r\n", js_lr_L, js_ud_L, js_lr_R, js_ud_R);
00046             }
00047             else{
00048                 pc.printf("BAD parse %s\r\n", joystr);    
00049             }
00050         }      
00051         myled = !myled; //toggle LED for activity verification
00052     }//while(1)
00053 }//main