Dear members,
I am trying to make two arduino unos (A1 & A2) talk to each other using a simple 5 mtr three core cable. I connect the following:
TxD (A1) → RxD (A2)
RxD (A1) → TxD (A2)
Gnd (A1) → Gnd (A2)
The transmitter sends the pressure data from two pressure sensors after converting each reading to chr array and then concatenated. The code is given as:
#include<stdlib.h>
// These constants won't change. They're used to give names
// to the pins used:
int analogInPin0 = A0; // Analog input pins that the Refernece sensors are attached to
int analogInPin1 = A1;
int sensorValue0 = 0; // value read from the pot
int sensorValue1 = 0;
int sensorMin = 1023; // minimum sensor value
int sensorMax = 0; // maximum sensor value
float pressure0, pressure1;
char outstr1[10];
char outstr2[10];
void setup() {
pinMode(A0, INPUT);
pinMode(A1, INPUT);
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop() {
sensorValue0 = analogRead(analogInPin0);
sensorValue1 = analogRead(analogInPin1);
float voltage0 = sensorValue0 * (5.000 / 1023.000);
float voltage1 = sensorValue1 * (5.000 / 1023.000);
pressure0 = ((voltage0*12.5)-28.125);
pressure1 = ((voltage1*12.5)-28.125);
dtostrf(pressure0,7,4,outstr1);
dtostrf(pressure1,7,4,outstr2);
strcat(outstr1," ");
strcat(outstr1," ");
//strcat(outstr1," ");
strcat(outstr1,outstr2);
Serial.println(outstr1);
delay(5000);
}
The receiver is just reading this char array from serial port and converting it into a String object.
The code is:
#include <stdlib.h>
char instr[18] = {'\0'};
void setup()
{
Serial.begin(9600); // Debugging only
}
void loop()
{
int i=0;
if (Serial.available())
{
while(Serial.available()) {
instr[i++] = Serial.read();
}
String str(instr);
String s1 = str.substring(0,8);
String s2 = str.substring(9,18);
Serial.print(s2);
}
}
My sensor data is getting displayed if I try to print ‘str’ or ‘instr’. But I want to split my incoming string into two to separate between data from different pressure sensors. That’s why the ‘substring’ function is used. But somehow it doesn’t work. If I try to split and print s1’ and/or ‘s2’ individually, then whole incoming string is copied into ‘s1’ and nothing appears on the serial monitor for ‘s2’.
Can somebody indicate to me why ‘substring’ is not working? It would be greatly helpful!! And any additional suggestions to improve this code for serial communication are welcome with a big smile and a thank you!!
Cheers!
Pramit