9 years, 7 months ago.

Serial Communication between two mbeds with serial, buffer issue

So I am trying to set up serial communication between two mbeds. One is a "master" (sending data with no end) and one is a "slave" accepting data to no end. In the read project, I have no control over the master. It is simply sending me data whether the slave is there or not.

Master

#include "mbed.h"
Serial pc(USBTX, USBRX);
Serial uart(p28, p27);
 
int count = 1;

int main() {
    pc.printf("%d",count);
    while (1) {
            speed++;
            char str[125]="";
            sprintf(str, "%d", count);
            if(uart.writeable())
            {
                uart.printf("%s\n",str);
            }
            
    }
}

Slave

#include "mbed.h"
Serial pc(USBTX, USBRX);
Serial uart(p28, p27);
int main() {
    while(1) {
        wait(2);
        if(uart.readable()) {
            char message[125];
            uart.scanf("%s",message);
            message[strlen(message)] = '\n';
            pc.printf("%s", message);
        }
    }
}

So the master example code is just pumping me numbers in the form of strings. What I want the slave to do is read from the master every 2 seconds and print it out on the pc (that's why I have the wait(2)). The problem is, I am guessing, that the master is still writing in those two seconds to the RX buffer of the slave mbed causing some funky outputs. If you take away the wait(2), then everything works. But I need it to operate in a way so that no matter how the master is acting, I can pull whatever master is pushing at any given time. The master can be pushing data every 0.1 seconds, but I will be pulling data every 2 seconds...but this currently doesn't work.

Does anyone with more expertise suggest a fix?

Thank you!

1 Answer

9 years, 7 months ago.

there are many ways of doing it.

One of these could be :

- replace the wait(2) by a timer. So your soft loop while the time is below 2 seconds, but continue to check if there is some datas available. If this is the case, you have to store these data until the 2 seconds are elapsed.

-To store the incomming datas during the 2 seconds (if somes are comming...) you can use an FIFO stack.

So in pseudo code your soft could be :

while(1)
{
  T = Getime

 while (GetTime - T < 2 seconds)
 {
   if (uart.readable())
   {
    get the datas from uart
    push into the FIFO stack the datas;
   }
 }
 if (FIFO not empty)
   print datas
}


Hope it can help you.