The Arduino code, in both the calibrated and uncalibrated version, send X, Y and Z coordinates from the 9 DoF sensor over serial. | are used as data delimiters and a line break is added after the Z data point.

//uncalibrated code loop

lsm6ds.getEvent(&accel, &gyro, &temp);

x = map(accel.acceleration.x, -12, 11, 180, -180); 
y = map(accel.acceleration.y, -19, 20, -180, 180); 
z = map(accel.acceleration.z, -17, 15, 180, -180); 

Serial.print("|");
Serial.print(x);
Serial.print("|");
Serial.print(y);
Serial.print("|");
Serial.print(z);
Serial.println();
delay(50);
//calibrated code loop

roll = filter.getRoll();
pitch = filter.getPitch();
heading = filter.getYaw();
Serial.print("|");
Serial.print(heading);
Serial.print("|");
Serial.print(pitch);
Serial.print("|");
Serial.print(roll);
Serial.println();

The C# Script

In the C# script, a serial port is opened and the incoming baud rate is set. You will change the serial port to match your board's port. t represents the object that will be rotated in Unity. By making it a public object, it will appear in Unity as an editable value.

SerialPort stream = new SerialPort("COM52", 9600);

public Transform t;

In the loop, the incoming serial data is parsed using the | delimiter. The X, Y and Z values are assigned to individual variables and converted to floats.

string UnSplitData = stream.ReadLine();
print(UnSplitData);
string[] SplitData = UnSplitData.Split('|');

float AccX = float.Parse(SplitData[1]);
float AccY = float.Parse(SplitData[2]);
float AccZ = float.Parse(SplitData[3]);

The X, Y and Z data are packed into a Vector3 object. Finally, the data is sent to the Unity and applied to the destination 3D object using a rotation with Quaternion.Slerp() to apply the X, Y and Z coordinates as Euler measurements.

lastData = new Vector3(AccX, AccY, AccZ);

t.transform.rotation = Quaternion.Slerp(t.transform.rotation, Quaternion.Euler(lastData), Time.deltaTime * 2f);

This guide was first published on Aug 31, 2022. It was last updated on Apr 09, 2024.

This page (How the Two Scripts Work Together) was last updated on Mar 08, 2024.

Text editor powered by tinymce.