#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
int16_t ax, ay, az;
float accel_mag;
const int vib_pin = 9;
const float threshold = 105.0; // Adjust this value to set the stroke detection sensitivity
unsigned long stroke_start_time = 0;
const unsigned long stroke_timeout = 1000; // Time limit to complete a stroke in milliseconds
bool vibration_on = false; // Variable to keep track of whether vibration motor is on or off
void setup() {
Wire.begin();
mpu.initialize();
pinMode(vib_pin, OUTPUT);
Serial.begin(115200);
}
void loop() {
mpu.getAcceleration(&ax, &ay, &az); // Read acceleration data from the MPU6050
accel_mag = sqrt(ax*ax + ay*ay + az*az); // Calculate the magnitude of the acceleration vector
if (isnan(accel_mag)) {
// Handle NaN value here, e.g. set accel_mag to a default value
accel_mag = 0.0;
}
Serial.print("acceleration magnitude = ");
Serial.println(accel_mag);
if (accel_mag > threshold) { // If a stroke is detected
if (stroke_start_time == 0) { // If this is the first stroke of a cycle
stroke_start_time = millis(); // Start the stroke timer
} else if (millis() - stroke_start_time < stroke_timeout) { // If within time limit for completing a stroke
if (vibration_on) { // If vibration motor is on
digitalWrite(vib_pin, LOW); // Turn off the vibration motor
vibration_on = false; // Set vibration_on to false
}
}
else { // Stroke not completed within time limit
if (!vibration_on) { // If vibration motor is not on
digitalWrite(vib_pin, HIGH); // Activate the vibration motor
vibration_on = true; // Set vibration_on to true
}
stroke_start_time = 0; // Reset the stroke timer
}
} else { // No stroke detected
if (millis() - stroke_start_time >= stroke_timeout && !vibration_on) { // If within time limit for completing a stroke and vibration motor is not on
digitalWrite(vib_pin, HIGH); // Activate the vibration motor
vibration_on = true; // Set vibration_on to true
} else if (vibration_on) { // If vibration motor is on
digitalWrite(vib_pin, LOW); // Turn off the vibration motor
vibration_on = false; // Set vibration_on to false
}
stroke_start_time = 0; // Reset the stroke timer
}
delay(10); // Add a small delay to reduce the processing load on the microcontroller
}