Hello everyone, how do i send and receive a string and split it and store it to a different variables
here is the sample:
String string = "string1,string2";
how do i make it to this:
String var1 = "string1"
String var2 = "string2"
have a read of how-to-get-the-best-out-of-this-forum
e.g. what Arduino are you using?
what type are the variables? e.g. bytes, ints, floats, etc
what format is the string? e.g. comma seperated floats, binary, etc?
you can use substring() in the String class to extract substrings, see string tutorial
if you are using a low power Arduino such as the UNO or Mega use of the String class is not recommended as it can fragment memory and lead to unpredictable results
Hello
Did you try to use a sketch, didn´t you?
if YES
Post your sketch, well formated, with comments and in so called code tags "</>" to see how we can help.
Maybe...
String string = "string1,string2";
String a, b;
void setup()
{
Serial.begin(115200);
int index = string.indexOf(',');
a = string.substring(0, index);
b = string.substring(index + 1);
Serial.println(a);
Serial.println(b);
}
void loop () {}
20:21:04.567 -> string1
20:21:04.567 -> string2
this is for the sender part:
#include <SoftwareSerial.h>
#include <TinyGPSPlus.h>
static const int RXpin =4;
static const int TXpin = 3;
static const uint32_t GPSbaud = 9600;
TinyGPSPlus gps;
SoftwareSerial ss(RXpin, TXpin);
SoftwareSerial sendgpsData(8, 9);
String gpsData = "";
void setup() {
Serial.begin(9600);
ss.begin(GPSbaud);
}
void loop() {
gps_read();
sending_GPS();
delay(500);
gpsData = "";
}
void gps_read(){
while(ss.available() > 0){
if(gps.encode(ss.read())) gps_location();
}
if(millis() > 5000 && gps.charsProcessed() < 100){
Serial.println(F("No GPS detected, check wiring."));
while(true);
}
}
void gps_location() {
Serial.print(F("Location: "));
if(gps.location.isValid()){
lat = (gps.location.lat());
lon = (gps.location.lng());
}
else Serial.print(F("Invalid"));
Serial.println();
}
void sending_GPS(){
String gpslat = String(lat,7);
String gpslon = String(lon,7);
gpsData.concat(gpslat);
gpsData.concat(",");
gpsData.concat(gpslon);
if(gpsData != ""){
sendgpsData.write(gpsData); //help me in this part how do i send the string
}
Serial.print("gpsData: ");
Serial.println(gpsData);
}
and this is for the receiver part:
#include <SoftwareSerial.h>
SoftwareSerial receivegpsData(9, 8);
void setup() {
Serial.begin(9600);
receivegpsData.begin(9600);
}
void loop() {
receivegpsData.listen();
while(receivegpsData.available()>0){
char gpsdata = receivegpsData.read(); // please help me how do i read the sent string
}
//and help how do seperate the string data
}
what does the receiver receive? give an example?
looks like you are using Arduino UNO micrios - use of the String class is not recommended on such low power devices
using libraries makes writing code more comfortable at the cost of needing additional flash-memory and additional RAM-memory
I mean this serious:
users that are in a big hurry skip this posting and go on hurrying for multiple hours trying this trying that without proceeding. If the main fun is to be in the hurry eveyrthing is alright.
users that like to learn: take one hour of time (Yes it will take 60 minutes) to
- copy and paste the demo-code watching the results in the serial monitor
- reading inside the code step by step, function for function to understand step by step what the code is doing
This code offers learning quite some things that are of general use for all projects.
This code uses the SafeString-library which can be installed with the library-manager of the arduino IDE
If you have questions about the details just ask the questions.
Best thing is you try to modify the code to your needs and if something does not work
post
- your complete sketch
- a description of what the code does like posted
- a description what the code should do instead
// MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START *
// a detailed explanation how these macros work is given in this tutorial
// https://forum.arduino.cc/t/comfortable-serial-debug-output-short-to-write-fixed-text-name-and-content-of-any-variable-code-example/888298
#define dbg(myFixedText, variableName) \
Serial.print( F(#myFixedText " " #variableName"=") ); \
Serial.println(variableName);
// usage: dbg("1:my fixed text",myVariable);
// myVariable can be any variable or expression that is defined in scope
#define dbgi(myFixedText, variableName,timeInterval) \
do { \
static unsigned long intervalStartTime; \
if ( millis() - intervalStartTime >= timeInterval ){ \
intervalStartTime = millis(); \
Serial.print( F(#myFixedText " " #variableName"=") ); \
Serial.println(variableName); \
} \
} while (false);
// usage: dbgi("2:my fixed text",myVariable,1000);
// myVariable can be any variable or expression that is defined in scope
// third parameter is the time in milliseconds that must pass by until the next time a
// Serial.print is executed
// end of macros dbg and dbgi
// print only once when value has changed
#define dbgc(myFixedText, variableName) \
do { \
static long lastState; \
if ( lastState != variableName ){ \
Serial.print( F(#myFixedText " " #variableName" changed from ") ); \
Serial.print(lastState); \
Serial.print( F(" to ") ); \
Serial.println(variableName); \
lastState = variableName; \
} \
} while (false);
// MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END *
// SafeStringReader_Cmds.ino
//
// Example of NON-Blocking read commmands from the Arduino Monitor input and acts on them
// the available commands are start stop
// See the SafeStringReader_CmdsTimed.ino for an example using a struct to hold the commands and their functions
//
// Commands are delimited by space dot comma NL or CR
// If you set the Arduino Monitor to No line ending then the last command will be ignored until it is terminated by a space or ,
// Use the settings Newline or Carrage Return or Both NL & CR
//
// These commands can be picked out of a line of user input
// start stop
// The input line can be as long as you like 100's of Kb long, but only two small buffers need to parse the commands
//
// download and install the SafeString library from
// www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html
// overview about the functionality of this code:
// inside function loop() four things are done:
// 1. count up a variable infinitely to demonstrate the fast running loop
// 2. Blink the onboard LED to demonstrate non-blocking timing
// 3. Check for commands send over the serial interface
// and in case a command is received analyse the command and execute
// the function related to the command
// tries to convert the received input into a float / int
// 4. print the value of the counter-variable once every second to
// demontsrate the fast running loop
// create an myInputReader instance of SafeStringReader class
// that will handle commands upto 5 chars long
// delimited by space, comma or CarrageReturn or NewLine
// the createSafeStringReader( ) macro creates both the SafeStringReader (myInputReader) and the necessary SafeString that holds input chars until a delimiter is found
// args are (ReaderInstanceName, expectedMaxCmdLength, delimiters)
// create the "object" with name myInputReader that does read from the serial interface
// maximum length of accepted inputcommands is 5 characteras
// allowed delimiters are:
// space: the " "
// comma: ,
// carriage return: \r
// new line: \n
#include "SafeStringReader.h"
createSafeStringReader(myInputReader, 256, " ,\r\n");
createSafeString(myInput_SS, 64);
boolean running = true;
unsigned long loopCounter = 0;
unsigned long allwaysCounter = 100000000;
float myDemoFloat;
int myDemoInt;
byte conversionResult;
unsigned long MyTestTimer = 0; // Timer-variables MUST be of type unsigned long
const byte OnBoard_LED = 13;
void setup() {
Serial.begin(115200);
Serial.println("Setup-Start");
Serial.println();
Serial.println(F(" SafeString-Reader-Demo and float / integer-conversion-demo"));
Serial.println(F(" Commands are stop start"));
Serial.println(F(" Set the Arduino IDE monitor to Newline, or Carriage return or Both NL & CR"));
Serial.println(F(" See the SafeStringReader_CmdsTimed.ino for an example using a struct to hold the commands and their functions."));
SafeString::setOutput(Serial); // enable error messages and SafeString.debug() output to be sent to Serial
if (running) {
Serial.println(F(" Counter Started"));
}
myInputReader.connect(Serial); // where SafeStringReader will read from in this demo the standard Serial
myInputReader.echoOn(); // echo back all input, by default echo is off
}
void loop() {
//dbgi("top of loop",allwaysCounter,3000); // print value of variable allwaysCounter once every three seconds
allwaysCounter++; // does what its name says allways counting up more and more demonstrating the non-blocking character of the code
BlinkHeartBeatLED(OnBoard_LED, 250); // demontrates non-blocking timing
ManageSerialInput(); // call this non-blocking function in every iteration of loop
// rest of code here is executed while the user typing in commands
if ( TimePeriodIsOver(MyTestTimer, 20000) ) {// check if 1000 milliseconds have passed by
// once every 1000 milliseconds execute code below
if (running) { // only in case variable running has value true
Serial.print(F("allwaysCounter:"));
Serial.println(allwaysCounter);
}
}
/* while (....) { } while-loops reduce responsivness of code
for (....) { } for-loops reduce responsivness of code
delay(....) use of delay reduces responsiveness of code
*/
}
// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
unsigned long currentMillis = millis();
if ( currentMillis - startOfPeriod >= TimePeriod ) {
// more time than TimePeriod has elapsed since last time if-condition was true
startOfPeriod = currentMillis; // a new period starts right here so set new starttime
return true;
}
else return false; // actual TimePeriod is NOT yet over
}
void BlinkHeartBeatLED(int IO_Pin, int BlinkPeriod) {
static unsigned long MyBlinkTimer;
pinMode(IO_Pin, OUTPUT);
if ( TimePeriodIsOver(MyBlinkTimer, BlinkPeriod) ) {
digitalWrite(IO_Pin, !digitalRead(IO_Pin) );
}
}
void handleStartCmd() {
running = true;
Serial.println();
Serial.print(F("> start at Counter:"));
Serial.println(allwaysCounter);
}
void handleStopCmd() {
running = false;
Serial.println();
Serial.print(F("> stop at Counter:"));
Serial.println(allwaysCounter);
}
void ConvertToFloatPrintResult(SafeString& p_refToSS) {
float myDemoFloat = -0.1;
conversionResult = p_refToSS.toFloat(myDemoFloat);
dbg("R:", conversionResult);
if (conversionResult == 1) {
Serial.println("successful concersion to float");
dbg("F:", myDemoFloat);
}
else {
Serial.println("input was not a float");
Serial.println("value of float-variable stays unchanged");
dbg("F:", myDemoFloat);
}
Serial.println();
}
void ConvertToIntegerPrintResult(SafeString& p_refToSS) {
int myDemoInt = -789;
conversionResult = myInput_SS.toInt(myDemoInt);
if (conversionResult == 1) {
Serial.println("successful concersion to int");
dbg("I:", myDemoInt);
}
else {
Serial.println("input was not an integer");
Serial.println("value of integer-variable stays unchanged");
dbg("I:", myDemoInt);
}
//dbgc("integer",myDemoInt); only in case the variable myDemoInt has changed its value print once
}
void ManageSerialInput() {
if (myInputReader.read()) { // check if all characters of a command including delimiter are received
myInput_SS = myInputReader;
Serial.print("\n received input #");
Serial.print(myInput_SS);
Serial.println("#");
Serial.println();
ConvertToFloatPrintResult(myInput_SS);
ConvertToIntegerPrintResult(myInput_SS);
if (myInput_SS == "start") {
handleStartCmd();
}
else if (myInput_SS == "stop") {
handleStopCmd();
}
} // else no delimited command yet
}
/* Additional comments
this demo-code has a lot features. This means more lines to read
and more things that you CAN learn if you want
A code with more functinality than
- switch LED ON
- wait a second
- switch LED OFF
- wait a second
repeat
requires more lines of code and more time to learn
1. At the top there are three so called "MACROS" for comfortable debugoutput
2. The code has a easy to use non-blocking timing function
3. this codes shows how to write your own functions and how to call them
4. this code demonstrates how to use the comfortable
NON-blocking serial inputreader of the library SafeString
5. this code demonstrates how to use SafeStrings as parameters
6. this demo-code demonstrates how to convert strings into floats and int
*/
best regards Stefan
it should receive the gps latitude and latiitude in string
@ mark^5 (@markmarkmarkmarkmark
is this demo-code
really working?
you repeat to handing over a single byte to your function
gps.encode()
and the gps-object puts together all the single bytes until valid GPS-data is received
and then the result will be true?
Yes indeed this is how the library TinyGPSPlus is working.
Does your GPS-device send the gps-data in intervals so that there will be a pause between two "sendings" ? so your code has time to execute below the while-loop?
What is the actual problem you are trying to solve?
Post #1 & #2...
answered is post #6
Post #6 ignored...
Random information (full code which is good) provided in post #7 (replying to own post)
unprecise information
does "it" mean your "sender-sketch that receives data from your GPS-device
or
does "it" mean your "receiver-sketch that receives data from your sender-sketch
The SafeString serial-reader-function can be used for both your sender-sketch andyour receiver-sketch
In the SafeString-reader function you can define a delimiter like comma "," this means each time the reader reads a comma the function results in true and you can assign the received characters to another SafeString (like shown in the demo-code) and then do some more processing with the data
You should post a real example of what your sender-sketch is receiving from your GPS-device
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.