#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <Servo.h>
//Sensors
#define TRIG_PIN 9
#define ECHO_PIN 8
#define MetalSensor 4
/*Switch
#define button1Pin A0
#define button2Pin A2*/
//LED
#define LedRed 13
#define LedGreen 12
//LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
//Servos
Servo S1; /*Can Rejection Servo*/
Servo S2; /*Can Acceptents Servo*/
//STATES
int counter = 0;
float cash = 0.00;
float TotalAmount = 0.00;
int CansCounter = 0;
int TotalCans = 0;
int CurrentCans = 0;
float CurrentAmount = 0.00;
int MetalPresence;
int state = 0;
void setup()
{
Serial.begin(9600);
lcd.begin(16,2);
lcd.backlight();
S1.attach(11);
S2.attach(10);
pinMode(LedRed, OUTPUT);
pinMode(LedGreen, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(button1Pin, INPUT);
pinMode(button2Pin, INPUT);
pinMode(MetalSensor, INPUT);
S1.write(90);
S2.write(90);
}
void loop()
{
if (button1State == HIGH && button2State == LOW)
{
state = 1;
delay(500);
}
if (button2State == HIGH && button1State == LOW)
{
state = 0;
delay(500);
}
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int distance = pulseIn(ECHO_PIN, HIGH);
distance = distance * 0.034 / 2;
if (state == 1)
{
digitalWrite(LedRed, LOW);
digitalWrite(LedGreen, HIGH);
delay(250);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Insert Cans");
MetalPresence = digitalRead(MetalSensor);
if (distance < 5 && MetalPresence == LOW)
{
delay(1200);
S2.write(0);
digitalWrite(LedGreen, LOW);
digitalWrite(LedRed, HIGH);
delay(1200);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Processing");
delay(1200);
S2.write(90);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("You earn");
lcd.setCursor(0, 1);
lcd.print("RM 0.10");
cash = cash + 0.10;
delay(1200);
counter++;
CansCounter++;
TotalAmount = TotalAmount + 0.10;
TotalCans = TotalCans + 1;
CurrentAmount = cash;
CurrentCans = CansCounter;
Serial.print(TotalAmount);
Serial.print(",");
Serial.print(TotalCans);
Serial.print(",");
Serial.print(CurrentAmount);
Serial.print(",");
Serial.println(CurrentCans);
delay(200);
}
else if (distance < 5 && MetalPresence == HIGH)
{
delay(500);
S1.write(180);
digitalWrite(LedGreen, LOW);
digitalWrite(LedRed, HIGH);
delay(500);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Rejected");
delay(1000);
S1.write(90);
}
}
else if (state == 0)
{
digitalWrite(LedRed, HIGH);
digitalWrite(LedGreen, LOW);
S1.write(90);
if (counter == 1)
{
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Your total");
lcd.setCursor(0, 1);
lcd.print("is RM 0.10");
delay(2000);
CansCounter = 0;
cash = 0.00;
counter = 0;
}
else if (counter >= 2)
{
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Your total");
lcd.setCursor(0, 1);
lcd.print("is RM ");
lcd.print(cash, 2);
delay(2000);
CansCounter = 0;
cash = 0.00;
counter = 0;
}
else
{
lcd.clear();
lcd.print("Waiting for ");
lcd.setCursor(0, 1);
lcd.print("recycling");
delay(500);
cash = 0.00;
}
}
}