// MPU6050 example
// https://wokwi.com/arduino/projects/305937248748044864
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#define NOTE_A4 440
#define NOTE_B3 247
#define NOTE_F1 44
const float GAMMA = 0.7;
const float RL10 = 50;
float distance;
const int TrigPin = 7;
const int EchoPin = 6;
#define BUTTON_PIN 4
#define SPEAKER_PIN 11
Adafruit_MPU6050 mpu;
int speak;
void setup(void) {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(SPEAKER_PIN, OUTPUT);
pinMode(A0, INPUT);
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(TrigPin, OUTPUT);
pinMode(EchoPin, INPUT);
Serial.println("Ultrasonic sensor:");
while (!mpu.begin()) {
Serial.println("MPU6050 not connected!");
delay(1000);
}
Serial.println("MPU6050 ready!");
}
sensors_event_t event;
void loop() {
mpu.getAccelerometerSensor()->getEvent(&event);
int analogValue = analogRead(A0);
float voltage = analogValue / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
distance = pulseIn(EchoPin, HIGH) / 58.0; //
Serial.print(distance);
Serial.print("cm");
Serial.println();
delay(1000);
Serial.println();
tone(SPEAKER_PIN,NOTE_A4, digitalRead(BUTTON_PIN));
if (lux < 50) {
digitalWrite(13,HIGH);
}else {
digitalWrite(13,LOW);
}
if(distance<150)
{tone(12,NOTE_A4, 50);}
else if(distance>150&&distance<300)
{tone(12,NOTE_B3, 50);}
else{tone(12,NOTE_F1,HIGH);}
if(event.acceleration.z > 15)
{for(int x=0;x<10;x++){
tone(12,NOTE_B3,50);
delay(1000);}}
}