Ultrasonic Sensor with Explorer HAT Pro


#1

I bought a Sparkfun ultrasonic sensor yesterday to use with my Explorer HAT robot. I tested it on an Arduino UNO with this sample code from Sparkfun:

void setup()
{
  // initialize serial communications
  Serial.begin(9600); 
}

void loop()
{
  int sensor, inches, x;
  
  // read the analog output of the EZ1 from analog input 0
  sensor = analogRead(0);
  
  // convert the sensor reading to inches
  inches = sensor / 2;
  
  // print out the decimal result
  Serial.print(inches,DEC);
  
  // print out a graphic representation of the result
  Serial.print(" ");
  for (x=0;x<(inches/5);x++)
  {
    Serial.print(".");
  }
  Serial.println("|");

  // pause before taking the next reading
  delay(100);                     
}

The sensor worked fine with the Arduino, outputting an accurate whole number. Then I connected it to the Explorer HAT Pro with 5V, GND, and Analog 1. I used this code:

import explorerhat as eh
import time

while True:
    sensor = eh.analog.one.read()
    inches = sensor / 2
    print(inches)
    time.sleep(0.1)

I am getting a different output with the Explorer HAT, a decimal number that is far different than the Arduino. Is my Python program no good, or does the Explorer HAT’s analog inputs operate differently than an Arduino’s?


#2

Arduino Uno has a 10-bit ( 2 ^ 10 - 1 ) ADC, which will measure 0v to 5v with a number from 0 to 1023.

Explorer HAT has a 12-bit ADC ( 2 ^ 12 - 1 ), which will measure 0v to 5v with a number from 0 to 4095 ( but this is represented as a decimal in Python as it roughly maps to voltage )

So if 5v is 4095, that’s one millivolt granularity, approximately. ( it’s actually 1.221, millivolts granularity ).

Arduino has a granularity of about 5 millivolts ( well 4.8 and change ).

If 1 inch = Arduino reading / 2 then that would suggest 10mv per inch of resolution on the sensor. Although dividing by 2 is a very rough way to convert the Arduino ADC reading to inches that works around Arduino’s slow decimal handling.

To get inches out of Explorer HAT Pro that means you need to divide the output by about 8.19. Since Explorer HAT already divides it by 1000, you’ll need to do this:

So try:

import explorerhat as eh
import time

while True:
    sensor = eh.analog.one.read()
    inches = sensor / 0.00819
    print(inches)
    time.sleep(0.1)

Assuming your sensor isn’t clamped to a 10mv step, Explorer HAT Pro should give you a resolution of a tenth of an inch, whereas the Arduino can only tell you down to half an inch.

TLDR: inches = sensor / 0.00819


#3

Thanks! I’m building a self driving robot. Maybe I’ll post something about it in the Projects forum when its done! :-)