// Trafic control with Distance sensor using Arduino Uno
#include <Tiny4kOLED.h>
// Define the pin for the LEDs
const int greenLedPin = 8;
const int orangeLedPin = 10;
const int redLedPin = 12;
// Define the pins for the ultrasonic sensor
const int echoPin = 4;
const int trig_Pin = 6;
float cm;
float inches;
void setup() {
Serial.begin(9600);
// Set LED pins as outputs
pinMode(greenLedPin, OUTPUT);
pinMode(orangeLedPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
// Set ultrasonic sensor pins
pinMode(trig_Pin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize the OLED display
oled.begin();
// Clear the display
oled.clear();
// Turn on the display
oled.on();
// Set the font
oled.setFont(FONT6X8);
}
long readUltrasonicDistance(int trig, int echo) {
// Clear the trigger
digitalWrite(trig, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echo, HIGH);
}
void loop() {
// Measure the distance in cm
cm = 0.0344 / 2 * readUltrasonicDistance(trig_Pin, echoPin);
// Convert cm to inches
inches = cm / 2.54;
// Clear the OLED display
oled.clear();
// Display the distance
oled.setCursor(0, 0);
oled.print("---Distance---");
oled.setCursor(0, 2);
oled.print(F("Inches: "));
oled.print(inches, 1);
oled.setCursor(0, 4);
oled.print("CM: ");
oled.print(cm, 1);
// Check if the distance is below 100 cm
if (cm < 100) {
oled.setCursor(0, 6);
oled.print("!!! Car near by !!!");
// Light orange and green signal to GO!
digitalWrite(orangeLedPin, HIGH);
delay(2000);
digitalWrite(orangeLedPin, LOW);
delay(1000);
digitalWrite(greenLedPin, HIGH);
Serial.print("Measured distance in cms: ");
Serial.println(cm);
delay(10000);
digitalWrite(greenLedPin, LOW);
} else {
oled.setCursor(0, 6);
oled.print("--Car far away--");
// Light orange and red signal to STOP!
digitalWrite(orangeLedPin, HIGH);
delay(2000);
digitalWrite(orangeLedPin, LOW);
delay(1000);
digitalWrite(redLedPin, HIGH);
Serial.print("Measured distance in cms: ");
Serial.println(cm);
// Pause for 10 seconds
delay(10000);
digitalWrite(redLedPin, LOW);
}
// Clear the OLED display
oled.clear();
}