#include <Servo.h>
const int numChannels = 16;
// Define the control pins for the analog multiplexer
const int s0 = 2;
const int s1 = 4;
const int s2 = 7;
const int s3 = 8;
// Define the pin connected to the analog input (MUX output)
const int analogInputPin = A0;
// Define the pin connected to the servo
const int servoPin = 9;
// Array to store sensor values
int sensorValues[numChannels];
// Create a Servo object
Servo myServo;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set the control pins of the analog multiplexer as outputs
pinMode(s0, OUTPUT);
pinMode(s1, OUTPUT);
pinMode(s2, OUTPUT);
pinMode(s3, OUTPUT);
// Attach the servo to its pin
myServo.attach(servoPin);
}
void loop() {
// Read values from all channels of the analog multiplexer
for (int i = 0; i < numChannels; i++) {
selectChannel(i); // Select the channel to read from
// Read the value from the selected channel
sensorValues[i] = analogRead(analogInputPin);
// Add a small delay to stabilize the reading
delay(10);
}
// Print the sensor values
for (int i = 0; i < numChannels; i++) {
Serial.print("Channel ");
Serial.print(i);
Serial.print(": ");
Serial.println(sensorValues[i]);
delay(100);
}
// Map the potentiometer value (from channel 1) to the servo position (0-180 degrees)
int servoPos = map(sensorValues[1], 0, 1023, 0, 180);
// Move the servo to the mapped position
myServo.write(servoPos);
// Print the servo position
Serial.print("Servo Position: ");
Serial.println(servoPos);
// Delay to avoid overwhelming the serial monitor
delay(1000);
}
// Function to select a channel on the analog multiplexer
void selectChannel(int channel) {
boolean b0 = channel & 1;
boolean b1 = (channel >> 1) & 1;
boolean b2 = (channel >> 2) & 1;
boolean b3 = (channel >> 3) & 1;
digitalWrite(s0, b0);
digitalWrite(s1, b1);
digitalWrite(s2, b2);
digitalWrite(s3, b3);
// Add a small delay to ensure the channel selection is stable
delay(10);
}