#define echoPin A0
#define trigPin A1
#define greenLED A4
#define orangeLED A3
#define redLED A2
#define switchPin D1
#define buzzerPin D2
#define SHCP D5
#define STCP D4
#define DS D3
int sound, time_delay;
int switchState;
float distance_meters;
long duration, distance;
byte digits[] = {
0b01111110, // digit 0
0b00001010, // digit 1
0b10110110, // digit 2
0b10011110, // digit 3
0b11001010, // digit 4
0b11011100, // digit 5
0b11111100, // digit 6
0b00001110, // digit 7
0b11111110, // digit 8
0b11011110 // digit 9
};
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(greenLED, OUTPUT);
pinMode(redLED, OUTPUT);
pinMode(orangeLED, OUTPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
pinMode(DS, OUTPUT);
pinMode(SHCP, OUTPUT);
pinMode(STCP, OUTPUT);
}
void loop() {
switchState = digitalRead(switchPin);
if (switchState == LOW) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration / 2 * 0.0343;
Serial.print("Distance in CM: ");
Serial.println(distance);
distance_meters = distance * 0.01;
Serial.print("Distance in metre: ");
Serial.println(distance_meters);
int distanceCategory;
if (distance >= 120) {
distanceCategory = 3;
} else if (distance > 30 && distance < 120) {
distanceCategory = 2;
} else if (distance <= 30) {
distanceCategory = 1;
}
switch (distanceCategory) {
case 3:
digitalWrite(greenLED, HIGH);
digitalWrite(orangeLED, LOW);
digitalWrite(redLED, LOW);
sound = 0;
time_delay = 0;
break;
case 2:
digitalWrite(greenLED, LOW);
digitalWrite(orangeLED, HIGH);
digitalWrite(redLED, LOW);
sound = 440;
time_delay = map(distance, -30, 90, 0, 1000);
Serial.print("time delay = ");
Serial.println(time_delay);
break;
case 1:
digitalWrite(greenLED, LOW);
digitalWrite(orangeLED, LOW);
digitalWrite(redLED, HIGH);
sound = 440;
time_delay = 0;
break;
default:
digitalWrite(greenLED, LOW);
digitalWrite(orangeLED, LOW);
digitalWrite(redLED, HIGH);
sound = 0;
time_delay = 0;
break;
}
tone(buzzerPin, sound, time_delay);
int distance_integer = int(distance_meters * 10);
int digit1 = distance_integer / 10;
int digit2 = distance_integer % 10;
digitalWrite(STCP, LOW);
shiftOut(DS, SHCP, MSBFIRST, digits[digit2]);
shiftOut(DS, SHCP, MSBFIRST, digits[digit1]| 0b00000001);
digitalWrite(STCP, HIGH);
delay(500);
} else {
// turn off all LEDs and displays
digitalWrite(greenLED, LOW);
digitalWrite(orangeLED, LOW);
digitalWrite(redLED, LOW);
digitalWrite(buzzerPin, LOW);
}
}
Loading
st-nucleo-l031k6
st-nucleo-l031k6