Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save lkarlslund/a88a2a35590b611f058544d53e9c7014 to your computer and use it in GitHub Desktop.

Select an option

Save lkarlslund/a88a2a35590b611f058544d53e9c7014 to your computer and use it in GitHub Desktop.
Nudge sensor for Virtual Pinball machine using Arudino Micro and MPU6050 accelerometer
#include <Wire.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Joystick.h>
// #include <Keyboard.h>
// Define the MPU6050 object
Adafruit_MPU6050 mpu;
// Define the joystick object
Joystick_ joystick;
// Keyboard_ keyboard;
// Define the potentiometer pin
const int potPin = A0;
float xbaseline, ybaseline, zbaseline;
sensors_event_t accel, gyro, temp;
void setup() {
// Initialize the serial communication
Serial.begin(9600);
// Initialize the I2C communication
Wire.begin();
// Initialize the MPU6050
if (!mpu.begin()) {
if (Serial) {
Serial.println("Failed to find MPU6050 chip");
}
while (1) {}
}
if (Serial) {
Serial.println("Connected to MPU6050 chip");
}
// Calibrate the MPU6050
mpu.setAccelerometerRange(MPU6050_RANGE_2_G);
mpu.setFilterBandwidth(MPU6050_BAND_94_HZ);
// Set the joystick range
joystick.begin(false);
joystick.setXAxisRange(-512, 512);
joystick.setYAxisRange(-512, 512);
joystick.setZAxisRange(0, 1023);
// keyboard.begin();
for (int i = 0; i < 10; i++) {
mpu.getEvent(&accel, &gyro, &temp);
xbaseline += accel.acceleration.x;
ybaseline += accel.acceleration.y;
zbaseline += accel.acceleration.z;
}
xbaseline /= 10;
ybaseline /= 10;
zbaseline /= 10;
}
void loop() {
// Read the accelerometer data
mpu.getEvent(&accel, &gyro, &temp);
if (Serial) {
Serial.print("Acceleration X: ");
Serial.printf("%.2f", accel.acceleration.x - xbaseline);
Serial.print(", Y: ");
Serial.printf("%.2f", accel.acceleration.y - ybaseline);
Serial.print(", Z: ");
Serial.printf("%.2f", accel.acceleration.z - zbaseline);
Serial.println(" m/s^2");
}
// Convert the acceleration values to joystick values
int x = map(accel.acceleration.x - xbaseline, -2, 2, -512, 512);
int y = map(accel.acceleration.y - ybaseline, -2, 2, -512, 512);
// Read the potentiometer value and convert it to a joystick value
int z = analogRead(potPin);
z = map(z, 0, 1023, 0, 1023);
// Send the joystick values to the computer
joystick.setXAxis(x);
joystick.setYAxis(y);
joystick.setZAxis(z);
joystick.sendState();
joystick.sendState();
// Wait for a short amount of time to prevent overwhelming the HID driver
delay(20);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment