You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
101 lines
2.6 KiB
101 lines
2.6 KiB
3 years ago
|
using System;
|
||
|
using System.Collections;
|
||
|
using System.Collections.Generic;
|
||
|
using System.IO.Ports;
|
||
|
using System.Threading;
|
||
|
using UnityEngine;
|
||
|
using LitJson;
|
||
|
|
||
|
public class MyAccelSerialPort : MonoBehaviour
|
||
|
{
|
||
|
private SerialPort serialPort;
|
||
|
private Thread readPortData;
|
||
|
//public List<byte> listReceive = new List<byte>();
|
||
|
public string jsonData = "";
|
||
|
//根据受力情况设置小球的位置
|
||
|
public Transform AccelBall;
|
||
|
|
||
|
|
||
|
// Use this for initialization
|
||
|
void Start()
|
||
|
{
|
||
|
//Application.targetFrameRate = 120;
|
||
|
try
|
||
|
{
|
||
|
serialPort = new SerialPort("COM4", 115200);
|
||
|
serialPort.ReadTimeout = 500;
|
||
|
if (!serialPort.IsOpen)
|
||
|
{
|
||
|
serialPort.Open();
|
||
|
}
|
||
|
readPortData = new Thread(new ThreadStart(readData));
|
||
|
readPortData.IsBackground = true;
|
||
|
readPortData.Start();
|
||
|
}
|
||
|
catch (Exception)
|
||
|
{
|
||
|
throw;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Update is called once per frame
|
||
|
void Update()
|
||
|
{
|
||
|
if (jsonData != "")
|
||
|
{
|
||
|
MPUAccelData mpudata_ = JsonMapper.ToObject<MPUAccelData>(jsonData);
|
||
|
AccelBall.localPosition = new Vector3((float)mpudata_.AccelX/2, (float)mpudata_.AccelY/2 - 2.3f, (float)mpudata_.AccelZ/2 + 1.2f);
|
||
|
//Debug.LogWarning("Temperature = " + mpudata_.Temperature);
|
||
|
//print("x=" + mpudata_.GyroX + "||y=" + mpudata_.GyroY + "||z=" + mpudata_.GyroZ + "____Ax=" + mpudata_.AccelX + "||Ay=" + mpudata_.AccelY + "||Az=" + mpudata_.AccelZ + "-----" + Time.deltaTime);
|
||
|
//MpuBoardTrans.transform.localPosition += new Vector3(speedX/1000, 0, 0);
|
||
|
//print("speed="+speedY);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
//结束后关闭串口
|
||
|
private void OnDestroy()
|
||
|
{
|
||
|
if (serialPort.IsOpen)
|
||
|
serialPort.Close();
|
||
|
readPortData.Abort();
|
||
|
}
|
||
|
|
||
|
//弧度转角度
|
||
|
private float TransRadToAngle(double rad)
|
||
|
{
|
||
|
//return -(float)rad * 180 / Mathf.PI;
|
||
|
return (float)rad * 90;
|
||
|
}
|
||
|
/// <summary>
|
||
|
/// 读取数据
|
||
|
/// </summary>
|
||
|
private void readData()
|
||
|
{
|
||
|
try
|
||
|
{
|
||
|
while (serialPort != null && serialPort.IsOpen)
|
||
|
{
|
||
|
byte addr = Convert.ToByte(serialPort.ReadByte());
|
||
|
serialPort.DiscardInBuffer();
|
||
|
//listReceive.Add(addr);
|
||
|
//print("{"+serialPort.ReadLine());
|
||
|
jsonData = "{" + serialPort.ReadLine();
|
||
|
}
|
||
|
}
|
||
|
catch (Exception)
|
||
|
{
|
||
|
throw;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|
||
|
private void caculateSpeed(float accelSpeed)
|
||
|
{
|
||
|
|
||
|
}
|
||
|
}
|