Ultrasonic range sensor ping() gives "-1"

Has anyone seen the problem with Sparki where the ultrasonic range or distance sensor gives output values of “-1” sometimes? I see this problem most often when the servo directs Sparki’s head to the right or left. It could be showing normal range values but then spikes to -1 every so often, worst case of 1 out of every 2 data values. If I keep the head centered, it seems to work fine.

Its not unusual for it to happen sometimes (its the indication of a bad reading), but 1 of 2 is pretty bad. How often is it when the servo isn’t active?

Out of curiosity, do you get this problem when the USB is plugged in? Is the servo straining when its turned left or right (hitting up against anything)? If so, it might be a low-battery issue.

I am having a similar but worse problem. The original issue was an intermittent -1. Now it is -1 all the time. I tried another HC-SR04 and another Sparki to sensor cable. Neither made any difference. The servo is not turning. It happens regardless of running on batteries or USB power.

Motherboard issue??

Thanks

Ok, it is something I am doing wrong in the code as an attempt to filter out the -1 readings. The code without the filter is give normal readings with occasional -1 values. The code with the filter is setting the ping to -1 all the time.

Here is my attempt at filtering the reading

  ping = sparki.ping(); 
  
  if (ping = -1)
  {
    filteredPing = 99;                      
  }
  else
  {
    filteredPing = ping;
  }

So to evaluate the statement (to check one value against another), you need to use double equal signs, ‘==’. Just using one will make ping equal to the value. Your code is turning all incoming signals into -1.

Try this instead:

int filteredPing;
ping = sparki.ping();
  
  if (ping == -1)
  {
    filteredPing = 99;                      
  }
  else
  {
    filteredPing = ping;
  }

Thank you, I totally forgot about that == vs = thing. I will fix my code and give it a try.

Thanks again,

That fixed it, much better now. Thanks for the fast answer.

Regards,