Unity マイコン間のシリアル通信(送受信)
https://gyazo.com/21ad9d1c840f2ef9999f2ad3c451d7fc
M5 Atom lite(マイコン) 側
送信:ボタンを押すと「a」を送信します。
受信:受信した文字によってLEDの色を変更します。
code: M5Atom_Serial_LED.ino
#include "M5Atom.h" //M5Atom.hをインクルード
uint8_t DisBuff2 + 5 * 5 * 3; //LED配色バッファ
//配色バッファ設定関数
void setBuff(uint8_t Rdata, uint8_t Gdata, uint8_t Bdata)
{
DisBuff0 = 0x05;
DisBuff1 = 0x05;
for (int i = 0; i < 25; i++)
{
DisBuff2 + i * 3 + 0 = Rdata;
DisBuff2 + i * 3 + 1 = Gdata;
DisBuff2 + i * 3 + 2 = Bdata;
}
}
void setup()
{
M5.begin(true, true, true); // 初期化
Serial.begin(115200); //USBシリアル初期化
delay(10); //10msec 待機
setBuff(0xff, 0x00, 0x00); //配色バッファ初期化 
M5.dis.displaybuff(DisBuff); //AtomLED初期化
}
char ch = 0; //シリアル通信用変数(1文字)
void loop()
{
if(Serial.available()) {
ch = Serial.read();
}
switch (ch)
{
case '0':
setBuff(0x40, 0x00, 0x00);
break;
case '1':
setBuff(0x00, 0x40, 0x00);
break;
case '2':
setBuff(0x00, 0x00, 0x40);
break;
case '3':
setBuff(0x20, 0x20, 0x20);
break;
default:
break;
}
M5.dis.displaybuff(DisBuff);
if (M5.Btn.wasPressed())
{
Serial.println("a");
}
delay(50);
M5.update();
}
Unity 側
送信:キー(左、右、下、スペース)を押すと設定した文字を送信します。
受信:受信した文字をログに表示します。
code: Serial.cs
// ファイル名 Serial.cs
// ファイル名とクラス名をあわせる必要があるので注意
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System;
using System.IO.Ports;
using UnityEngine;
using UniRx;
public class Serial : MonoBehaviour {
public string portName;
public int baurate;
SerialPort serial;
bool isLoop = true;
void Start ()
{
this.serial = new SerialPort (portName, baurate, Parity.None, 8, StopBits.One);
try
{
this.serial.Open();
Scheduler.ThreadPool.Schedule (() => ReadData ()).AddTo(this);
}
catch(Exception e)
{
Debug.Log ("can not open serial port");
}
}
void Update()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
Write("1");
}
if (Input.GetKey(KeyCode.RightArrow))
{
Write("2");
}
if (Input.GetKeyDown(KeyCode.Space))
{
Write("3");
}
}
public void ReadData()
{
while (this.isLoop)
{
string message = this.serial.ReadLine();
Debug.Log( message );
}
}
public void Write(string message)
{
this.serial.Write(message);
Debug.Log( message );
}
void OnDestroy()
{
this.isLoop = false;
this.serial.Close ();
}
}
参考にしたサイト
【研究室セミナー】超スマート社会をつくるVRxIoTセミナ「実世界を仮想化するフィジカル・コンピューティング入門」【2018・2019】
【M5Stackでシリアル通信】M5ATOM Matrix/Liteを使って、シリアルデータをパソコンに取り込む方法
UnityとArduinoをシリアル通信
#シリアル通信
https://gyazo.com/71c7de59f100448c29cdb7f29fbd171b
Communication Robotics Lab.