Challenge in ultrasonic distance measurement using PCF8575(I2C)

When, I read the distance using ultrasonic sensor(HC-SR04) in the following scenario, I keep getting 0 as value and not getting correct measurement.

  1. Using Arduino UNO
  2. Due to Port constraints, i am using PCF8575 I2C board expander (As slave).
  3. The ultrasonic sensor(HC-SR04) is connected with PCF8575 I2C board.
  4. Also, i am using NewPing library for ultrasonic sensor distance measurement.

if we could not achieve this functionality using NewPing library, please suggest any alternative approach.

Please refer the code below:

#include "Arduino.h"
#include "NewPing.h"
#include "PCF8575.h"

#define Trigger P6 
#define Echo     P5

#define MAX_DISTANCE 400

PCF8575 pcf8575(0x20);
volatile int Distance = 0;

void setup() {

  Serial.begin(9600);
  pcf8575.pinMode(P6,OUTPUT);
  pcf8575.pinMode(P5,INPUT);
  pcf8575.begin();

}

void loop() {

  NewPing sonar(Trigger, Echo, MAX_DISTANCE);
  Distance = sonar.ping_cm();
  String CM = " cm - sensor";
  Serial.println(Distance + CM);
}

I think the sonar library needs direct access to the port pin to measure the echo timing.

If you can use the port expander for other purposes, freeing up the sonar pins, that solves the problem.

If you look at PCF8575.h, you will see that the constants P5 and P6 are defined as 5 and 6 so the NewPing library will be using the Uno pins 5 and 6 to attempt sonar, not pin 5 and 6 on your port expander.

As @jremington says, you can't use expansion pins for sonar.

1 Like

In general, you can't pass expansion pin numbers to any function expecting Arduino pin numbers.

Use the expansion for pins which you do nothing to but pinMode(), digitalRead(), or digitalWrite(). Those will work by changing the calls to pcf8575.pinMode(), pcf8575.digitalRead(), and pcf8575.digitalWrite(). Hopefully, that will free up two Arduino pins you can use for Trigger and Echo.

Does the pcf8575 library support other Arduino functions? If there is a pcf8575.pulseIn() you could use that to read the Echo pin.

1 Like

Thanks for giving more clarity. As the PCF8575 does not have pulseIn() function, I think I need to see some other alternative.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.