Skip to content

16. Interface and application programming

This week I worked on defining my final project idea and started to getting used to the documentation process.

Unity

Display the value obtained from the sensor using Unity.

  • Unity
  • Platform for game development
  • SerialPort
  • Class used for serial communication with C#

Unity

The following sources are used by Unity.

///SerialHandler.cs

using System.Collections;
using System.IO.Ports;
using System.Threading;
using UnityEngine;

/// <summary>
/// Class for serial communication
/// </summary>
public class SerialHandler : MonoBehaviour
{
  /// <summary>
  ///     delegate type that receives one argument of type string
  /// </summary>
  /// <param name="message"></param>
  public delegate void SerialReadEventHandler(string message);

  /// <summary>
  ///     Define the delegate type event created above
  /// </summary>
  public event SerialReadEventHandler OnDataReceived = delegate { };

  /// <summary>
  /// port name used for serial communication
  /// </summary>
  public string portName = "/dev/tty.usbmodem1421 or COM1";

  /// <summary>
  /// Match with Arduino settings
  /// </summary>
  public int baudRate = 19200;

  /// <summary>
  /// SerialPort
  /// </summary>
  private SerialPort port;

  /// <summary>
  /// readingData
  /// </summary>
  private string readData;

  /// <summary>
  ///The method called at startup 
  /// </summary>
  void Awake()
  {
    port = new SerialPort(portName, baudRate);
    port.ReadTimeout = 1000;
    port.NewLine = "\n";
    port.Open();

    StartCoroutine("Read");
  }

  /// <summary>
  /// Method called every frame
  /// </summary>
  void Update()
  {
    if (readData.Length > 0)
    {
      OnDataReceived(readData);
      readData = "";
    }
  }

  /// <summary>
  /// Method called when destroying instance
  /// </summary>
  void OnDestroy()
  {
    if (port != null && port.IsOpen)
    {
      port.Close();
      port.Dispose();
    }
  }

  /// <summary>
  /// Read from the port each 100ms
  /// </summary>
  private IEnumerator Read()
  {
    while (port != null && port.IsOpen)
    {
      try
      {
        readData = port.ReadLine();
      }
      catch (System.Exception e)
      {
        Debug.LogWarning(e.Message);
      }
      yield return new WaitForSeconds(0.1f);
    }
  }

  /// <summary>
  /// Write to the port 
  /// </summary>
  /// <param name="message"></param>
  public void Write(string message)
  {
    try
    {
      port.Write(message);
    }
    catch (System.Exception e)
    {
      Debug.LogWarning(e.Message);
    }
  }
}
///ReadSerial.cs

using System.Collections;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// Class that uses serial communication
/// </summary>
public class ReadSerial : MonoBehaviour
{
  /// <summary>
  /// SerialHandler
  /// </summary>
  public SerialHandler serialHandler;

  /// <summary>
  /// display text instance 
  /// </summary>
  public Text text;

  /// <summary>
  /// The method to be called at start time
  /// </summary>
  void Start()
  {
    // Register OnDataReceived method of this class to OnDataReceived event 
    serialHandler.OnDataReceived += OnDataReceived;
  }

  /// <summary>
  /// OnDataReceived event
  /// </summary>
  /// <param name="readData"></param>
  void OnDataReceived(string readData)
  {
    try
    {
      byte[] data = System.Text.Encoding.ASCII.GetBytes(readData);
      if (data.Length < 2) return;
      float val = (data[0] << 8) + (data[1] & 0Xff);
      // write on the text
      text.text = (val / 100).ToString();
    }
    catch (System.Exception e)
    {
      Debug.LogWarning(e.Message);
    }
  }
}

Perform serial communication in Unity using the above code

  1. Add an empty object.
    • createEmpty
  2. Change the name to SerialHander and add SerialHander.cs to the Inspector
    • attachSerialHandler
  3. Add text to the scene.
    • createText
  4. Add ReadSerial.cs to text
    • Text
  5. Set the serial handler settings to appropriate values
    • settingSerialHandler

Arduino

The following is the Arduino program for serial communication.

// Using GroveConnectors
#define GROVE_R1 PA2 // Right 1
#define GROVE_R2 PA3 // Right 2
#define GROVE_L1 PA7 // Left 1
#define GROVE_L2 PB2 // Left 2

// Using Serial I/O
// ATTiny44 is not available Serial
// Alternative SoftwareSerial Library
#include <SoftwareSerial.h>
SoftwareSerial softSerial(0,1); // RX, TX

// for reading GroveThermoSensorV1.2 value
const int B = 4275;               // B value of the thermistor
const int R0 = 100000;            // R0 = 100k

void setup() {
  // put your setup code here, to run once:
  pinMode(GROVE_L1,INPUT);
  pinMode(GROVE_R2,OUTPUT);
  softSerial.begin(19200);
}

void loop() {
  // read the value from the sensor:
  // analogRead
  int temperature = getTemperature(); 
  // write x value  

  // Convert from float type (4 bytes) to int type (2 bytes).
  // Multiply by 100 to use decimal places.
  softSerial.write((int16_t)(temperature * 100) >> 8);
  softSerial.write((int16_t)(temperature * 100) & 0xFF);
  softSerial.write('\n');
  // wait 500 mill second
  delay(500);
}

/**
 * calculate Temperature Value
 * return temperature -40 ~ +125 ℃
 */
float getTemperature(){
  // read the value
  int val = analogRead(GROVE_L1);
  float R = 1023.0/val-1.0;
  R = R0*R;
  float temperature = 1.0/(log(R/R0)/B+1/298.15)-273.15; // convert to temperature
  return temperature;
}

Result

Text display of serial data from Arduino.

Files