How to send/receive more than 1 integer through serial communication?

As i know there are lots of method to send/receive integers but i could not figure out how to send multiple data?

In my project i'am using two arduinos one attached to accelerometer sensor and my sensor gives me 2 angle values as outputs like "30" and "-22". (angle values around x and y axis)

I would like to use them as inputs for my other arduino using serial communication.

According to my forum search i found this article very useful but as i said, i need to send two integers.

http://forum.arduino.cc/index.php/topic,99225.0.html

is it possible to enter sensor outputs to serial window as (30,-22);

Output:

30
-22

Could you please help me how can i do that?

Thanks.

Use Serial.print as many times as you need to output as many things as you need:-

int val1 = 30;
int val2 = -20;
Serial.print("first value ");
Serial.print(val1);
Serial.print(" second value ");
Serial.println(val2);    // print and start a new line.

Thank you very much for your very quick reply.

On the receiver side what the code should be to receive these seperated data at the same time?

Look at the code examples in serial input basics. One of the three options should do what you need. See also the section about parsing the received data.

...R

Thank you very much for this tutorial.

I read it and have a small question if you can help me.

Parsing code is starting with;

char receivedChars[] = "This is a test, 1234, 45.3" ; (when data are "This is a test,1234,45.3")

But ın my studies i will send data which is not known by myself. For example sensor will read angle values around x and y axis as 30 and -22.

So how can i specify those values into my parsing code as you did above?

You need to combine that parsing example with the code examples above which actually read the serial input.

The basic algorithm is to:

  1. Set up a buffer to hold the received data (specify how much space you expect to use)
  2. Place received characters into that buffer (without going past the end of the buffer)
  3. Parse for start/end markers and the data you want
  4. Skip over any data you don't want

Step 4 can get complex, mostly if you need to keep working on the buffer and receiving new data at the same time. The "several characters" example doesn't attempt to do this - it processes all of the buffer before it looks to Serial.available() again. Always think about what happens if any character is missed or garbled: how can the receiver re-synchronise to the incoming data and find the correct values.

Nick Gammon's State Machine example which processes serial data and allows you to send multiple variables is a great place to start.

you can arbitrarily update either of the axis independently of each other... if you wish.

In my project i'am using two arduinos one attached to accelerometer sensor and my sensor gives me 2 angle values as outputs like "30" and "-22". (angle values around x and y axis)

Do you have an exact/actual example of the data that is sent from the sensor? Is the data sent have some end of data marker/delimiter? This is important in evaluating the receiving/parsing methods to use.

Nsitu:
I read it and have a small question if you can help me.
Parsing code is starting with;
char receivedChars[] = "This is a test, 1234, 45.3" ; (when data are "This is a test,1234,45.3")

If you look at the other examples they place the received data into an array called receivedChars

This is just an example of the sort of thing that might be in that array. The important thing is that you know the order of the data items and the type of data. The actual values can vary. I used 3 different types of data just for illustration.

...R

Thanks for all advices,

I tried to combine receiving code and parsing code below, it is half working i dont know why, when i enter <12,5> it gives me just integer1=12 and integer2=0(always equal to 0). It is probably about that i am a newcomer. Is it easy to fix it? If yes how can i do? Thank you very much again.

const byte numChars = 32;
char receivedChars[numChars];
int integerFromPC1 = 0;
int integerFromPC2 = 0;
char recvChar;
char endMarker = '>';
boolean newData = false;

void setup() {
	Serial.begin(9600);
	Serial.println("<Arduino is ready>");
}

void loop() {
	recvWithStartEndMarkers();
	showNewData();
        parseData();
	showParsedData();
}

void recvWithStartEndMarkers() {
	static boolean recvInProgress = false;
	static byte ndx = 0;
	char startMarker = '<';
	char endMarker = '>';
	char rc;
	
	if (Serial.available() > 0) {
		rc = Serial.read();

		if (recvInProgress == true) {
			if (rc != endMarker) {
				receivedChars[ndx] = rc;
				ndx++;
				if (ndx >= numChars) {
					ndx = numChars - 1;
				}
			}
			else {
				receivedChars[ndx] = '\0'; // terminate the string
				recvInProgress = false;
				ndx = 0;
				newData = true;
			}
		}

		else if (rc == startMarker) {
			recvInProgress = true;
		}
	}
}

void showNewData() {
	if (newData == true) {
		Serial.print("This just in ... ");
		Serial.println((char*)receivedChars);
		newData = false;
	}
}

void parseData() {

    // split the data into its parts
    
  char * strtokIndx; // this is used by strtok() as an index
  
  strtokIndx = strtok((char*)receivedChars,",");
  integerFromPC1 = atoi(strtokIndx); 
  
  strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
  integerFromPC2 = atoi(strtokIndx);     // convert this part to an integer
  
}
  
  void showParsedData() {
	
	Serial.print("Integer1 ");
	Serial.println(integerFromPC1);
        Serial.print("Integer2 ");
        Serial.println(integerFromPC2);
	}

Nsitu:
I tried to combine receiving code and parsing code below, it is half working i dont know why, when i enter <12,5> it gives me just integer1=12 and integer2=0(always equal to 0).

Can you please post all the output from your program as it appears in the Serial Monitor?

...R

Robin2:
Can you please post all the output from your program as it appears in the Serial Monitor?

...R

