コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】【Arduino】Z キーが押されている時に LED を光らせる

スクリプト

Arduino

void setup()
{
  Serial.begin( 9600 );
  pinMode( 13, OUTPUT );
}

void loop()
{
  if ( Serial.available() <= 0 ) return;

  char data = Serial.read();
  int num = data == '1' ? HIGH : LOW;
  digitalWrite( 13, num );
  Serial.flush();
}

Unity

using System.IO.Ports;
using UnityEngine;

public class Example : MonoBehaviour
{
    private SerialPort serial;

    private void Awake()
    {
        serial = new SerialPort( "COM3", 9600 );
        serial.Open();
    }
    
    private void Update()
    {
        var isPress = Input.GetKey( KeyCode.Z );
        var str     = isPress ? "1" : "0";

        serial.Write( str );
    }
}

デモ