PICのコード変更
まずはPICのコード変更から。
ジャイロセンサーからの値のみに絞り、xyzの値を,(カンマ)で区切って出力するように変更。
#include "mcc_generated_files/mcc.h"
#include "mcc_generated_files/examples/i2c_master_example.h"
#include <stdio.h>
#include <math.h>
uint8_t Buffer1[6];
int16_t gxRaw, gyRaw, gzRaw;
void main(void)
{
SYSTEM_Initialize();
I2C_Write1ByteRegister(0x68, 0x6B, 0x00); //Internal 8MHz oscillator
I2C_Write1ByteRegister(0x68, 0x6A, 0x00); //I2C MasterMode OFF
I2C_Write1ByteRegister(0x68, 0x37, 0x02); //I2C_BYPASS_EN
I2C_Write1ByteRegister(0x68, 0x23, 0xFF); //FIFO Enable
I2C_Write1ByteRegister(0x68, 0x1B, 0x18); //Full Scale Range ±2000°/s
I2C_Write1ByteRegister(0x0D, 0x0B, 0x01);
I2C_Write1ByteRegister(0x0D, 0x09, 0x11);
while (1)
{
I2C_ReadDataBlock(0x68, 0x43, Buffer1, 6);
gxRaw = Buffer1[0] << 8 | Buffer1[1];
gyRaw = Buffer1[2] << 8 | Buffer1[3];
gzRaw = Buffer1[4] << 8 | Buffer1[5];
printf("%d,%d,%d\r\n",gxRaw, gyRaw, gzRaw);
__delay_ms(300);
}
}
Unityへの反映
UnityではUpdateのタイミングで直方体オブジェクトの角度プロパティを取得し、xyzそれぞれの角度プロパティにジャイロセンサー値を加算して動きがどうなるかみてみます。
using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using System;
using UnityEngine;
public class Bluetooth_to_Unity : MonoBehaviour
{
private SerialPort port;
private float gx, gy, gz;
// Start is called before the first frame update
void Start()
{
port = new SerialPort("COM7", 9600, Parity.None, 8, StopBits.One);
Debug.Log("start");
port.NewLine = "\r\n";
port.ReadBufferSize = 64;
port.ReadTimeout = 50;
port.Open();
}
// Update is called once per frame
void Update()
{
if (port.IsOpen)
{
try
{
String data = port.ReadLine();
string[] arr = data.Split(',');
gx = (int.Parse(arr[0]))/16.4f;
gy = (int.Parse(arr[1]))/16.4f;
gz = (int.Parse(arr[2]))/16.4f;
Debug.Log(gx.ToString() + ", " + gy.ToString() + ", " + gz.ToString() + "\r\n");
}
catch (TimeoutException)
{
}
}
Transform myTransform = this.transform;//現在の角度を取得
Vector3 localAngle = myTransform.localEulerAngles;
localAngle.x = localAngle.x + gx; //現在の角度にセンサー値をプラス
localAngle.y = localAngle.y + gy;
localAngle.z = localAngle.z + gz;
myTransform.localEulerAngles = localAngle; // 更新後の角度を設定
}
}
Unityでの実行結果
センサー基板は机上に触らず固定しているにもかかわらず、開始直後からオブジェクトが回転を始めています。センサー値に何らかの補正が必要なようです。ではまた。