ciao a tutti,
ho acquistato un sensore ad ultrasuoni HY-SRF05 per un piccolo progetto. Da quel che ho capito, posso sapere la distanza calcolando il tempo tra l'invio e la ricezione del suono di echo secondo la formula s=vt (spazio=velocitàtempo). Ho provato diversi codici reperiti in rete per provarne il funzionamento, ma la distanza letta è sempre 0. Non riesco a capire se il problema è del sensore o del codice che ho utilizzato per testarlo.
ecco il codice:
#define ECHOPIN 2 // Pin to receive echo pulse
#define TRIGPIN 3 // Pin to send trigger pulse
void setup(){
Serial.begin(9600);
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
}
void loop(){
digitalWrite(TRIGPIN, LOW); // Set the trigger pin to low for 2uS
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH); // Send a 10uS high to trigger ranging
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW); // Send pin low again
int distance = pulseIn(ECHOPIN, HIGH); // Read in times pulse
distance= distance/58; // Calculate distance from time of pulse
Serial.println(distance);
delay(50); // Wait 50mS before next ranging
}
Sul forum internazionale ho trovato questo codice fatto per la MEGA (occhio ai pin!):
const int trigPin = 53; //Change to pin you use
const int echoPin = 50; //Here too
void setup() {
// initialize serial communication:
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
digitalWrite(trigPin, LOW);
}
void loop()
{
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, 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(500);
}
long microsecondsToInches(long microseconds)
{
// According to Parallax's datasheet for the PING))), 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.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
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;
}