I'm trying to connect 4 ultrasonic sensors HC-SR04 to Arduino UNO using a NXP's PCF8574P chip. If 4 sensors are connected to Arduino pins, everything's fine.
The problem appears when I try co bind them throught PCF8574P. The speed of response falls dramatically: almost 4 seconds to send signals and read response from the all 4 sensors.
What really takes time is pulseIn(). This is the place where I see the most of time being spent...
Here's the code:
#include <Wire.h>
#include "PCF8574.h"
PCF8574 pcf_us; //Ultrasonic sensors
//The matrix of pin assignments for the ultrasonic sensors (trig (OUTPUT), echo (INPUT))
int usPinMatrix[4][2] = {
{0, 4}, //0 (pin for trig), 4 (pin for echo)
{1, 5}, //1 (pin for trig), 5 (pin for echo)
{2, 6}, //2 (pin for trig), 6 (pin for echo)
{3, 7} //3 (pin for trig), 7 (pin for echo)
};
void setup() {
Serial.begin (9600);
Serial.println("Initializing device...");
Wire.begin();
//PCF8574P I2C address
/*
A0 A1 A2 address
- - - 0x20
+ - - 0x21
- + - 0x22
+ + - 0x23
- - + 0x24
+ - + 0x25
- + + 0x26
+ + + 0x27
*/
pcf_us.begin(0x21);
for (int i = 0; i <= 3; i++){
pcf_us.pinMode(usPinMatrix[i][0], OUTPUT);
pcf_us.pinMode(usPinMatrix[i][1], INPUT);
};
};
void loop() {
int us_pin, trigPin, echoPin, duration, distance;
for (int i = 0; i <= 3; i++){
Serial.print(usPinMatrix[i][0]);
Serial.print(") ");
Serial.print("Send sound... ");
pcf_us.digitalWrite(usPinMatrix[i][0], HIGH);
pcf_us.digitalWrite(usPinMatrix[i][0], LOW);
Serial.print("Switch off... Reading from ");
Serial.print(usPinMatrix[i][1]);
Serial.print("... ");
duration = pulseIn(usPinMatrix[i][1], HIGH);
distance = duration / 2 / 29.1;
Serial.print("Duration: ");
Serial.print(duration);
Serial.print(" s ");
Serial.print(distance);
Serial.println(" cm");
if (usPinMatrix[i][0] == 3) Serial.println("");
};
};
This is what I get when I run the code:
0) Send sound... Switch off... Reading from 4... [Waiting] Duration: 0 s 0 cm
1) Send sound... Switch off... Reading from 5... [Waiting] Duration: 0 s 0 cm
2) Send sound... Switch off... Reading from 6... [Waiting] Duration: 0 s 0 cm
3) Send sound... Switch off... Reading from 7... [Waiting] Duration: 0 s 0 cm
What am I doing wrong?