I am making a joystick and I am tryin to to get analog joystick module values and button values from uno and send it to esp32 with uart. But the values are not coming as expected. Normally it should be between 0-1023. Right now it is like in 13000. I am going to put my code here.
UNO's code
#define X1 A0
#define Y1 A1
#define X2 A2
#define Y2 A3
#define b1 7
#define b2 8
struct analog
{
unsigned long Xaxis;
unsigned long Yaxis;
};
analog state;
void setup()
{
Serial.begin(9600);
}
void loop()
{
state.Xaxis=analogRead(X1);
state.Yaxis=analogRead(Y1);
byte ptr;
ptr = (byte)&state;
byte counter = sizeof(state);
Serial.print('<');
do
{
byte m = (byte*)*ptr;
Serial.write(m);
Serial.print(m,HEX);
ptr++;
counter--;
}
while(counter != 0);
Serial.write('>'); //end of strauct data
Serial.println();
delay(2000);
}
ESP32's code
#define Rxpin 16
#define Txpin 17
struct analog
{
unsigned long Xaxis;
unsigned long Yaxis;
unsigned long button1;
int button2;
};
analog state;
byte myData[8];
bool flag = false;
void setup()
{
Serial.begin(115200);
Serial2.begin(9600, SERIAL_8N1, Rxpin, Txpin);
}
void loop()
{
byte n = Serial2.available();
if (n != 0 )
{
if (flag == false)
{
char x = Serial2.read();
if (x == '<')
{
flag = true;
}
}
else
{
Serial2.readBytesUntil('>', myData, 8);
//--- recreate structure-------
state.Xaxis = (myData[3]<<8)|myData[0];
state.Yaxis = (myData[7]<<8)|myData[4];
Serial.println(state.Xaxis,HEX);
Serial.println(state.Xaxis,DEC);
flag = false;
}
}
}
I approximately got the code from here Sending structs through serial. - Using Arduino / Programming Questions - Arduino Forum