sea-battle/Assets/Scripts/ArduinoController.cs
2026-01-09 08:45:22 +03:00

99 lines
2.0 KiB
C#

using System;
using System.Collections;
using System.IO.Ports;
using UnityEngine;
// ÓÑÒÀÐÅÂØÈÉ ÊÎÄ , ÑÅÉ×ÀÑ ÐÀÁÎÒÀ ×ÅÐÅÇ ComWrapper
public class ArduinoController : MonoBehaviour
{
public static ArduinoController Instance;
public string portName = "COM3";
public int baudRate = 115200;
private SerialPort serial;
void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
void Start()
{
portName = SerialPort.GetPortNames()[^1];
serial = new SerialPort(portName, baudRate);
serial.ReadTimeout = 50; // íå áëîêèðóåò ïîòîê
try
{
serial.Open();
Debug.Log("Arduino ïîäêëþ÷åíà");
}
catch (Exception e)
{
Debug.LogError("Îøèáêà ïîäêëþ÷åíèÿ: " + e.Message);
}
}
void Update()
{
// Ïðè¸ì äàííûõ îò Arduino
if (serial != null && serial.IsOpen && serial.BytesToRead > 0)
{
try
{
string line = serial.ReadLine();
Debug.Log("Ïîëó÷åíî: " + line);
// ìîæíî ïàðñèòü êîìàíäó è çàïóñêàòü ýôôåêòû
}
catch (TimeoutException) { }
}
}
public void SendCommand(int cmd)
{
if (serial != null && serial.IsOpen)
{
serial.WriteLine(cmd.ToString());
Debug.Log("Îòïðàâëåíî: " + cmd);
}
}
public void Blink(float duration = 0.3f)
{
StartCoroutine(BlinkCoroutine(duration));
}
private IEnumerator BlinkCoroutine(float duration)
{
if (serial == null)
{
yield break;
}
serial.WriteLine("80101"); // âêëþ÷èòü áåëûì
yield return new WaitForSeconds(duration);
serial.WriteLine("80100"); // âûêëþ÷èòü
}
void OnApplicationQuit()
{
if (serial != null && serial.IsOpen)
serial.Close();
}
}