I have 2 questions
1)what .setInterval() does exactly do ?I havent found a good explanation
2)I want to measure the distance using an ultrasonic sensor if the distance is less than 30 a vibration motor will vibrate
but i dont want that to happen in function void loop because it’s too large
i want it to happen every 1 second for example
and the rest of the code still run
I hope you understood me
how this is going to be done ?
#define trigPin 45
#define echoPin 44
#define trigPin2 41
#define echoPin2 40
float duration, distance;
float duration2, distance2;
int safetyDistance,safetyDistance2;
const int vib = 24;
const int buzzer = 22;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
////////////////////////
pinMode(buzzer, OUTPUT);
pinMode(vib, OUTPUT);}
id loop() {// put your main code here, to run repeatedly:
//the parts that keep repeating until the arduino is off
/////////////////////////////////////////////////////////
// Write a pulse to the HC-SR04 Trigger Pin
digitalWrite(trigPin, LOW);// Clears the trigPin
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);// Sets the trigPin on HIGH state for 10 micro seconds to generate the ultrasound wave
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the response from the HC-SR04 Echo Pin
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Determine distance from duration// Calculating the distance
// Use 343 metres per second as speed of sound
distance = (duration / 2) * 0.0343;
// Prints the distance on the Serial Monitor
Serial.print("Distance = ");
Serial.print(distance);
Serial.println(" cm a");
safetyDistance = distance;
if (safetyDistance <= 10){
digitalWrite(vib, HIGH);
delay(500);
digitalWrite(vib, LOW);}
else{
digitalWrite(vib, LOW);}
Serial.print("\n");
delay(10);
////////////////////////////////////////////////////////////////
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
// Measure the response from the HC-SR04 Echo Pin
duration2 = pulseIn(echoPin2, HIGH);
// Determine distance from duration
// Use 343 metres per second as speed of sound
distance2 = (duration2 / 2) * 0.0343;
// Send results to Serial Monitor
Serial.print("Distance = ");
Serial.print(distance2);
Serial.println(" cm b");
safetyDistance2 = distance2;
if (safetyDistance2 <= 10){
digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW);}
else{digitalWrite(buzzer, LOW);}
Serial.print("\n");
}