Hi everyone. im kinda new here so ill be brief
i have this code that reads data from com port 8 and uses it to move an object on Y axis. but the problem is the object doesnt even move. what should i do?
here is my code:
</>using System;
using System.IO.Ports;
using System.Threading;
using UnityEngine;
public class SerialYController : MonoBehaviour
{
private SerialPort _serialPort;
private Thread _serialThread;
private bool _keepReading;
private int _axisY = 0; // Integer for the Y axis value
private object _lockObject = new object(); // To synchronize access to _axisY
// Adjust this factor to scale movement properly
public float movementScalingFactor = 1f; // Can be adjusted for desired movement scale
void Start()
{
InitializeSerialPort();
}
void Update()
{
int axisY;
// Safely read the shared data
lock (_lockObject)
{
axisY = _axisY;
}
// Map serial data to Unity controls
float movement = axisY * movementScalingFactor;
// Move the object along the Y axis
transform.Translate(new Vector3(0, movement, 0) * Time.deltaTime);
// Log the current position and received data
Debug.Log($"Current Y Position: {transform.position.y}, Received Y: {axisY}, Movement: {movement}");
}
void InitializeSerialPort()
{
_serialPort = new SerialPort("COM8", 115200)
{
ReadTimeout = 500,
WriteTimeout = 500
};
try
{
_serialPort.Open();
_keepReading = true;
_serialThread = new Thread(ReadSerialData) { IsBackground = true };
_serialThread.Start();
Debug.Log("Serial port opened.");
}
catch (Exception ex)
{
Debug.LogError($"Error opening serial port: {ex.Message}");
}
}
void ReadSerialData()
{
while (_keepReading)
{
try
{
string data = _serialPort.ReadLine();
Debug.Log($"Data received: {data}");
ProcessSerialData(data);
}
catch (TimeoutException)
{
// Handle the timeout exception if needed
}
catch (Exception ex)
{
Debug.LogError($"Error reading serial data: {ex.Message}");
}
}
}
void ProcessSerialData(string data)
{
try
{
// Example: assuming data is a single integer value
if (int.TryParse(data.Trim(), out int axisY))
{
lock (_lockObject)
{
_axisY = axisY;
}
Debug.Log($"Parsed Y value: {_axisY}");
}
else
{
Debug.LogWarning($"Failed to parse Y value from '{data}'");
}
}
catch (Exception ex)
{
Debug.LogError($"Error processing serial data: {ex.Message}");
}
}
void OnApplicationQuit()
{
_keepReading = false;
if (_serialThread != null && _serialThread.IsAlive)
{
try
{
_serialThread.Join(1000); // Wait for a maximum of 1 second
}
catch (ThreadStateException ex)
{
Debug.LogError($"Error stopping thread: {ex.Message}");
}
}
if (_serialPort != null && _serialPort.IsOpen)
{
_serialPort.Close();
}
}
}</>