How to send ASCII command to sensor and read out answer

Hi all,

I have an inclinometer sensor which I need to read out with arduino. If the sensor gets the command get---x it sends the value over serial connection.

With the serial monitor it works well when I send get---x. Now I'd like to do that in a function in may sketch like void getdata(). When I call that function the sensor should send the value.

PC is connected to arduino Serial and sensor is connected to Serial2 on my Mega.

How can I send that command in my function like the serial monitor does it? The sensor should send a 9byte string as answer like ±xxx.xxx which I need to read back on Serial to the PC.

Could someone help with a code snippet or give me a hint how to do that?

I use this sketch with my serial monitor that works

void setup() {
	// initialize both serial ports:
	Serial.begin(38400);
	Serial2.begin(38400);
}

void loop() {
	// read from port 1, send to port 0:
	if (Serial2.available()) {
		int inByte = Serial1.read();
		Serial.write(inByte);
	}

	// read from port 0, send to port 1:
	if (Serial.available()) {
		int inByte = Serial.read();
		Serial2.write(inByte);
	}
}

Take a look at Robin2's excellent serial handling basics tutorial

Thanks for the hint

Joe

You choose not to identify the particular sensor you have... Any reason for keeping that a secret?

Hi it's not a secret at all. It's from leveldevelopments model HPS-05-1-232
https://www.leveldevelopments.com/products/inclinometers/inclinometer-sensors/single-axis-inclinometer-sensors/hps-series/hps-05-1-232-precision-inclinometer-single-axis-5-rs232-output/

Data sheet

I read through the named basic serial tutorial but couldn't find a real solution.

My code for now

void setup()
{
 Serial.begin(38400);
 Serial2.begin(38400);
}

void loop()
{
 Serial2.write("get---x");
 while (Serial2.available()) {
 int inByte = Serial2.read();
 Serial.write(inByte);
 }
 Serial.println();
 delay(1000);
 Serial2.write("gettemp");
 while (Serial2.available()) {
 int inByte = Serial2.read();
 Serial.write(inByte);
 }
 Serial.println();
 delay(1000);
}

This works but brings sporadic failures in the sent values.

Has anybody a better solution, maybe readout the exact number of sent chars?

Any solution not involving delay(1000); would be an improvement, surely?

The delay is just for testing. I will not use the code in the loop in the end I will create a function to get the sensor value.

Having several example of the returned results would help but have you tried parseFloat to see if it works?
It might stumble if you have a leading + character but then you could maybe read the results into a buffer using readBytesUntil and then start at the second character.