Download MPR 121 project

This project demonstrates how we can connect a capacitive touch sensor in Unity. For this project, I used Adafruoit's MPR121 sensor, available here.

Extending libraries

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

Sending capacitive touch events from Arduino to Unity

To connect the sensor to Arduino, we used the library Adafruit_mpr121.

This library can be download through the library manager of Arduino. Sketch>Include Library>Manager Libraries>...[search MPR 121].


// Setup MPR 121
#include <Wire.h> // https://learn.adafruit.com/adafruit-mpr121-12-key-capacitive-touch-sensor-breakout-tutorial/wiring
#include "Adafruit_MPR121.h" 

#include <Uduino.h>
Uduino uduino("MPR121");

#ifndef _BV
#define _BV(bit) (1 << (bit))
#endif

Adafruit_MPR121 cap = Adafruit_MPR121();

uint16_t lasttouched = 0;
uint16_t currtouched = 0;
bool initCap = false;
void setup() {
  Serial.begin(9600);

  while (!Serial) { // needed to keep leonardo/micro from starting too fast!
    delay(10);
  }

  if (!cap.begin(0x5A)) {
     initCap = false;
  } else {
     initCap = true;
  }
}

void loop() {

  uduino.update();

  if (uduino.isConnected()) {
    if(!initCap) {
      uduino.println("MPR121 not found, check wiring?");
      return;
    }
    // Get the currently touched pads
    currtouched = cap.touched();

    for (uint8_t i = 0; i < 12; i++) {
      // it if *is* touched and *wasnt* touched before, alert!
      if ((currtouched & _BV(i)) && !(lasttouched & _BV(i)) ) {
        uduino.print(i); uduino.println(" touched");
      }
      // if it *was* touched and now *isnt*, alert!
      if (!(currtouched & _BV(i)) && (lasttouched & _BV(i)) ) {
        uduino.print(i); uduino.println(" released");
      }
    }
    lasttouched = currtouched;
  }
  uduino.delay(15);
}

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

Get Touch data on Unity

On unity, we can now parse the data and use it to control UI elements.

using UnityEngine;
using UnityEngine.UI;
using Uduino;

public class MPR121 : MonoBehaviour
{

    public Image[] images;

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

    void Update()  {  }

    void DataReceived(string data, UduinoDevice baord)
    {
        string[] values = data.Split(' ');
        int pressed = 0;
        bool ok = int.TryParse(values[0], out pressed); // Trying to parse data to a float
        string status = values[1];

        if (ok)
        {
            Debug.Log("Finding new touch " + data);
            if (status == "touched") images[pressed].color = new Color(0, 1, 1);
            else if (status == "released") images[pressed].color = new Color(0, 0, 0);
        }
        else
        {
            Debug.Log("Error parsing " + data);
        }
    }
}