// Exercise #2 | Pouya Abbasi | 991152135
#define TRIGGER_PIN 7
#define ECHO_PIN 6
#define MAX_DISTANCE 300
#define RED_LED_PIN 9
#define GREEN_LED_PIN 10
#define BLUE_LED_PIN 11
#define SPEAKER_PIN 8
void setup() {
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(RED_LED_PIN, OUTPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
pinMode(BLUE_LED_PIN, OUTPUT);
pinMode(SPEAKER_PIN, OUTPUT);
}
void loop() {
unsigned int duration, distance;
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration / 58;
if (distance > 300) {
setColor(0, 0, 0);
noTone(SPEAKER_PIN);
} else if (distance >= 200 && distance <= 300) {
flashRGBLed(0, 255, 0, 500);
beep(500, 500);
} else if (distance >= 100 && distance < 200) {
flashRGBLed(255, 255, 0, 300);
beep(300, 300);
} else {
flashRGBLed(255, 0, 0, 100);
beep(150, 150);
}
}
void setColor(int red, int green, int blue) {
analogWrite(RED_LED_PIN, 255 - red);
analogWrite(GREEN_LED_PIN, 255 - green);
analogWrite(BLUE_LED_PIN, 255 - blue);
}
void flashRGBLed(int red, int green, int blue, int duration) {
unsigned long currentTime = millis();
static unsigned long previousTime = 0;
static boolean ledState = LOW;
if (currentTime - previousTime >= duration) {
previousTime = currentTime;
ledState = !ledState;
if (ledState) {
setColor(red, green, blue);
} else {
setColor(0, 0, 0);
}
}
}
void beep(int duration, int beepDuration) {
static unsigned long previousTime = 0;
unsigned long currentTime = millis();
if (currentTime - previousTime >= duration) {
previousTime = currentTime;
tone(SPEAKER_PIN, 600);
delay(beepDuration / 2);
noTone(SPEAKER_PIN);
delay(beepDuration / 2);
}
}