Edit: Pasted wrong code, fixed
Edit2: Code Formatting
I need some help with a school project, I chose to code 2 ultrasonics to turn a light on and sound a buzzer. Each if statement/ultrasonic works i you isolate it, however, when all combined the nothing works, not even the serial monitor displays accurate cm. Could you help, below is the code:
//DISPLAY DISTANCE INFO TO SERIAL MONITER
#define TRIGPIN1 3
#define ECHOPIN1 2
#define TRIGPIN2 5
#define ECHOPIN2 4
// name variables to hols usonic range
unsigned long int duration;
unsigned long int duration2;
double range = 0.0;
double range2 = 0.0;
//define output pins
int buzzerPin = 10;
int buzzerPin2 = 11;
int blueLED = 7;
int redLED = 8;
void setup() {
// put your setup code here, to run once:
pinMode(TRIGPIN1, OUTPUT);
pinMode(TRIGPIN2, OUTPUT);
pinMode(ECHOPIN1, INPUT);
pinMode(ECHOPIN2, INPUT);
pinMode(buzzerPin, OUTPUT); //make sure to add another buzzer
pinMode(buzzerPin2, OUTPUT); //make sure to add another buzzer
Serial.begin(9600); //serial data here
Serial.begin(9600);
pinMode(blueLED, OUTPUT); //set up blue output
pinMode(redLED, OUTPUT); //set up red output
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(TRIGPIN1, LOW);
delayMicroseconds(2);
//send signal then off
digitalWrite(TRIGPIN1, HIGH);
delayMicroseconds(.5);
digitalWrite(TRIGPIN1, LOW);
//CALCULATE CM RANGE
duration = pulseIn(ECHOPIN1, HIGH);
range = ((double)(duration)) / 58.2;
//display values
Serial.print("Range: ");
Serial.print(duration);
Serial.print(" cm");
//same thing but with the other one
digitalWrite(TRIGPIN2, LOW);
delayMicroseconds(2);
//send signal then off
digitalWrite(TRIGPIN2, HIGH);
delayMicroseconds(.5);
digitalWrite(TRIGPIN2, LOW);
//CALCULATE CM RANGE
duration2 = pulseIn(ECHOPIN2, HIGH);
range2 = ((double)(duration2)) / 58.2;
//display values
Serial.print("Range2: ");
Serial.print(range2);
Serial.print(" cm");
//start the statement
if(range<5){
digitalWrite(blueLED, HIGH);
analogWrite(buzzerPin, 5000);
delay(1000);
analogWrite(buzzerPin, 0);
digitalWrite(blueLED, LOW);
}
//no else was needed
if (((double)(duration2)) / 58.2 <5){
digitalWrite(redLED, HIGH);
analogWrite(buzzerPin2, 5000);
delay(1000);
analogWrite(buzzerPin2, 0);
digitalWrite(redLED, LOW);
}
}