Hello everyone, I'm trying to use an ultrasonic sensor to control an LED using the constrain() and map() functions. But it's not working. Some help would be very appreciated. Thank you!
The goal is to limit the inputs between 2 and 22 using the constrain() function.
Code:
// Arduino pin numbers for the sensor output and input pins
const int pingTrig = A0;
int pingEcho = A1;
void setup() {
// initialize serial communication
Serial.begin(9600);
// initialize sensor pins
pinMode(pingTrig, OUTPUT); // change A0 pin mode to digital output
pinMode(pingEcho, INPUT); // change A1 pin mode to digital input
}
void loop()
{
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;
// The HC-SR04 is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse
digitalWrite(pingTrig, LOW);
delayMicroseconds( 5);
digitalWrite(pingTrig, HIGH);
delayMicroseconds(10);
digitalWrite(pingTrig, LOW);
pingEcho = constrain(pingEcho, 2, 22);
pingEcho = map(pingEcho, 2, 22, 0, 255);
// The Echo pin is used to read the signal from HC-SR04; a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
duration = pulseIn(pingEcho, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds)
{
// According to the Ping sensor datasheet, there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
Serial output:
0 in, 0 cm
0 in, 0 cm
0 in, 0 cm
0 in, 0 cm
0 in, 0 cm
0 in, 0 cm