Download HC-SR04 project

This project demonstrates how we can connect a proximity sensor in Unity. For this project, I used the HC-SR04 sensor, one of the most popular distance and proximity sensor. If your proximity sensor is different, this tutorial presents the method to connect any sensor in Unity.

Extending libraries

To have more in formations on how to augment existing libraries, you can watch the dedicated http://www.marcteyssier.com/uduino/tutorials/add-external-libraries video tutorial.

Sending proximity sensor from Arduino to Unity

To connect the distance sensor to Arduino, we used the library New Ping.
This library can be download through the library manager of Arduino. Sketch>Include Library>Manager Libraries>...[search New Ping] or on this url.


// Setup Sonar
#include <NewPing.h> //To add the library : Sketch>Include Library>Manager Libraries...> [search and add NewPing library] 
#define TRIGGER_PIN  12  
#define ECHO_PIN     11  
#define MAX_DISTANCE 300 
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); 

void setup() {
  Serial.begin(9600);
}

void loop() {
    Serial.println(sonar.ping_cm()); 
    delay(30);
}

If you add some Serial.print command in the setup function, it might break Uduino auto-detection process

At this stage, you can test the code in the Arduino serial monitor. Everything should work as expected. Now, you need to add Uduino library. At the top of the Arduino file, you can add the dependency and setup Uduino.

// Setup Uduino
#include <Uduino.h>
Uduino uduino("Range");

Then, we keep the same Arduino code and add uduino.update() in the loop function. To write the values only when the board is connected, we add the condition uduino.isConnected().

void loop() {
  uduino.update(); // This part is needed to be detected by Unity. 

  if (uduino.isConnected()) {
   uduino.println(sonar.ping_cm()); 
   delay(30);
  }
}

The values have to be written in the same "line". Serial.println should be called only once, ad the send of the loop.

Get sensor values on Unity

On unity, we can now parse the data (distance) and use it in the game.

public class GetDistanceHCSR : MonoBehaviour
{
    public Transform distancePlane;
    float distance = 0;

    void Start() {
      UduinoManager.Instance.OnDataReceived += DataReceived;
    }

    void Update()  {  
       distancePlane.transform.position = new Vector3(0, 0, distance );
    }

    void DataReceived(string data, UduinoDevice baord) {
       bool ok = float.TryParse(data, out distance ); 
     }
}