XBee communicating to m3PI

Hi,

I am working on a project that has an m3pi talking over Xbee, and as an intermediary step i have code that will talk back and forth with the m3pi.

I found it somewhat challenging to get messages back and forth from the m3pi because the mbed serial library doesn’t have a thing similar to serial.readString() in arduino, thus i had to write code to loop through the chars.

I figure this may be useful for anyone getting started with the m3pi and xbees.

I am going to assume a reader is familiar with how to use the m3PI, mbed, and xbees in other contexts.

I bought two xbees and the xbee explorer from sparkfun.

sparkfun.com/products/11812
sparkfun.com/products/8665 X 2
pololu.com/product/2153

I put the code below onto the mbed
the code will send out on the xbee that value “Z is %d\n”,z once every three seconds
anything you send in will be printed to the LCD screen on the m3pi.


#include "mbed.h"
#include "m3pi.h"


// works - will send messages to m3pi that are then displayed.


m3pi m3pi;
Serial mySerialDevice(p28, p27); 

    int n = 1; // for looping thu char array
    int z = 1;
    
    int loopCount = 1;


char messageIn[50];
char messageToSend[50];

char nxtChr;
    
void obtainSerialData();
void sendSerialData(char messageOut[]);


int main() {

    mySerialDevice.baud(9600);

    wait(1);
  
    while (1) {
 
        obtainSerialData();
        
        m3pi.cls();
        m3pi.locate(0,0);
        m3pi.printf(messageIn);
        
        wait(1.5);
        sprintf(messageToSend,"Z is %d\n",z);
        sendSerialData(messageToSend);
        wait(1.5);
        z++;
    
    } // end of the while loop
} // end of the main function

void obtainSerialData()
{
        n = 0;
        while (mySerialDevice.readable()) 
        {
            nxtChr =  mySerialDevice.getc();
            messageIn[n] = nxtChr;
            if (nxtChr == '\0')
            {
                break;
            }
            if (nxtChr == '\n')
            {
                messageIn[n] = '\0';
                break;
            }
            
            n++;
        }
}
    
void sendSerialData(char messageOut[])
{
        int n=0;
        while (1) 
        {
            mySerialDevice.putc(messageOut[n]);

            if (messageOut[n] == '\0')
            {
                break;
            }
            n++;
        }    
}

I then used the serial monitor in the arduino environment and hooked it to my com port for the xbee. when i switched on the m3pi, i saw that the serial port on my computer shows the “Z = 1” message from my m3pi. When I wrote text into my serial monitor, it came out on the m3pi.





Hello.

That seems generally useful! Thanks for sharing.

-Jon