This project is one which I made for my Robotics Class
Here is the link to the tinkercad simulation
https://www.tinkercad.com/things/bjrHzMEOw6j
Let's look at the code:
LiquidCrystallcd(2,3,4,5,6,7);
initializes an instance of the LiquidCyrstal Class.
int ledPin = 12;
const int PIRPin = 8;
int pirState = LOW;
int val = 0;
int photoCellPin = A0;
int photoCellReading;
int speakerPin = 10;
Declares variables
void setup()
{
lcd.begin(16,2);
pinMode(ledPin, OUTPUT);
pinMode(PIRPin, INPUT);
pinMode(photoCellPin, INPUT);
pinMode(speakerPin, INPUT);
Serial.begin(9600);
lcd.setCursor(0,0);
lcd.print("P.I.R Motion And");
lcd.setCursor(0,1);
lcd.print("light sensors");
delay(2000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Processing Data.");
playTone(300,300);
delay(150);
playTone(0,0);
delay(3000);
lcd.clear();
lcd.setCursor(3,0);
lcd.print("Waiting For");
lcd.setCursor(3,1);
lcd.print("Motion...");
}
sets up the sensors and displays a short message on the screen. also plays a sound
void loop()
{
val = digitalRead(PIRPin);
photoCellReading = analogRead(photoCellPin);
if(val == HIGH)
{
digitalWrite(ledPin, HIGH);
if(pirState == LOW)
{
Serial.println("Motion Detected");
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Motion Detected");
lcd.setCursor(0,1);
lcd.print(photoCellReading);
playTone(300,300);
delay(150);
playTone(0,0);
pirState = HIGH;
}
} else
{
digitalWrite(ledPin, LOW);
delay(300);
scrollScreenSaver();
if(pirState == HIGH)
{
Serial.println("Motion Ended");
pirState = LOW;
}
}
}
checks if there is motion, and if there is then it sounds an alarm. if there is not, it displays a custom message
void playTone(long duration, int freq)
{
duration *= 1000;
int period = (1.0/freq)*100000;
long elapsed_time = 0;
while(elapsed_time < duration)
{
digitalWrite(13, HIGH);
digitalWrite(speakerPin, HIGH);
delayMicroseconds(period/2);
digitalWrite(13, LOW);
digitalWrite(speakerPin, LOW);
delayMicroseconds(period/2);
elapsed_time += (period);
}
}
Function for playing the Alarm sound
void scrollScreenSaver()
{
lcd.clear();
lcd.setCursor(15,0);
lcd.print("No Motion");
lcd.setCursor(15,1);
lcd.print("Waiting");
for(int i = 0; i < 22; i++)
{
lcd.scrollDisplayLeft();
delay(150);
}
}
Function to scroll a custom screen saver
Comments