#include <Wire.h>
#include <LiquidCrystal.h>
#include <Servo.h>
Servo servo; // Create servo object to control a servo
#define LED_PIN 13 // Pin for the LED
int val;
int pos = 0; // Variable to store the servo position
int sensor = 1; // The pin that the sensor is attached to
const int rs = 12, en = 11, d4 = 10, d5 = 9, d6 = 8, d7 = 7;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int ab;
const int DOUT_PIN = 2; // Pin connected to the DOUT pin of the load cell
const int CLK_PIN = 3; // Pin connected to the CLK pin of the load cell
const float MAX_WEIGHT = 10; // Maximum weight in kilograms
bool carDetected = false;
unsigned long carDetectedTime = 0; // Variable to store the time when the car was detected
void setup() {
lcd.begin(20, 4);
pinMode(sensor, INPUT);
pinMode(LED_PIN, OUTPUT);
servo.attach(4);
// Initialize the load cell module
pinMode(DOUT_PIN, INPUT);
pinMode(CLK_PIN, OUTPUT);
// Wait for the load cell module to stabilize
delay(1000);
}
void loop() {
val = digitalRead(sensor); // Read sensor value
// Read the weight from the load cell
float weight = getWeight();
// Display the weight on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Weight: ");
lcd.setCursor(0, 1);
lcd.print(weight, 1);
lcd.print(" kg");
// Check if the weight exceeds the maximum limit
if (weight > MAX_WEIGHT) {
digitalWrite(LED_PIN, HIGH); // Turn on the LED
delay(1000); // Wait for 1 second
digitalWrite(LED_PIN, LOW); // Turn off the LED
lcd.setCursor(0, 2);
lcd.print("CHANGE ROAD OR TURN BACK");
carDetected = false;
} else if (val == LOW && !carDetected) {
openBarrier();
carDetected = true;
carDetectedTime = millis(); // Record the time when the car was detected
} else if (carDetected && millis() - carDetectedTime >= 10000) {
closeBarrier();
carDetected = false;
}
delay(1000);
}
float getWeight() {
unsigned long value = 0;
// Read 24 bits of data from the load cell
for (byte i = 0; i < 24; i++) {
digitalWrite(CLK_PIN, HIGH);
delayMicroseconds(0.5);
value <<= 1;
if (digitalRead(DOUT_PIN)) {
value++;
}
digitalWrite(CLK_PIN, LOW);
delayMicroseconds(0.5);
}
// Set the MSB (bit 24) to 0 for a positive value
value &= 0x7FFFFF;
// Calculate the weight in kilograms
float weight = value / 100;
return weight;
}
void openBarrier() {
for (pos = 0; pos <= 90; pos += 1) {
servo.write(pos);
delay(10);
}
}
void closeBarrier() {
for (pos = 90; pos >= 0; pos -= 1) {
servo.write(pos);
delay(10);
}
}