# Track 2D Movement Using Arduino Ultrasonic Sensors and Visualize in Unity

3,571

40

2

please watch the video for better demonstration.

we will be using two ultrasonic sensors, one to track horizontal movement and the other to track the vertical. the key is in placing the sensors and using a tool(a shoe box in our example) that will remain at a visible range to both sensors at the top, bottom , left and right edges. and the whole process is visualized by moving an object in unity.

### Teacher Notes

Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.

## Step 1: Get the Parts

1- 2 ultrasonic sensors

2- 8 female-male wires

3- 4 male-male wires

4- 2 shoe boxes

6- pushpins

7-small screw driver

8- a box cutter

## Step 2:

1- cut the side wall of the shoe box and using the push pins place it on top to hold our y-axis ultrasonic sensor

2-make holes for our sensors, for me I drew each circle of the ultrasonic and used a box cutter . you need one on the side wall for the x-axis sensor and the other on the top wall for y-axis.

3- mount your arduino to the side of the shoebox and place your breadboard on top. we need them to be half way between the two sensors to make wiring easier.

4- connect your ultrasonics to the arduino and breadboard, each ultrasonic will need 4 wires..a ground, vcc, and two digital pins for trig and echo I used 5 and 4 for the x-axis , 7 and 6 for the y-axis.

(schematic will be available soon)

## Step 3: Lets Write Arduino Code

the code simply will read the two sensors reading make it into a string and send it to unity for processing. however, instead of reading values in centimeters we will do it in millimeter to provide a smoother movement in unity by making a slight change in the formula

const int TRIGX = 5;
const int ECHOX = 4;

const int TRIGY = 7;

const int ECHOY = 6;

void setup (){

Serial.begin(9600);

pinMode(TRIGX, OUTPUT);

pinMode(ECHOX, INPUT);

pinMode(TRIGY, OUTPUT);

pinMode(ECHOY, INPUT); }

void loop (){

int dataX = GetUltra(TRIGX,ECHOX);

int dataY = GetUltra(TRIGY,ECHOY);

Serial.flush();

Serial.print( dataX );

Serial.print(','); Serial.print( dataY );

Serial.println();

delay(20);

}

double GetUltra ( int trig , int echo){

digitalWrite(trig , LOW);

delayMicroseconds(2);

digitalWrite(trig, HIGH);

delayMicroseconds(8);

digitalWrite(trig, LOW);

double distance = ( pulseIn(echo, HIGH) )* 343.2 / 2000; return distance;

}

## Step 4: Lets Write Our Unity Code

1- edit>project settings>player> scroll down to optimization and change api compatibility to .NET 2.0

2-now we change the main camera into Orthographic and set the size to 5 and finally change it's position to

x = 9 , y = -6

3- create a cube and attach the script to it

```using UnityEngine;using System.Collections;
using System.IO.Ports;
public class axis : MonoBehaviour {    private Vector3 temp;    private SerialPort stream = new SerialPort(@"\\.\" + "COM11", 9600);	// Use this for initialization
void Start () {
stream.Open();
}

// Update is called once per frame
void Update () {

}
IEnumerator readString() {        while (true) {            if (stream.IsOpen) {                try
string[] values = value.Split(',');                    float x = int.Parse(values[0]);
float y = -1 * (int.Parse(values[1]));
x = x / 10f;
y = y / 10f;
temp = transform.position;
temp.x = x;
temp.y = y;
transform.position = temp;                }
catch (System.Exception) {                }            }            yield return null;        }    }
}```

## Recommendations

• ### Internet of Things Class

22,781 Enrolled

## 2 Discussions

i have hacked ps2 mouse which has x and y output...how move box in unity

Any advice how to rotate an object in unity given x,y,z accelerometer data?

Because pitch/roll/yaw only make sense given a fixed point of reference this is causing all kinds of strange artifacts like drifting, gimbal lock and cross-contamination on the axis that I didn't ask to change.

I've read some people have had luck creating an artificial horizon.. they project a fixed vector and a variable one onto a common X/Z plane, then they apply the yaw ,for example, around the global axis instead of the object's axis. Although I've read even this isn't perfect, and it's better to use local rotations to update the forward vector together with a reference up vector to build the final orientation.

Unfortunately, I haven't seen an actual implementation for any of this... I understand only 2 angles (pitch,yaw, or roll) can be derived from a 3-axis acclerometer, but what does the unity code look like transform.rotate,LookRotation,ProjectOnPlane, Quaternion.Euler, etc?