Skip to content

Instantly share code, notes, and snippets.

@nebs
Last active November 5, 2022 15:52
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nebs/125b56da1f9faa40eac2 to your computer and use it in GitHub Desktop.
Save nebs/125b56da1f9faa40eac2 to your computer and use it in GitHub Desktop.
Arduino 16-Channel Analog Multiplexer Reading
/*
This code relies on the fact that PORTB on the ATMega328 chip has consecutive pins
which we can take advantage of to set the channel on the mux.
This code has been tested with Sparkfun's 16-ch mux (https://www.sparkfun.com/products/9056).
*/
#define MUX_CH_COUNT 16 // Reduce this number if you use less channels
#define PIN_D_MUX_S0 8 // bit 7 of PORTB
#define PIN_D_MUX_S1 9 // bit 6 of PORTB
#define PIN_D_MUX_S2 10 // bit 5 of PORTB
#define PIN_D_MUX_S3 11 // bit 4 of PORTB
#define PIN_A_MUX_SIG 3 // This pin will read the input from the mux.
void setup() {
pinMode(PIN_D_MUX_S0, OUTPUT);
pinMode(PIN_D_MUX_S1, OUTPUT);
pinMode(PIN_D_MUX_S2, OUTPUT);
pinMode(PIN_D_MUX_S3, OUTPUT);
Serial.begin(9600);
}
void loop() {
for (byte i=0; i<MUX_CH_COUNT; i++) {
PORTB = (PORTB & B11110000) | i;
short val = analogRead(PIN_A_MUX_SIG);
// "val" holds the value for input "i", so you can insert your custom code here.
// Print the values...
Serial.print(i);
Serial.print(": ");
Serial.print(val);
Serial.print(" | ");
}
Serial.println("");
delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment