Problem summary
I have the Arduino nano 33 IoT with the ultrasonic sensor HC-SR04.
I just want to measure the distance between the sensor and an object.
But when an object gets closer, the value/distance increases...
The code
The code I upload:
#define ULTRASONIC_TRIG_PIN 12 // pin trig is D11
#define ULTRASONIC_ECHO_PIN 11 // pin echo is D12
long duration;
float distance;
void setup() {
pinMode(ULTRASONIC_TRIG_PIN, OUTPUT);
pinMode(ULTRASONIC_ECHO_PIN, INPUT);
Serial.begin(9600);
delay(1500);
}
void loop() {
digitalWrite(ULTRASONIC_TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(ULTRASONIC_TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(ULTRASONIC_TRIG_PIN, LOW);
duration = pulseIn(ULTRASONIC_ECHO_PIN, HIGH);
/* two ways to measure distance */
//distance = duration * 0.034 / 2;
distance = (duration/2) / 29.1;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(100);
}
Wiring
I have the nano 33 IoT wired with the sensor like so, but without a breadboard:
My pictures:
Serial monitor/values
This is wat shows up in the serial monitor:
When I push an object closer, the distance goes up to 140 cm.
What did I already tried?
- different pins (combinations)
- different ports
- different baud rates
- different data types(int, long, float) for the duration and distance
- different locations, because other objects could interfere, but also temperature, humidity, etc
Anyone got an idea where this goes wrong?



