problemi con sensore ultrasuoni HC SR04 e arduino uno r3
non mostra valore in centimetri nel monitor seriale
ma numeri a caso anche negativi o solo zeri
o fuori portata
problems with HC SR04 ultrasonic sensor and arduino r3
shows no value in centimeters in the serial monitor
but also negative numbers at random or only zeros
or out of range
void loop(){
digitalWrite(T, LOW); //Ultrasonic launch 2us low level
delayMicroseconds(2);
digitalWrite(T, HIGH); // ultrasound transmitting high voltage 10us, there is at least 10us
delayMicroseconds(10);
digitalWrite(T, LOW); // Ultrasonic launch low level
int distance = pulseIn(E, HIGH); //measure time
distance= distance; // time to distance (cm)
Serial.println(distance/58);
delay(50);
}
The traveltime can exceed 32767 us and therefore make int overflow. That could explain the odd readings.
You are using analog pin and pulseIn does that work?
The forth line from the end seems odd:
" distance= distance; // time to distance (cm)"
Wrote a small test program today as I just bought a HC-SR04. It worked. You can try it (Using triger pin 12 and echo pin 11):
const int pinTrig = 12;
const int pinEcho = 11;
const float DIVM = 4970.0; //Divide to get distance in meters
unsigned long ping( int trig, int echo) {
digitalWrite(trig, LOW); //Set LOW
delayMicroseconds(5); //Time for the sensor to react
digitalWrite(trig, HIGH);//Trigger ping
delayMicroseconds(10); //Give time to sensor to ping
digitalWrite(trig, LOW);
//Restets input pin to LOW in case its still high due to lack
//of echo
pinMode(echo, INPUT);
return (pulseIn(echo,HIGH, 25000)); // Max time 25 ms approx. 5 m
}
void setup() {
Serial.begin (9600);
pinMode(pinTrig, OUTPUT);
pinMode(pinEcho, INPUT);
}
void loop() {
unsigned long ping=0;
float dist=0;
for (int i=0; i<10; i++) {
p=ping(pinTrig, pinEcho);
dist += p/DIVM;
delay(25); // Not too short else error in measurement
}
dist /=10.0;
Serial.print("DIST: ");
Serial.println(dist);
delay(300);
}
@alexturco Your sketch as posted(using A0/A1) works fine for me. Check your pin wiring and if using a breadboard and jumper wires change the position and use different wires. Sometimes they can be flakey.