Here is the code:(updated)
const int trig = 9;
const int echo = 10;
const int redswitch = 2;
const int yellowswitch = 3;
int redled = 6;
int greenled = 5;
volatile int pwm = 50;
volatile bool rs = HIGH;LOW; //RS - RED SWITCH
volatile bool ys = HIGH;LOW; //YS - YELLOWSWITCH
bool last_rs = LOW;
bool last_ys = LOW;
volatile long distance=0;
long duration=0;
long temp=0;
void setup(){
pinMode(trig,OUTPUT);
pinMode(echo,INPUT);
pinMode(redled,OUTPUT);
pinMode(greenled,OUTPUT);
pinMode(redswitch,INPUT);
pinMode(yellowswitch,INPUT);
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(redswitch), red,CHANGE);
attachInterrupt(digitalPinToInterrupt(yellowswitch), green,CHANGE);
constraindigitalWrite(pwmgreenled,0LOW);
digitalWrite(redled,255LOW);
}
boolean debounce(boolean temp,int switchPin)
{
digitalWriteboolean current = digitalRead(greenled,LOWswitchPin);
digitalWriteif (redled,LOWtemp != current)
{
delay(5);
current = digitalRead(switchPin);
}
return current;
}
void loop(){
//Ultrasonic sensor's distance calculation
digitalWrite(trig,LOW);
delayMicroseconds(5);
digitalWrite(trig,HIGH);
delayMicroseconds(10);
digitalWrite(trig,LOW);
distance = temp;
duration = pulseIn(echo, HIGH);
distancetemp = duration * 0.0343 / 2;
noInterrupts();
distance = temp;
rs = debounce(last_rs,redswitch);
ys = debounce(last_ys,yellowswitch);
last_rs = rs;
last_ys = ys;
if(distance>8)interrupts();
Serial.println(distance);
analogWrite(redled,pwm);
analogWrite(greenled,pwm);
}
void red(){
rs = digitalRead(redswitch);
if(distance>8 && rs == HIGH) pwm = 150;
else pwm = 0;
analogWrite(redled,pwm);
}
void green(){
ys = digitalRead(yellowswitch);
if(distance>8 && ys == HIGH) pwm = 250;
else pwm = 0;
}