// Define the control pins for the 74HC4067 multiplexer
const int S0 = 11;
const int S1 = 10;
const int S2 = 9;
const int S3 = 8;
// Define the trigger pins for the ultrasonic sensors
const int trigPins[] = {6, 7}; // Adjust according to the number of sensors
// Common I/O pin from the multiplexer connected to an analog input
const int echoPin = A0;
// Number of sensors
const int numSensors = sizeof(trigPins) / sizeof(trigPins[0]);
void setup() {
Serial.begin(9600);
// Set the control pins as outputs
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
// Set the trigger pins as outputs
for (int i = 0; i < numSensors; i++) {
pinMode(trigPins[i], OUTPUT);
}
// Set the echo pin as input
pinMode(echoPin, INPUT);
}
void loop() {
for (int i = 0; i < numSensors; i++) {
// Select the multiplexer channel
selectMuxChannel(i);
// Read distance from the current sensor
long duration = readUltrasonic(trigPins[i]);
int distance = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print("Sensor ");
Serial.print(i);
Serial.print(": ");
Serial.print(distance);
Serial.println(" cm");
delay(100); // Small delay between readings
}
}
void selectMuxChannel(int channel) {
digitalWrite(S0, bitRead(channel, 0));
digitalWrite(S1, bitRead(channel, 1));
digitalWrite(S2, bitRead(channel, 2));
digitalWrite(S3, bitRead(channel, 3));
}
long readUltrasonic(int trigPin) {
// Set the trigger pin high for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin
long duration = pulseIn(echoPin, HIGH);
return duration;
}
Loading
cd74hc4067
cd74hc4067