so I'm working on a project for my school making a radar and thermometer with Arduino. and the code is like this.
#include <Servo.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 8
#define DHTTYPE DHT22
DHT_Unified dht(DHTPIN, DHTTYPE);
Servo servo_1;
int trig = 4;
int echo = 5;
int buzzpin = 13;
int buzzstate = LOW;
int ledr = 12;
int ledg = 11;
int ledstatus = 13;
unsigned long previousMillis = 0;
const long intervalFar = 250;
const long intervalClose = 50;
const long intervalIdle = 1250;
int servo_pin = 3;
int pos = 0;
int distance,duration;
void setup() {
Serial.begin(115200);
Serial.println("Radar Start");
pinMode(ledr, OUTPUT);
pinMode(ledg, OUTPUT);
pinMode(buzzpin, OUTPUT);
Serial.begin(115200);
servo_1.attach(servo_pin);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
dht.begin();
}
// moving servo
void loop() {
for (pos = 0; pos <= 180; pos+= 1){ // arah kiri ke kanan
servo_1.write(pos);
delay(60);
dist_calc(pos);
}
for (pos = 180; pos >= 0; pos -= 1){ // arah kanan ke kiri
servo_1.write(pos);
delay(60);
dist_calc(pos);
}
}
float dist_calc(int pos){
//trigger HC-SR04 sensor
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
duration = pulseIn(echo, HIGH);
distance = 100.0*(343.0*(duration/2.0))/1000000.0;
//led and buzzer
if (distance <= 200 && distance > 100){
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= intervalFar){
previousMillis = currentMillis;
if (buzzstate == LOW) {
buzzstate = HIGH;
} else {
buzzstate= LOW;
}
digitalWrite(buzzpin, buzzstate);
digitalWrite(ledr, buzzstate);
digitalWrite(ledg, LOW);
}
} else if (distance <= 100 && distance > 0) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= intervalClose) {
previousMillis = currentMillis;
if (buzzstate = LOW) {
buzzstate = HIGH;
} else {
buzzstate = LOW;
}
digitalWrite(buzzpin, buzzstate);
digitalWrite(ledr, buzzstate);
digitalWrite(ledg, LOW);
}
} else if (distance > 200){
digitalWrite(buzzpin, LOW);
digitalWrite(ledr, LOW);
digitalWrite(ledg, HIGH);
}
//DHT22 sensor
delay(1000);
sensors_event_t event;
dht.temperature().getEvent(&event);
float temperature = event.temperature;
Serial.print(pos);
Serial.print(" , ");
Serial.println(distance);
if (isnan(event.temperature)) {
Serial.println ("Error");
}else {
Serial.print("Suhu: ");
Serial.println(temperature);
}
}
when I tested the DHT22 and HC-SR04 sensors there were no problems. but the problem appears with the LED and buzzer so when the object approaches a distance between 0 - 100 cm there is no reaction whatsoever. even though I set it to flash and make a sound quickly