6 years, 1 month ago.

.gets function question

I am using the .gets function in order to access strings from a raspberry pi

I understand that if I have a 3 character string I can use .gets() in order to read these values using

Serial transmission

Serial device(p28, p27);  // tx, rx
Serial pc(USBTX, USBRX);

char value[3];
pc.printf("value: %s \r\n", value);

This will give me a string of 3 characters.

I want to be able to change the device.gets(value,3) to read characters until the \n from the raspberry pi appears. How can I do this if I change from a string from 3 characters to 4.

1 Answer

6 years, 1 month ago.

you can use scanf function or write a loop that read characters from serial and put them in an array of char until the '\n' is readed.

something could be :

char value[100];
int index=0;
char ch;

   if (device.readable())      // if there is an character to read from the device
       ch = device.getc();   // read it
      if (index<100)               // just to avoid buffer overflow
         value[index++]=ch;  // put it into the value array and increment the index
} while (ch!='\n');    // loop until the '\n' character

value[index]='\x0';  // add un 0 to end the c string


Accepted Answer

I keep getting a device.readable() = 0. Whenever I send the string, I am getting the data from the string each time. I am sending data to the raspberry pi and then using this to get data back by sending a string over serial from the pi to the mbed.

posted by Curtis Belknap 16 Apr 2015

I think, you should replace if (index<100) with if (index<99) in order to keep a place to value[index]='\x0'.

posted by Mahmoud Morsy 10 Feb 2018