You can use infrared or laser reader instead of ultrasonic distance sensor.
You can run the project from the Tinkercad virtual application sample and experience the system.
#include <LiquidCrystal.h> //initialize the pins const int trigPin = 6; const int echoPin = 7; const int buzzer = 8; const int role1 = 9; int count = 0; int count2 = 0; int urunaktif = 0; //initialize the variables long duration; int distance; //interfacing the LCD display const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); void setup() { //setup code to run once: pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(buzzer, OUTPUT); pinMode(role1, OUTPUT); lcd.begin(16,2); lcd.clear(); Serial.begin(9600); lcd.print("HELLO"); lcd.setCursor(0,1); lcd.print("NICEDAY"); delay(2000); lcd.clear(); } void loop() { digitalWrite(trigPin,HIGH); //delayMicroseconds(1000); digitalWrite(trigPin,LOW); duration = pulseIn(echoPin, HIGH); distance = (duration/2)/29.1; //delay(500); //suppose I have fixed the ultrasonic senser at the distance of 100 cm if (distance <80) { if (urunaktif ==0) /////// { tone(buzzer,1600); count++; count2++; urunaktif++; // delay(1000); } ///////////// } else { noTone(buzzer); urunaktif =0; } if (count2 ==12) { digitalWrite(role1, HIGH); count2 =0; lcd.clear(); } //lcd.clear(); lcd.setCursor(0,0); lcd.print("DISTANCE: "); lcd.print(distance); lcd.print("cm"); lcd.setCursor(0,1); lcd.print("PIECE "); lcd.print(count); lcd.print(" / "); lcd.print(count2); //delay(500); }
Tinkercad :