Saturday, February 25, 2023

Teensy 4.1 with GY-521 MPU-6050 Accel / Gyro / Temp to USB MIDI

 Overview

The GY-521 board uses an MPU-6050 IC with an accelerometer, gyroscope and thermometer. An I2C bus is used to communicate with the board using the Teensy 4.1. 


Hardware






The following connections should be made between the Teensy 4.1 and the GY-521:
  • Teensy 4.1 3V to GY-521 VCC - orange in the above photo
  • Teensy 4.1 ground to GY-521 GND - black in the above photo
  • Teensy 4.1 pin 19 / A5 / SCL / PWM to GY-521 SCL - yellow in the above photo
  • Teensy 4.1 pin 18 / A4 / SDA / PWM to GY-521 SDA - yellow in the above photo

Software

The Arduino code uses the Wire library to communicate with the GY-521 via the I2C bus. The data from seven registers (accel x, y, z; temperature; gyro x, y, z). If these values change, they are sent as a simple USB MIDI control change message 

#include "Wire.h" // This library allows you to communicate with I2C devices.
const int MPU_ADDR = 0x68; // I2C address of the MPU-6050

int16_t value[7];
const int chan = 1;
const int cc_offset = 0;

void setup() {
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(MPU_ADDR); // Begins a transmission to the I2C slave (GY-521 board)
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
}

void loop() {
Wire.beginTransmission(MPU_ADDR);
Wire.write(0x3B); // starting with register 0x3B
Wire.endTransmission(false); // active connection
Wire.requestFrom(MPU_ADDR, 7 * 2, true); // request a total of 7*2=14 registers

for (int i = 0; i < 7; i++) {
int16_t data = Wire.read() << 8 | Wire.read();
data = constrain(map(data, -17000, 17000, 0, 127), 0, 127);

if (data != value[i]) {
value[i] = data;
usbMIDI.sendControlChange(i + cc_offset, data, chan);
delay(5);
}
}
}




The data can be seen via a Max patch such as this one. 

0 comments: