【问题标题】:How can I use mpu6050 and arduino uno to control cube so the cube will move with mouse position?如何使用 mpu6050 和 arduino uno 控制立方体,使立方体随鼠标位置移动?
【发布时间】:2019-08-17 19:38:28
【问题描述】:

当我第一次用我的 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;

}

【问题讨论】:

    标签: unity3d arduino mpu6050


    【解决方案1】:

    首先,检查您的设备。数据是否由您的设备发送并由 mpu 连接的机器接收? 您也可以在代码中的 dataString = stream.ReadLine(); 之后尝试在 Unity 中使用 Debug.Log(dataString)(仅当来自 mpu 的数据通过您的设备连接到的机器接收时才有意义)。

    【讨论】:

    • 我试过你的方法,我可以从 mpu 获得读数,但读数始终为 0; 0; 2; 0. 有人可以帮忙吗?
    • @user11940781,Unity 似乎可以正确地从串口读取数据。问题出在固件或 mpu 上。无论如何,你可以做一些额外的测试来证明它。使用 String output = "Test"(例如)并在 Unity 中使用 Debug.Log() 进行检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多