Code for ultrasonic sensors wont run correctly

So i just bought a Arduino Uno Wifi Rev 2, i originally had written some code to detect water level in a tank for the Arduino Uno but wanted to expand the program to send data to a CoAP server. But when i run the code on my Arduino Uno Wifi the code dont work correctly. The code works perfectly fine on my Arduino Uno but not on the Arduino Uno Wifi, any idea why?

//*  Water Level Detector For Multiple Sensors  *//

// Sensor ONE
#define trigPin1 7
#define echoPin1 6

long t = 0, h = 0, hp = 0, sensorONE;

void setup()
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);

// Sensor One
// Transmitting Pulse
void pulseONE(int trigPin,int echoPin)
  digitalWrite(trigPin, LOW);
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);
  // Waiting for Pulse
  t = pulseIn(echoPin, HIGH);
  // Calculating Distance
  h = (t / 2) / 29.1;

  h = h - 8; // Offset
  h = 23 - h;  // water height, 0 - 50 cm
  hp = h / 0.23;  // distance in %, 0-100 %


void loop() 
  pulseONE(trigPin1, echoPin1);
  sensorONE = hp;
  // Sending to Computer
  Serial.print("% Sensor One\n");

Please explain exactly what you mean by "dont work correctly".

So the code will calculate the distance to the bottom of the tank and then invert the number so it shows how full the tank is in % when you fill water in it. So on the Arduino Uno it will start out at 0% cause the tank is empty but on the Arduino Uno Wifi it starts out at 134% and never changes.

Hi. I can reproduce the issue. The issue seems to be caused by calling pulseIn() very soon after Serial.print().

The workaround I used is to call Serial.flush() at the start of your pulseONE function. That will cause the sketch to wait until the Serial transmit buffer is emptied before calling pulseIn().

I wanted to give you the workaround ASAP, but I'm going to investigate this issue further and report it to the Arduino developers if appropriate, I will update this thread if there's any new information.

That's awesome! Thank you so much for the help! I tried the workaround and it works like a charm.

You're welcome. I'm glad to hear it's working!

I submitted a bug report to the Arduino megaAVR Boards repository:

The alternative workaround I found is to call noInterrupts() before pulseIn() and then interrupts() after.