ARTICLE AD BOX
I made a simple unity program that processes serial data from an Arduino (which is actually an ESP32 board with the Arduino core) and a potentiometer, and uses the data to affect a gameObject's position. It also sends data that turns on or turns off a led.
This is the board's c++ code (Note: I used a library that allows me to map my potentiometer's input into a floating point):
#include <MapFloat.h>; const int potPin = 5; const int ledPin = 2; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(potPin, INPUT); pinMode(ledPin, OUTPUT); } void loop() { // put your main code here, to run repeatedly: float readValue = mapFloat(analogRead(potPin), 0, 4095, -8, 8); Serial.println(readValue); if (Serial.available()) { char cmd = Serial.read(); if(cmd == '1') { digitalWrite(ledPin, 1); } if(cmd == '0') { digitalWrite(ledPin, 0); } } }This is the c# code for a unity script that connects to the Arduino
using UnityEngine; using System.IO.Ports; public class arduinoConnector : MonoBehaviour { // Start is called once before the first execution of Update after the MonoBehaviour is created SerialPort serial = new SerialPort("COM7", 9600); void Start() { serial.Open(); serial.ReadTimeout = 100; } // Update is called once per frame void Update() { string data = serial.ReadLine(); Debug.Log(data); float value = float.Parse(data); transform.position = new Vector3(value, -4, 0); } private void OnApplicationQuit() { serial.Close(); } public void turnOn() { serial.Write("1"); } public void turnOff() { serial.Write("0"); } }However, when I test out the program and specifically the gameObject that's controlled by the potentiometer, I find the way it moves to be sluggish and choppy despite running on a pretty new gaming laptop, which is not good for the type of game I wanted to make with these tools.
What could I do to help make my serial connection with the Arduino and the potentiometer more smooth?
