#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#define TRIG_PIN 10
#define ECHO_PIN 9
int ledRed = 13; int SWRed = 8;
int ledGreen = 12; int SWGreen = 7;
int close = 20; int open = 160;
int counter = 0; float cash = 0.10;
int keystateRed; int keystateGreen;
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo myservo;
void setup()
{
lcd.begin(16,2);
myservo.attach(11);
pinMode(ledRed, OUTPUT);
pinMode(ledGreen, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(SWRed, INPUT);
pinMode(SWGreen, INPUT);
}
float ReadDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
float distance = ReadDistance();
void loop()
{
keystateRed = digitalRead(SWRed);
keystateGreen = digitalRead(SWGreen);
if (keystateGreen == HIGH && keystateRed == LOW)
{
delay(200);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Insert Can");
myservo.write(open);
digitalWrite(ledRed, LOW);
digitalWrite(ledGreen, HIGH);
float distance = ReadDistance();
if (distance <= 100)
{
delay(1200);
myservo.write(close);
digitalWrite(ledGreen, LOW);
digitalWrite(ledRed, HIGH);
delay(1200);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Processing");
lcd.println();
delay(1200);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("You earn");
lcd.setCursor(0, 1);
lcd.print("RM ");
lcd.print(cash);
cash = cash + 0.10;
delay(1200);
counter++;
}
}
else if (keystateRed == HIGH && keystateGreen == LOW)
{
digitalWrite(ledRed, HIGH);
digitalWrite(ledGreen, LOW);
myservo.write(close);
if (counter == 1)
{
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Your total");
lcd.setCursor(0, 1);
lcd.print("is RM 0.10");
delay(3000);
cash = 0.10;
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 - 0.10);
delay(3000);
cash = 0.10;
counter = 0;
}
else
{
lcd.clear();
lcd.print("Waiting for ");
lcd.setCursor(0, 1);
lcd.print("recycling");
delay(3000);
cash = 0.10;
}
}
}