Don't do 2 Bluetooth writes. It is easy to get out of sync.
Sending one joystick's values.
#include <SoftwareSerial.h>
const byte xPin = A0;
const byte yPin = A1;
SoftwareSerial ss(4, 7);
void setup()
{
Serial.begin(115200);
ss.begin(9600);
}
void loop()
{
static unsigned long timer = 0;
unsigned long interval = 1000;
if (millis() - timer >= interval)
{
timer = millis();
int xValue = analogRead(xPin);
int yValue = analogRead(yPin);
Serial.print("x value = ");
Serial.print(xValue);
Serial.print(" y value = ");
Serial.println(yValue);
char buffer[15];
snprintf(buffer, 14, "%d,%d", xValue, yValue);
Serial.println(buffer);
ss.println(buffer);
}
}
Receive one joystick data. Uses methods from the serial input basics tutorial: :
#include <SoftwareSerial.h>
int xValue = 0;
int yValue = 0;
const byte numChars = 32;
char receivedChars[numChars]; // an array to store the received data
boolean newData = false;
SoftwareSerial ss(4, 7);
void setup()
{
Serial.begin(115200);
ss.begin(9600);
}
void loop()
{
recvWithEndMarker();
//showNewData();
if (newData)
{
parseData();
displayData();
newData = false;
}
}
void recvWithEndMarker()
{
static byte ndx = 0;
char endMarker = '\n';
char rc;
while (ss.available() > 0 && newData == false)
{
rc = ss.read();
if (rc != endMarker)
{
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars)
{
ndx = numChars - 1;
}
}
else
{
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewData()
{
if (newData == true)
{
Serial.print("This just in ... ");
Serial.println(receivedChars);
//newData = false;
}
}
void parseData()
{
char *strings[2]; // an array of pointers to the pieces of the above array after strtok()
char *ptr = NULL; byte index = 0;
ptr = strtok(receivedChars, ","); // delimiter comma
while (ptr != NULL)
{
strings[index] = ptr;
index++;
ptr = strtok(NULL, ",");
}
//Serial.println(index);
/*
// print all the parts
Serial.println("The Pieces separated by strtok()");
for (int n = 0; n < index; n++)
{
Serial.print("piece ");
Serial.print(n);
Serial.print(" = ");
Serial.println(strings[n]);
}
*/
// convert string data to numbers, map to servo ranges
xValue = atoi(strings[0]);
yValue = atoi(strings[1]);
}
void displayData()
{
Serial.print("x value = ");
Serial.print(xValue);
Serial.print(" y value = ");
Serial.print(yValue);
Serial.println(); // blank line
}