What will the following Arduino code do? Please explain in a few words.
In this setup, a motor is connected to an H-bridge, which is
controlled by pin11 and pin 10. A distance sensor is connected to
pin 2.
Here is the code:
int motorPin1 = 11; // Variables defined before setup
and loop functions can be used anywhere in any
function.
int motorPin2 = 10;
int distance_sensor_pin = 2;
long int pulse_duration, distance_in_inches;
void setup() { // The setup function
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
Serial.begin(9600);
} // end of setup function
void loop() { // The loop function
// read the distance
pinMode( distance_sensor_pin, OUTPUT) ;
digitalWrite( distance_sensor_pin , LOW);
delayMicroseconds(2);
digitalWrite( distance_sensor_pin , HIGH);
delayMicroseconds(5);
digitalWrite( distance_sensor_pin , LOW);
pinMode( distance_sensor_pin , INPUT);
pulse_duration = pulseIn( distance_sensor_pin , HIGH);
distance_in_inches = pulse_duration / 74 / 2;
Serial.println(distance_in_inches);
delay(200);
// do stuff
if ( distance_in_inches > 10) {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
}
else {
if ( distance_in_inches < 2) {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
}
else {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
}
}
} // end of loop function
Hello,
Please find the answer
attached below. If the answer has helped you please give a
thumbs up
rating. Thank you and have a nice day!
The H bridge motor setup is used to change the direction of the motor by toggling the states of the two (or four) switches connected to the bridge. In this case, the control is achieved by toggling the motorPin1 and motorPin2 outputs. The toggling is in turn controlled by the measurement of the distance as reported by the distance sensor. If the distance sensor reads a distance of less than 2 inches, the motor is rotated in a particular direction and if the distance is greater than 10 inches, then the motor is rotated in the reverse direction. If the distance is between 2 and 10 inches, the H bridge is shut down (by openong both the switches), and the motor does not rotate.
Get Answers For Free
Most questions answered within 1 hours.