#include<Servo.h>
const int buttonPin1 = 10;//Manual closing button
const int buttonPin2 = 11;//Manual opening button
const int buttonPin3 = 12;//Manual mode button
const int buttonPin4 = 13;//Automated mode button
const int irSensorPin = 2;
static const int servoPin=6;
Servo servo1;
byte flag=90;//for andle of movement
byte mode=1;//manual mode
// Variables to hold state
volatile unsigned long lastTime = 0;
volatile int count = 0;
unsigned long rpm = 0;
// Interrupt Service Routine to count pulses
void countPulse()
{
count++;
}
void setup()
{
pinMode(buttonPin1,INPUT_PULLUP);//from 0 to 90 degree
pinMode(buttonPin2,INPUT_PULLUP);//from 90 to 0 degree
pinMode(buttonPin3,INPUT_PULLUP);
pinMode(buttonPin4,INPUT_PULLUP);
servo1.write(90);
servo1.attach(servoPin);
// Initialize Serial communication
Serial.begin(9600);
pinMode(irSensorPin, INPUT);
// Attach an interrupt to the IR sensor pin
attachInterrupt(digitalPinToInterrupt(irSensorPin), countPulse, RISING);
}
void loop()
{
// Calculate RPM every 1 second
if (millis() - lastTime >= 1000)
{
// Calculate RPM
rpm = (count * 60)/ 4; // Assuming 4 slots or markings on the rotating object
Serial.print("RPM: ");
Serial.println(rpm);
// Reset count and update lastTime
count = 0;
lastTime = millis();
}
//--------------- mode selection
if(digitalRead(buttonPin3)==LOW)
{
mode=0;//Manual mode
}
else if(digitalRead(buttonPin4)==LOW)//FOR AUTOMATED MODE
{
mode=1;//Automated mode
}
//----------
//automated fn
if(mode==1){
if(rpm!=0)//checking whether the bus start running
{
if(flag != 90)//checking whether already closed or not
{
for(int posDegrees=0;posDegrees<=90;posDegrees++)//closing the stair
{
servo1.write(posDegrees);
delay(15); // this speeds up the simulation
}
}
flag=90;
// delay(3000);
}
else//checking the bus is not running
{
if(flag!=0)
{
for(int posDegrees=90;posDegrees>=0;posDegrees--)
{
servo1.write(posDegrees);
delay(15); // this speeds up the simulation
}
}
flag=0;
// delay(3000);
}
}
else if(mode==0){//manual fn
if(digitalRead(buttonPin1)==LOW)//to close
{
if(flag != 90)
{
for(int posDegrees=0;posDegrees<=90;posDegrees++)
{
servo1.write(posDegrees);
delay(15); // this speeds up the simulation
}
}
flag=90;
}
else if(digitalRead(buttonPin2)==LOW)
{
if(flag!=0)
{
for(int posDegrees=90;posDegrees>=0;posDegrees--)
{
servo1.write(posDegrees);
delay(15); // this speeds up the simulation
}
}
flag=0;
}
else if(rpm!=0){
if(flag != 90)
{
for(int posDegrees=0;posDegrees<=90;posDegrees++)
{
servo1.write(posDegrees);
delay(15); // this speeds up the simulation
}
}
flag=90;
}
}
}