#define TRIGGER_PIN 13
#define ECHO_PIN 12
#define PWM_PIN 5
#define POTI_PIN 4
unsigned int max_distance;
int poti;
int out;
void trigger_pulse() {
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
}
void setup() {
Serial.begin(115200); // Starts the serial communication
pinMode(TRIGGER_PIN, OUTPUT); // Trigger pin as output
pinMode(ECHO_PIN, INPUT); // Echo pin as input
pinMode(PWM_PIN, OUTPUT); // PWM pin as output
pinMode(POTI_PIN, INPUT); // Potentiometer pin as input
//analogWrite(PWM_PIN, 0); // Initial PWM duty cycle
}
void loop() {
max_distance = map(analogRead(POTI_PIN), 0, 4095, 0, 400); // Read max distance from potentiometer
trigger_pulse();
while(!digitalRead(ECHO_PIN)); // Wait for echo to go high
unsigned long start = micros(); // Record start time
while(digitalRead(ECHO_PIN)); // Wait for echo to go low
unsigned long duration = micros() - start; // Measure duration of echo pulse
unsigned int distance = duration / 58.2; // Calculate distance in cm
distance = constrain(distance, 0, max_distance); // Constrain distance to max distance
analogWrite(PWM_PIN, map(distance, 0, max_distance, 255, 0)); // Set PWM duty cycle based on distance
out = map(distance, 0, max_distance, 255, 0);
poti = analogRead(POTI_PIN);
Serial.print("distance: ");
Serial.print(distance);
Serial.print(" out: ");
Serial.print(out);
Serial.print(" poti: ");
Serial.print(poti);
Serial.print(" max_distance: ");
Serial.println(max_distance);
delay(500);
}