I am using an ultrasonic distance sensor to control PWM signal to a motor driver. The closer the distance the duty cycle of PWM should increase. The PWM will only output 6 or 14 depending on PIN number. What am I doing wrong?
Using Arduino Nano & HC-S04 Ultrasonic Sensor
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
const int motor = 6;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(motor, OUTPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
Serial.print("PWM: ");
Serial.println(motor);
if (distance <= 40) {
analogWrite(motor, 255);
if (distance > 40 || distance <=80) {
analogWrite(motor, 127);
if (distance > 80 || distance <=120) {
analogWrite(motor, 64);
}
}
}
else {
analogWrite(motor, 0);
}
}
it is best to use a series of if/else statements that start with the highest range and progress to the lowest distance.
if ( distance > 120 ) {
// do something when above 120
} else if ( distance > 80 ) {
// do something when 80-120
} else if ( distance > 40 ) {
// do something when 40-80
} else if ( distance > 20 ) {
// do something when 20-40
} else {
// do something when 0-20
}
if you don't like that style, you can also use switch/case statements where the case statements specify a range
switch( distance ) {
case 0...20:
// do something
break;
case 21...40:
// do something else
break;
case 41...80:
...
}
They both look clean. I am not comfortable using switch/case yet but i'll save this code for when I'm learning. I really appreciate you laying out the proper structure.