I am trying to make a buzzer play when the gyroscope attached to the Arduino passes a certain rotation threshold on the x axis. The problem is: it also activates when I simulate to go back under the threshold, which is quite strange.
#include <Adafruit_MPU6050.h>
#include <CuteBuzzerSounds.h>
int buzzer_pin = 4;
Adafruit_MPU6050 IMU;
void setup() {
pinMode(buzzer_pin, OUTPUT);
Serial.begin(115200); // Any baud rate should work
digitalWrite(buzzer_pin, LOW);
if (!IMU.begin()) {
Serial.println("Sensor init failed");
while (1)
yield();
}
Serial.println("Found a sensor");
IMU.setAccelerometerRange(MPU6050_RANGE_2_G);
switch (IMU.getAccelerometerRange()) {
case MPU6050_RANGE_2_G:
Serial.print("+-2G");
break;
}
IMU.setGyroRange(MPU6050_RANGE_250_DEG);
switch (IMU.getGyroRange()) {
case MPU6050_RANGE_250_DEG:
Serial.print("+- 250 deg/s");
break;
}
}
void loop() {
sensors_event_t acc, giro, t;
IMU.getEvent(&acc, &giro, &t);
Serial.print("\n X: ");
Serial.print(giro.gyro.x, 1);
Serial.print(" Y: ");
Serial.print(giro.gyro.y, 1);
Serial.print(" Z: ");
Serial.print(giro.gyro.z, 1);
if (giro.gyro.x > 0.5) //threshold
{
digitalWrite(buzzer_pin, HIGH);
}
else
{
digitalWrite(buzzer_pin, LOW);
}
delay(1000);
}
A link to try it out: https://wokwi.com/projects/351917249533051471
The threshold is between 25 and 30 degrees: to simulate it, click on the IMU and play with the rotation X slider.
I understood the problem:
in Wokwi, buzzers do "activate" (show notes but don't make any real sound) when using DigitalWrite()
but they are not made to activate with that. One should use tone()
as by documentation.