Hello, I am using a MPU6050 gyro sensor as a controller for an interactive 3D environment I made in Unity, so I'm sending the values to Unity using Serial. I am using the MPU6050_tockn library to read from the gyro and wrmhlto read the data in Unity - the code below is based on the example from the wrmhl github.
I need to grab the value difference between the current reading and the one before that, ie if the gyro moves from X 10 to X 15 I want to extract the value 5 and send to serial, and if the gyro doesn't move it sends 0.
I'm very new to this, I'm sure it's pretty easy but I have googled and checked some references and haven't been able to find any answer that I understood.
Here is my code:
#include <MPU6050_tockn.h>
#include <Wire.h>
MPU6050 mpu6050(Wire);
#define SERIAL_USB
void setup() {
#ifdef SERIAL_USB
Serial.begin(9600);
while (!Serial);
#endif
Wire.begin();
mpu6050.begin();
mpu6050.calcGyroOffsets(true);
}
void loop() {
mpu6050.update();
String x = String((int)mpu6050.getAngleX());
String y = String((int)mpu6050.getAngleY());
String z = String((int)mpu6050.getAngleZ());
sendData(x+"_" + y+"_" + z+"_");
sendData("\n"); //adding underscores and line break to parse the data in Unity
delay(5);
}
void sendData(String data){
#ifdef NATIVE_USB
SerialUSB.println(data);
#endif
#ifdef SERIAL_USB
Serial.println(data);
#endif
}
ieee488:
Converting integers to String is a bad idea since you will need those integers.
I just noticed that too. I've used a lot of example code for parts of the project so maybe that's a leftover from some other application that I copied it from. Thanks for pointing it out, I will look into it.
ieee488:
No idea what you mean by X 10 to X 15
inside setup( )
currentX = 0;
...
inside loop()
newX = mpu6050.getAngleX();
if ((currentX - newX) > 5)
{
do something
}
currentX = newX; //make the new value the current value
I don't think this is what I'm after. Re: "X10 to X15" - the gyro sensor is measuring x, y and z angles continuously and outputting as values between roughly -150 and 150. I want to extract a value that's always defined as the difference between the last two readings taken from the sensor.
So, if I move the sensor on the X axis, from the position where it outputs "x angle 10" (what I called X10 above) to where it outputs "x angle 15", I want my "difference value" to be 5 on the first update after I moved the sensor - and then on the next update to change to whatever the difference is between "X angle 15" and what the sensor currently measures (which will be 0 if I haven't moved it further), etc. Does this make it more clear?
I'm not looking for the arduino to do anything besides send the values to serial and 5 is just an arbitrary number in this case so I don't see the use of the if statement.