This just in ... 12
Integer1 12
Integer2 0
Integer1 12
Integer2 0
Integer1 12
Integer2 0
Integer1 12
Integer2 0
.
.
.
.
.continues like this.

This just in ... 12

I wonder why that line is not 12,5

Given that it is not 12,5 the rest of the output is what you would expect.

You think some more about that and so will I.

... a little later ...

If you look at the function showNewData() you will see that it only works if newData is true AND when it is finished it sets newData to false.

The two functions you added parseData(); and showParsedData(); work even when there is no new data. The simplest way to make them work only when there is new data is to remove them from loop() and call them from showNewData() like this ...

void showNewData() {
	if (newData == true) {
		Serial.print("This just in ... ");
		Serial.println((char*)receivedChars);
		newData = false;
		parseData();
		showParsedData();
	}
}

This is probably not the ideal overall design, but it works.

By the way, because the new functions were not waiting for newData to be true they were working on partial data - hence the 12 on its own and the 0s when nothing had been received.

...R

Robin2:
I wonder why that line is not 12,5

Given that it is not 12,5 the rest of the output is what you would expect.

You think some more about that and so will I.

...R

Ok i will, thanks a lot.

See the stuff I added to my earlier post which overlapped with yours.

Also, (and just for information, and certainly not for criticism) you seem to have missed an important debugging signal - the code with your additions behaved very differently from my original code. In my code it only produced output if you gave it some input whereas with your additions the code produced output continuously. That was the main thing that pointed me to the solution. However you did not mention this changed behaviour in Reply #9

...R

Robin2:
See the stuff I added to my earlier post which overlapped with yours.

Also, (and just for information, and certainly not for criticism) you seem to have missed an important debugging signal - the code with your additions behaved very differently from my original code. In my code it only produced output if you gave it some input whereas with your additions the code produced output continuously. That was the main thing that pointed me to the solution. However you did not mention this changed behaviour in Reply #9

...R

Robin thank you very much, it is now working perfectly.BTW i have an alternative code i cant decide which is more elegant way maybe you can decide.

const int NUMBER_OF_FIELDS = 2; // how many comma separated fields we expect
int fieldIndex = 0;            // the current field being received
int values[NUMBER_OF_FIELDS];   // array holding values for all the fields
int sign=1;


void setup()
{
  Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud
}

void loop()
{
  if( Serial.available())
  {
    char ch = Serial.read();
    if(ch >= '0' && ch <= '9') // is this an ascii digit between 0 and 9?
    {
      // yes, accumulate the value
      values[fieldIndex] = (values[fieldIndex] * 10) + (ch - '0'); 
    }
    else if (ch == ',')  // comma is our separator, so move on to the next field
    {
      if(fieldIndex < NUMBER_OF_FIELDS-1)
        fieldIndex++;   // increment field index
    }
    else if(ch == '-')
       sign = -1;
    else
    {
      // any character not a digit or comma ends the acquisition of fields
      // in this example it's the newline character sent by the Serial Monitor
      Serial.print( fieldIndex +1);
      Serial.println(" fields received:");
      //for(int i=0; i <= fieldIndex; i++)
      //{
       //Serial.println(values[i]);
       values[0]=values[0]*sign;
       values[1]=values[1]*sign;
       Serial.println(values[0]);
       Serial.println(values[1]);
       //values[i] = 0; // set the values to zero, ready for the next message
      //}
      fieldIndex = 0;  // ready to start over
      values[0]=0;
      values[1]=0;
      sign=1;
    }
  }
}

This code waiting inputs like "156,24" only one problem for this code when i set "sign" variable as "-1" (this happens when "-" sign received) all outputs become minus.

For example
when i enter 154,52

output
154
52

When i enter 154,-52

output
-154
-52
Note: Original code works for only 1 number(learned from arduino cookbook), i changed it for 2 numbers this is why minus sign is not working properly.

Do you have any idea to fix this?

Nsitu:
This code waiting inputs like "156,24" only one problem for this code when i set "sign" variable as "-1" (this happens when "-" sign received) all outputs become minus.

Hey, Gimme a break here ...

I gave you some code that works with all the values you have mentioned in Reply #16. Don't expect me to write another version of the same thing.

...R

Robin2:
Hey, Gimme a break here ...

I gave you some code that works with all the values you have mentioned in Reply #16. Don't expect me to write another version of the same thing.

...R

Thank you for your all support.

No, actually i am not expecting from you to write another version of same thing. I'am just writing another version in this topic because maybe other forum reader can choose according to their desire. i just asked to you maybe it is very easy to fix or maybe not.(I can not decide because of my lack of experince)

Whatever. Here is the alternative code;

#include <TextFinder.h>

TextFinder finder(Serial);

const int NUMBER_OF_FIELDS = 2; // how many comma-separated fields we expect
int fieldIndex = 0;             // the current field being received
int values[NUMBER_OF_FIELDS];   // array holding values for all the fields


void setup()
{
  Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud
}

void loop()
{

  for(fieldIndex = 0; fieldIndex  < 2; fieldIndex ++)
  {
    values[fieldIndex] = finder.getValue(); // get a numeric value

  }
  Serial.print( fieldIndex);
  Serial.println(" fields received:");
  //for(int i=0; i <  fieldIndex; i++)
  //{
    // Serial.println(values[i]);
  //}
  Serial.println(values[0]);
  Serial.println(values[1]);
  fieldIndex = 0;  // ready to start over
}

You just need to install textfinder library from;

Textfinder