0

当我第一次用我的 mpu6050 尝试 arduino 代码时,串行监视器显示读数。但是,当我尝试将其与统一联系起来时,无法统一显示或使用读数。我被这个问题困住了。我试图使我统一创建的立方体随着鼠标位置移动,然后被 mpu 6050 替换。

Arduino代码

#include <Wire.h>
#include <I2Cdev.h>
#include <MPU6050.h>

MPU6050 mpu;
int16_t ax, ay, az, gx, gy, gz;
int vx, vy;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  mpu.initialize();
  //if (!mpu.testConnection()) { while (1); }
}

void loop() {
 mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

 vx = ((gx+300)/150)-1;  // "+300" because the x axis of gyroscope give 
 values about -350 while it's not moving. Change this value if you get 
 something different using the TEST code, chacking if there are values far 
 from zero.
 vy = -(gz-100)/150; // same here about "-100"

 String output = String(gx) + ";" + String(gz) + ";" + String(vx) + ";" + 
 String(vy);

 Serial.println(output);
 Serial.flush();

 delay(10);
 }

统一代码

public class Cube : MonoBehaviour {

SerialPort stream = new SerialPort("COM4", 115200);
public Camera cam;
public float mousex;
public float mousey;
public GameObject target; // is the gameobject to
public float acc_normalizer_factor = 0.00025f;
public float gyro_normalizer_factor = 1.0f / 32768.0f;   // 32768 is max 
value captured during test on imu

//float curr_angle_x = 0;
//float curr_angle_y = 0;
//float curr_angle_z = 0;

float curr_offset_x = 0;
float curr_offset_y = -2;



void Start()
{

    stream.Open();


    cam = Camera.main;


}

void Update()
{
    string dataString = "null received";
    dataString = stream.ReadLine();

    char splitChar = ';';
    string[] dataRaw = dataString.Split(splitChar);

    float vx = int.Parse(dataRaw[2]);
    float vy = int.Parse(dataRaw[3]);

    curr_offset_x += (vx * acc_normalizer_factor);
    curr_offset_y += (vy * acc_normalizer_factor);
    //get mouse possition
    mousex = (curr_offset_x);
    mousey = (curr_offset_y);
    //adapt it to screen
    // 5 in z to be in the front of the camera, but up to you, just 
avoid 0
    Vector3 mouseposition = cam.ScreenToWorldPoint(new Vector3(mousex, 
mousey, 5));
     //make your gameobject fallow your input
    target.transform.position = mouseposition;

}
4

1 回答 1

0

首先,检查您的设备。数据是否由您的设备发送并由 mpu 连接的机器接收?您也可以在代码中立即尝试Debug.Log(dataString)在 UnitydataString = stream.ReadLine();中进行操作(仅当来自 mpu 的数据由您的设备连接到的机器接收时才有意义)。

于 2019-08-17T23:37:27.960 回答